Singleton mode-We are often used, the following are lazy loading two implementations, only when learning!
Scenario One: Synchronized
private static Singletonlazy instance = NULL; Private Singletonlazy () {}; public static Singletonlazy getinstance () { if (null = = Instance) { CreateInstance (); } return instance; }
Private synchronized static Singletonlazy CreateInstance () { if (null = = Instance) { Instance = new Singletonlazy (); } return instance; }
|
Scenario Two: Lock ( recommended )
private static Singletonlazylock instance = NULL; Private Singletonlazylock () {};
Plus read/write lock private static Readwritelock rwl = new Reentrantreadwritelock ();
/** * Singleton mode lazy loading concurrency * @return */ public static Singletonlazylock getinstance () { Rwl.readlock (). Lock (); try { if (null = = Instance) { Rwl.readlock (). Unlock (); Rwl.writelock (). Lock (); if (null = = Instance) { Instance = new Singletonlazylock (); } Rwl.writelock (). Unlock ();
} Rwl.readlock (). Lock (); } catch (Exception e) { E.printstacktrace (); } finally { Rwl.readlock (). Unlock (); }
return instance; }
|
Although the single case is not as trivial as the cache write, if adding sychonize on the GetInstance method will greatly affect performance, the single-instance write will only be written on the first use.
Use read-write lock operation, basically all on the reading lock, no impact on other thread access!
This article is from the "Suck on self-renewal" blog, please be sure to keep this source http://wyong.blog.51cto.com/1115465/1764864
Java Singleton mode-lazy loading