A single example has a variety of ways of writing, this example is a lazy type of a single example. What you need to be aware of in a high Concurrency environment is:
1. It is necessary for a singleton to create multiple instance objects when accessing and invoking their corresponding getinstance methods concurrently. Lock
2. The use of synchronized is a better solution, the advantage is that the code is concise, the disadvantage is that when throwing an exception can not handle the maintenance of the system in good condition.
3. The display of the lock setting is a good solution.
The code to use lock is as follows:
Package demo;
Import Java.util.concurrent.locks.Lock;
Import Java.util.concurrent.locks.ReentrantLock;
/** *
Reference use
* @author watson_xu
* @date 2012-1-8 PM 04:31:09 * * Public
final class Singletoncontext {
private static Singletoncontext sc = null;
Private Singletoncontext () {
}
private static lock lock = new Reentrantlock ();
public static Singletoncontext getinstance () {
if (sc = null) {
lock.lock ();
if (sc = = null) {
try{
sc = new Singletoncontext ();
} finally {
lock.unlock ()
;
}}} return
SC;
}
When using synchronized, the code is as follows:
Package demo;
/** *
Reference Use
*
* * @author watson_xu
* @date 2012-1-8 PM 04:31:09 * * Public
Final class Singletoncontext {
private static singletoncontext sc = null;
Private Singletoncontext () {
} public
static synchronized Singletoncontext getinstance () {
if (null = SC {
sc = new Singletoncontext ();
}
return new Singletoncontext ();
}
See more Java syntax, you can pay attention to: "Thinking in the Java Chinese manual", "JDK 1.7 reference manual in English," "JDK 1.6 API Java Chinese Reference manual", "JDK 1.5 API Java Chinese Reference manual", also hope that everyone Support the cloud-dwelling community.