VolatileSingleton.java
/*
* Copyright@ 2011 www.egtry.com
*/
package egtry.thread;
///volatile long or double variables are reads/writes atomic
public class VolatileSingleton extends Thread {
private static VolatileSingleton _instance=null; //need to be volatile
private static volatile int counter=0;
public static void main(String[] args) {
int n=100;
VolatileSingleton[] list=new VolatileSingleton[n];
//create threads
for(int i=0; i<n; i++) {
VolatileSingleton t=new VolatileSingleton();
list[i]=t;
}
//start threads
for(int i=0; i<n; i++) {
VolatileSingleton t=list[i];
t.start();
}
//let all theads finish
for(int i=0; i<n; i++) {
VolatileSingleton t=list[i];
try {
t.join();
} catch (InterruptedException e) {
System.out.println("InterruptedException ");
}
}
System.out.println("total instance: "+VolatileSingleton.counter); //there is a possible that more than 1 instances are created.
}
private VolatileSingleton(){};
public static VolatileSingleton getInstance() {
if (_instance==null) {
synchronized(VolatileSingleton.class) {
if (_instance==null) { //double check
_instance=new VolatileSingleton();
counter++;
}
}
}
return _instance;
}
@Override
public void run() {
VolatileSingleton.getInstance();
}
}