Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "this" escape the constructor in Java?

Tags:

I've heard about this happening in non thread-safe code due to improperly constructed objects but I really don't have the concept down, even after reading about in in Goetz's book. I'd like to solidify my understanding of this code smell as I maybe doing it and not even realize it. Please provide code in your explanation to make it stick, thanks.

like image 527
non sequitor Avatar asked Oct 19 '09 12:10

non sequitor


People also ask

Can I pass this in constructor?

You can pass an argument of any data type into a method or a constructor. This includes primitive data types, such as doubles, floats, and integers, as you saw in the computePayment method, and reference data types, such as classes and arrays.

How do you stop a constructor in Java?

The only way to "stop" a constructor is to throw an exception. Bearing in mind of course that the caller is supposed to "know" about this exception and be able to handle the case where the constructor fails.

Can we use this keyword outside constructor?

The keyword “this” in Java can be applied to instance variables, constructors, and methods. It is used only inside the member functions of the class. In other words, it can only be used within the non-static method of a class. This reference cannot be used outside the class.


1 Answers

Example : in a constructor, you create an event listener inner class (it has an implicit reference to the current object), and register it to a list of listener.
=> So your object can be used by another thread, even though it did not finish executing its constructor.

     public class A {        private boolean isIt;       private String yesItIs;        public A() {         EventListener el = new EventListener() { ....};         StaticListeners.register(el);         isIt = true;         yesItIs = "yesItIs";       }      } 

An additional problem that could happen later : the object A could be fully created, made available to all threads, use by another thread ... except that that thread could see the A instance as created, yesItIs with it "yesItIs" value, but not isIt! Believe it or not, this could happen ! What happen is:

=> synchronization is only half about blocking thread, the other half is about inter-thread visibility.

The reason for that Java choice is performance : inter-thread visibility would kill performance if all data would be shared with all threads, so only synchronized data is guaranteed to be shared...

like image 95
KLE Avatar answered Oct 10 '22 04:10

KLE