[Introduction]
Recently I was joined one interesting discussion with my colleagues "What's details for "new" operations of Java? Putting "new" inside or outside synchronized block?". I surprisingly found nobody could telling correctly about that. So here I listed the possible semantics about "new".
A a = new A();
1. Loading class definition of Class "A"
* Using class loader of current thread trying to load class "A"
* Reading the class information into memory (it was "Native Memory" or "VM heap" ? - My answer will be both)
* Transforming the class information to runtime JIT codes let JVM could executing them.
2. Calculate the initial memory consumption for the instance of class "A"
* Calculation contains:
** Static Variables
** None-static Variables
note: Please remember the differences between reference and object. Otherwise you cannot understanding the concept.
3. Analysis the hiercharies of Class "A". Then loop the step 4, 5, 6 until all the class of hiercharies were touched:
4. Use the size be calculated by previous step and use system level "C" function "malloc" allocate the memeory of OS.
* Malloc is not thread safe except several flag need to be set
* Malloc implementation is OS depend.
note: Sun already cover those issues. 99% is thread safe.
5. Create the reference in the stack, and make the reference point to the Object.
6. Calling the object constructor method and do initialization
* Static initialization
* None-static initialization
* Constructor body
note: any of above path could be none-thread safe victim.
So here the answer for "new" is thread safe or not is uncentainty or Dependes class/object instantiation need to be thread-safe.
[Back to topic]
Then the strategy for putting "new" operator inside or outside synchronized block will be:
* Always putting the "new" operator inside the synchronized block except when
* Only if you understand or design class completely and already make sure the whole path is thread safe, you can put the "new" operator outside synchronized block.
References:
"http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/LinkedBlockingQueue.java?view=log reversion 1.54
move value allocation outside the lock scope."
Comments