The practice of Java Singleton mode

Source: Internet
Author: User

Singleton mode is one of the most common and important design patterns in Java design patterns.

The simplest notation is:

 Public classTestsingleton {Private StaticString ourinstance =NULL; //Privatization Constructor    PrivateTestsingleton () {}//provides static methods for external access     Public StaticString getourinstance () {if(Ourinstance = =NULL) {ourinstance= "Singleton mode assignment succeeded!!!" ";        System.out.print (ourinstance); }        returnourinstance; }}

This way of writing a singleton mode is thread insecure, the following code to simulate the multi-threaded concurrency, code execution:

 Public classTest {/*** thread Pool*/   Final StaticExecutorservice ThreadPool =Executors.newcachedthreadpool (); /*** Concurrency number*/   Private Final Static intConcurrent_count = 10; /*** Sync Tool class? */   Final StaticCountdownlatch locks =NewCountdownlatch (Concurrent_count);  Public Static voidMain (string[] args) { for(inti = 0; i < Concurrent_count; i++) {Threadpool.execute (NewRunnable () {@Override Public voidrun () {Locks.countdown ();                Testsinleton.getourinstance ();        }            } ); }    }}

The code is very simple, with the thread pool executing concurrent_count tasks, each task executing to

Locks.countdown ()

is blocked, when the number of blocked tasks reaches Concurrent_count, all tasks are executed simultaneously, thus simulating multiple users ' concurrent scenarios. (How to use Countdownlatch)

Think: If the single-mode thread is safe, then the console will print only once: the single-mode assignment succeeds!!!

Run the program 3 times to see the console output:

" C:\Program Files\java\jdk1.8.0_101\bin\java " ...  exit0
" C:\Program Files\java\jdk1.8.0_101\bin\java " ...  exit1
" C:\Program Files\java\jdk1.8.0_101\bin\java " ...  exit1

It's not like this, and it's easy to see the variable being assigned multiple times. Therefore, the above singleton mode is thread insecure.

Think about why this is happening?

if (ourinstance = = null) may be executed concurrently because of a multiuser concurrency operation, multiple thread judgments (ourinstance = = null) are true if Ourinstance is empty.

To modify the code:

 Public classTestsinleton {Private StaticString ourinstance =NULL; //Privatization Constructor    PrivateTestsinleton () {}//provides static methods for external access     Public StaticString getourinstance () {if(Ourinstance = =NULL){           synchronized(Testsinleton.class){                if(Ourinstance = =NULL) {ourinstance= "single-mode copy success!!!" ";                System.out.print (ourinstance); }            }            //ourinstance= "Single case mode assignment success!!!            "; //System.out.print (ourinstance);        }        returnourinstance; }}

For the first time, most of the threads are blocked out. Continuing down is a synchronized method that only allows single-threaded execution, so there is no case where multiple threads are executed at the second time.

Run the program multiple times to view the console:

" C:\Program Files\java\jdk1.8.0_101\bin\java " ...  exit0

The discovery will only print once.

The practice of Java Singleton mode

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.