Java Singleton pattern combined with the new idea of Juc atomic class eruption

Source: Internet
Author: User

Singleton mode is one of 23 design patterns, about its introduction, has been countless, the general online implementation of the way is nothing but what lazy type, a hungry man type, internal class, enumeration, volatile plus double check lock and so on, today I think of a new way of realization, Using the atomic class provided by J.U.C, the code is as follows:

class SingleTon {    privatestaticnew AtomicReference<>();    privateSingleTon() {    }    publicstaticgetInstance() {        while (reference.getnull) {            reference.compareAndSet(nullnew SingleTon());        }        return reference.get();    }}

Test:
1. Test Thread class

 class testthread extends Thread {Hashset<singleton> HashSet;BooleanFlagintNumber PublicTestthread (hashset<singleton> HashSet,BooleanFlagintNumber) { This. HashSet = HashSet; This. flag = Flag; This. Number = number; } @Override Public voidRun () {if(flag) {testthread[] threads =NewTestthread[number]; for(inti =0; I < number; i++) {Threads[i] =NewTestthread (HashSet,!flag,0); } for(inti =0; I < number;            i++) {Threads[i].start ();        }} hashset.add (Singleton.getinstance ()); System.out.println ("Current hashset size:"+ hashset.size ()); }}
    1. Test example
HashSet<SingleTon> hashSet = new HashSet<>();        50;        TestThread[] threads = new TestThread[number];        fori0ii{            threads[i] = new TestThread(hashSet, true, 200);        }        fori0ii{            threads[i].start();        }   

However, the results are not clear, and in some cases, the results are printed as follows:

2
2
2
2
2
2
2
2
2
2
2
2
2
2

The instant sadness, originally thought discovers the New world, the result, hey! Do not forget, what is the problem? Why would there be two singleton?
OK, modify the test method:

Hashset<singleton> HashSet =NewHashset<> ();intNumber = -; testthread[] Threads =NewTestthread[number]; for(inti =0; I < number; i++) {Threads[i] =NewTestthread (HashSet,true, $); } for(inti =0; I < number;        i++) {Threads[i].start (); } thread.sleep ( the);if(Hashset.size () >1) { for(SingleTon Singleton:hashset) {System. out. println (SingleTon +""+ Singleton.hashcode ()); }        }

Although the results are still 2,3,1, the final printing information shows that there is only one singleton instance in HashSet. What is this for? Because the hashset is non-thread-safe, in a multithreaded environment, prone to state inconsistencies. Let's change to Copyonwritearrayset and try again.

 class testthread extends Thread {Copyonwritearrayset<singleton> HashSet;BooleanFlagintNumber PublicTestthread (copyonwritearrayset<singleton> HashSet,BooleanFlagintNumber) { This. HashSet = HashSet; This. flag = Flag; This. Number = number; } @Override Public voidRun () {if(flag) {testthread[] threads =NewTestthread[number]; for(inti =0; I < number; i++) {Threads[i] =NewTestthread (HashSet,!flag,0); } for(inti =0; I < number;            i++) {Threads[i].start ();        }} hashset.add (Singleton.getinstance ());    System.out.println (Hashset.size ()); }}

OK, everything is fine.
You are welcome to point out the wrong place.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java Singleton pattern combined with the new idea of Juc atomic class eruption

Related Article

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.