Thread security issues in singleton mode and thread Security Issues in Mode

Source: Internet
Author: User

Thread security issues in singleton mode and thread Security Issues in Mode

What problems does a single meeting bring about?

If multiple threads call this instance at the same time, thread security issues may occur.

 

Where is a singleton generally used?

The purpose of a singleton is to ensure that there is only one instance at runtime. The most common scenarios include getting database connections or creating BeanFactory operations in Spring, these operations call their methods to execute a specific action.

 

First, let's take a look at the following two models: the lazy Chinese Style

 

Public class MyFactory {// create immediately in the hungry Chinese Style // private static MyFactory instance = new MyFactory (); // public static MyFactory getInstance () {// return instance; //} // when used in lazy mode, you do not need to create it (with thread security issues) private static MyFactory instance = null; public static MyFactory getInstance () {instance = new MyFactory (); return instance ;}}

 

 

The following describes several methods to solve thread security:

Method 1: A Private Static internal class instanceHolder is added to MyFactory. The external interface is the getInstance () method, that is, only in MyFactory. when getInstance () is used, the instance object is created without synchronization. Only one instance is guaranteed, and the Lazy feature is also available.

public class MyFactory {        private static class instanceHolder {               public static MyFactory instance = new MyFactory();           }                 public static MyFactory getInstance() {               return MyFactory.instanceHolder.instance;           }   }

Test code

import static org.junit.Assert.*;import org.junit.Test;public class MyFactoryTest {    @Test    public void testGetResource() {        MyFactory mf1 = MyFactory.getInstance();        MyFactory mf2 = MyFactory.getInstance();        System.out.println(mf1 != null);//true        System.out.println(mf1 == mf2);//true    }}

Method 2: (lazy)

This method does not use synchronization, and ensures that the reference of MyFactory is created only when the static getInstance () method is called,

  private static MyFactory instance = new MyFactory();
public static MyFactory getInstance() {   return instance; }

Test code: Same method 1

 

Method 3: synchronized is usually used to lock the entire method, which is resource-consuming. In fact, this code instance = new MyFactory () may cause multi-thread access problems ();

To reduce resource consumption, just lock this sentence. The two threads concurrently enter the if statement that determines whether the instance is null for the first time. A thread obtains the lock and executes the new operation, another thread is blocked,

After the first thread completes the new operation, it is not safe for the second thread to directly perform the new operation. In order to avoid the second new operation, add the second condition judgment, both the second check

    private static MyFactory instance;    public static MyFactory getInstance(){        if(instance == null){            synchronized (MyFactory.class) {                if(instance == null){                    instance = new MyFactory();                }            }        }        return instance;    }    

Test code in the same way as method 1

 

 

 

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.