Created
November 9, 2022 19:37
-
-
Save rohanjai777/3d481634a8a3a79e01ed376b74a0d540 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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