4,563,341 th visitor since 2017.2.1 ( Today : 235 )
Programming
No. 699
Name. swindler
Subject. Double-checked locking and the Singleton pattern
Main Cate. Java
Sub Cate. Java
Date. 2013-02-22 14:25
Hit. 2368 (211.36.27.3)
File.

import java.util.*;
class Singleton
{
private static Singleton instance;
private Vector v;
private boolean inUse;

private Singleton()
{
v = new Vector();
v.addElement(new Object());
inUse = true;
}

public static Singleton getInstance()
{
if (instance == null) //1
instance = new Singleton(); //2
return instance; //3
}
}



Thread 1 calls the getInstance() method and determines that instance is null at //1.

Thread 1 enters the if block, but is preempted by thread 2 before executing the line at //2.

Thread 2 calls the getInstance() method and determines that instance is null at //1.

Thread 2 enters the if block and creates a new Singleton object and assigns the variable instance to this new object at //2.

Thread 2 returns the Singleton object reference at //3.

Thread 2 is preempted by thread 1.

Thread 1 starts where it left off and executes line //2 which results in another Singleton object being created.

Thread 1 returns this object at //3.





public static Singleton getInstance()
{
if (instance == null)
{
synchronized(Singleton.class) { //1
if (instance == null) //2
instance = new Singleton(); //3
}
}
return instance;
}


Thread 1 enters the getInstance() method.

Thread 1 enters the synchronized block at //1 because instance is null.

Thread 1 is preempted by thread 2.

Thread 2 enters the getInstance() method.

Thread 2 attempts to acquire the lock at //1 because instance is still null. However, because thread 1 holds the lock, thread 2 blocks at //1.

Thread 2 is preempted by thread 1.

Thread 1 executes and because instance is still null at //2, creates a Singleton object and assigns its reference to instance.

Thread 1 exits the synchronized block and returns instance from the getInstance() method.

Thread 1 is preempted by thread 2.

Thread 2 acquires the lock at //1 and checks to see if instance is null.

Because instance is non-null, a second Singleton object is not created and the one created by thread 1 is returned.




[바로가기 링크] : http://coolx.net/cboard/develop/699



Name
Password
Comment
Copyright © 1999-2017, swindler. All rights reserved. 367,611 visitor ( 1999.1.8-2004.5.26 ), 2,405,771 ( -2017.01.31)

  2HLAB   2HLAB_Blog   RedToolBox   Omil   Omil_Blog