Does GWT create asynccallback in constructor safe?

Assuming the constructor works in the client side of the code (the one that translates to javascript). The onSuccess callback method modifies the class instance variables. The callback is implemented as an anonymous class, so an instance of the outer class can be accessed using OuterClass.this.

Usually in simple Java, we should not do something like this, because in this case the 'this' link may go away before the object is completed.

But does this also apply when Java code is translated into Javascript? I assume that javascript code is executed by a single thread in a web browser, so this should not be a problem (single thread => visibility problems)?

+4
source share
2 answers

AsyncCallback itself is just a class. When you send an RPC request in production mode, you are guaranteed that the result will arrive asynchronously through XmlHttpRequest; in compiled javascript it is 100% impossible to skip the link before the construction is completed, as the callback will be called in a separate javascript execution stack.

However, in gwt-dev mode, things that should be asynchronous are not always the case. Personally, I abandoned gwt-dev over super-dev-mode and used gwt-dev when I really need a java debugger, so I can’t tell you exactly whether it will be protected from construction problems or not (check it and find out !).

If you do not send any requests in the constructor, you will be 100% safer. Simply creating an asynchronous callback will only cause problems if you subsequently access OuterClass. This is unsafe, no matter which classes are involved.

+2
source

On the one hand, you are right - the problem cannot be caused by a separate thread, since JavaScript is single-threaded.

Callback events will certainly be handled by an event handler that starts after the current event handler (the one that builds the current object) is completed. Therefore, they will only see a fully constructed object.

On the other hand, you don't need threads at all to use the underlying problem. Here is a simple example:

final A a = new A(); final B b = new B(a); 
 public class A { private B b; public void setB(final B b) { this.b = b; } public void letBSaySomething() { b.saySomething(); } } 
 public class B { private A a; private final int some; public B(final A a) { this.a = a; a.setB(this); a.letBSaySomething(); some = 55; a.letBSaySomething(); } public void saySomething() { RootPanel.get().add(new Label("Hello " + some)); } } 

The result is a conclusion

 Hello 0 Hello 55 

(although "some" are final). This happens both in GWT (compiled / uncompiled) and in simple Java programs.

+3
source

All Articles