Singleton mode-detail-awareness

Source: Internet
Author: User

Purpose:

In the single-piece mode, you must control the instance creation process to ensure that all the customer programs use the same instance created.

Notes

1. synchronization problems caused by lazy initialization:

Singleton class, used sleep to enlarge the problem.

package com.jue.singleton;public class Singleton {private static Singleton instance;private static int index = 0;private Singleton() {System.out.println("-------------------------index: " + (index++));}public static Singleton getInstance() {if (instance == null) {try{Thread.sleep(1000);}catch(Exception e){}instance = new Singleton();}return instance;}}

Mythread class

package com.jue.singleton;public class MyThread implements Runnable{@Overridepublic void run() {// TODO Auto-generated method stubSystem.out.println("MyThread run()");Singleton myInstance = Singleton.getInstance();}}

Main method:

package com.jue.singleton;public class TestSingleton {/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubnew Thread(new MyThread()).start();Singleton instance = Singleton.getInstance();}}

Result:

Mythread run ()
------------------------- Index: 0
------------------------- Index: 1

Solution

A. Lock

public static synchronized Singleton getInstance() {if (instance == null) {try{Thread.sleep(1000);}catch(Exception e){}instance = new Singleton();}return instance;}

B. It is created during initialization.

private static Singleton instance = new Singleton();private static int index = 0;private Singleton() {System.out.println("-------------------------index: " + (index++));}public static Singleton getInstance() {return instance;}

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.