| Back to logs list
Reprinted from 304510237 at 10:37 on July 23, 2010 Reading (loading. ..) Comments (0) Category: Technical Articles
down here not to discuss the application of single-case model what occasion, the main delay is that caused by loading a series of single-case model, as well as how to solve.
the following delay load problem on the analysis of reference from:
the above mentioned model of delay in loading a single case double-checked locking (referred to DCL), ie double lock failed, and the solutions for the DCL.
first look at the delay of loading a single case code:
synchronized block around the creation of the single object case, it seems that the delay is a typical load singleton pattern. But there is a problem, assume that thread A is running to / / 1 when thread B is preempted the cpu, and run to / / 3, then thread A will continue to repeat to create objects, leading to the destruction of a single cases of rules.
ok, then we do a modification, the code becomes this:
we see that, in addition to / / 1 for a non-null check in the synchronized block of code / / 3 and added a check, which is double-checked locking (DCL), so as to avoid the above other threads to create singleton objects repeated the question, looks like perfect.
Unfortunately, even the DCL may also fail.
instance = new Singleton ();
simple line of code to create the object to be divided into steps:
1) Allocate memory,
2) invoke constructor,
3) give reference
If this is the order of steps 1), 2), 3) that no problem, but the JIT compiler does not guarantee 2) and 3) order, so may become a 1), 3), 2) Then take a look at what might happen:
thread A first enter the synchronized block, the implementation instance = new Singleton (), then instance only to get a ref, but the constructor has not yet implemented, to exit the synchronization block;
Cut the thread B, then a non-null instance of (the above thread has been assigned A ref), then to return the instance, and this instance is not initialized by constructor, and then access the instance will cause an error.
This is JITcompilers the out-of-order issue, led to the order of initialization and unpredictable variable assignment, resulting in more problems.
more detailed analysis on the DCL:
Well, to all the problems listed here,
paul smith wallets sale, and have been able to see the singleton pattern has become so cumbersome to use delay loading and worrying.
first load delay aside, for the singleton, if the do not care whether the delay must be loaded, the easiest way is nothing less than the static load:
do both easy and safe.
or delay to see how to improve the singleton pattern is loaded:
only call the getInstance method, using LazyFoo class, will initialize the LazyFoo, also reached the purpose of lazy, but not jdk5.