I have a queston regarding double-checked locking. Consider this example:
public class Singleton {
private static volatile Singleton instance = null;
public static Singleton getInstance() {
if(instance == null) {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
}
return instance ;
}
}
As I have understood, the above code is the correct way to make a Singleton class.
However, NetBeans wants me to remove the outer if statement, so it would look like this:
public class Singleton {
private static volatile Singleton instance = null;
public static Singleton getInstance() {
synchronized(Singleton.class) {
if(instance == null) {
instance = new Singleton();
}
}
return instance ;
}
}
The only differece between these two snippets is that in the second example, the code will always get into the synchronized block and in the first it will not. Why would I listen to NetBeans and remove the outer if statement? It should be better avoid the locking.
Double-Checked Locking is widely cited and used as an efficient method for implementing lazy initialization in a multithreaded environment. Unfortunately, it will not work reliably in a platform independent way when implemented in Java, without additional synchronization.
Double-checked locking is the practice of checking a lazy-initialized object's state both before and after a synchronized block is entered to determine whether or not to initialize the object.
Ans. There is no mapping of single ton with number of processor of the system. So double check locking will not fail depending on number of processor.
In software engineering, double-checked locking (also known as "double-checked locking optimization") is a software design pattern used to reduce the overhead of acquiring a lock by testing the locking criterion (the "lock hint") before acquiring the lock.
NetBeans's automatic hint system obviously isn't aware that it's possible to do double-checked locking correctly with volatile
, as you've done, so it suggests full locking instead. Better safe than sorry. But you're right in this case, not NetBeans.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With