Java Singleton mode-lazy loading

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.