Several ways to implement Java singleton pattern

Source: Internet
Author: User

Singleton mode many books are written in this way:

public class SingleTon1 {private SingleTon1 () {}private static SingleTon1 instance = Null;public static SingleTon1 Getinsta nCE () {if (instance = = null) {instance = new SingleTon1 ();} return instance;}}

  But the actual development is not so written, because there is a serious problem, multi-threaded concurrent access, may produce multiple instances!!

Here are a few common methods:

1. UseSynchronized keywords
Package Singleton;public class SingleTon1 {private SingleTon1 () {}private static SingleTon1 instance = null;//Multithreading problem Solution One, But the efficiency is not high! Because every call will be locked! public static synchronized SingleTon1 getinstance () {if (instance = = null) {instance = new SingleTon1 ();} return instance;} public void print () {System.out.println ("thread_id:" +thread.currentthread (). GetId ());} private static Object object = new Object ();//A clever way to lock only when NULL, and then not add public static SingleTon1 GetInstance2 () {if ( instance = = null) {synchronized (object) {instance = new SingleTon1 ();}    } return instance;}}
2. Add lock
Package Singleton;import Java.util.concurrent.locks.reentrantlock;public class SingleTon2 {    private SingleTon2 () {}    private static Reentrantlock lock = new Reentrantlock ();p rivate static SingleTon2 instance = Null;public void print () {System.out.println ("thread_id:" +thread.currentthread (). GetId ());}    public static SingleTon2 GetInstance2 () {if (instance = = null) {Lock.lock (); if (instance = = null) {  //Note here to judge!! Instance = new SingleTon2 ();}    Lock.unlock ();} return instance;}}
3. Use static variables:
Package Singleton;public class SingleTon3 {public    static void print () {System.out.println ("thread_id:" + Thread.CurrentThread (). GetId ());}    public static Nested getnested () {return nested.instance;}    This is a singleton created class    static classes nested{      private Nested () {    }    static Nested instance = new Nested ();}    }

These are the common patterns for creating singleton:

Test code:

Package Singleton;import Singleton. Singleton3.nested;public class Test2 {public static void main (string[] args) {//TODO auto-generated method stubnested Sin Gleton; myrunnable mm = new myrunnable (); Myrunnable m1 = new myrunnable (); Myrunnable2 m2 = new Myrunnable2 (); new Thread (M1). Start (); new Thread (m2). Start (); if (M1.singleton = = M2.singleton) {  //Is the same System.out.println ("is the same");} Else{system.out.println ("Not the Same");}}} Class Myrunnable implements runnable{nested Singleton; @Overridepublic void Run () {//TODO auto-generated method Stubsingl Eton = singleton3.getnested (); Singleton3.print ();}} Class Myrunnable2 implements runnable{nested Singleton; @Overridepublic void Run () {//TODO auto-generated method stubsing Leton = singleton3.getnested (); Singleton3.print ();}    }

Output:

is the same
Thread_id:11
Thread_id:10

Several ways to implement Java singleton pattern

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.