Skip to content

Instantly share code, notes, and snippets.

@rohanjai777
Created November 9, 2022 19:37
Show Gist options
  • Save rohanjai777/3d481634a8a3a79e01ed376b74a0d540 to your computer and use it in GitHub Desktop.
Save rohanjai777/3d481634a8a3a79e01ed376b74a0d540 to your computer and use it in GitHub Desktop.
class DBC{
static int a = 10;
private static DBC dbc;
private DBC(){}
public static DBC getInstance(){ //not thread safe
if(dbc == null){
dbc = new DBC();
}
return dbc;
}
}
public class Client{
public static void main(String[] args){
DBC obj = DBC.getInstance();
System.out.println(obj.a); //10
}
}
//Synchronized
class DBC{
static int a = 10;
private static DBC dbc;
private DBC(){}
public synchronized static DBC getInstance(){ //now thread safe, but its blocking code
if(dbc == null){
dbc = new DBC();
}
return dbc;
}
}
//Double check locking
class DBC{
static int a = 10;
private static DBC dbc;
private DBC(){}
public static DBC getInstance(){ //now thread safe, double check locking
if(dbc == null){
synchronized(DBC.class){ //making critical section synchronized
if(dbc == null){
dbc = new DBC();
}
}
}
return dbc;
}
}
//Best implementation
class DBC{
static int a = 10;
private static DBC dbc = new DBC(); //only one instance
private DBC(){}
public static DBC getInstance(){ //now thread safe
return dbc;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment