Results 1 to 5 of 5
Thread: Why twice condition check?
- 09-11-2012, 01:02 PM #1
Member
- Join Date
- Aug 2012
- Posts
- 22
- Rep Power
- 0
Why twice condition check?
In the example below, why has synchronized been checked twice? I'm talking about lines 7 and 9 .
Java Code:public class Singleton { private static volatile Singleton instance = null; private Singleton() { } public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class){ if (instance == null) { instance = new Singleton(); } } } return instance; } }Tools of Choice : Eclipse Helios | Windows Vista | Windows 7 | MySQL | Apache Tomcat
- 09-11-2012, 01:21 PM #2
Re: Why twice condition check?
Because code executing on another Thread may have been creating the instance while this Thread was waiting for the lock in order to enter the synchronized block.
That said, your code looks rather old. In early Java versions, this kind of coding was considered optimal because a null check was more than an order of magnitude faster than obtaining a lock. With improvements in both computers and the JVM, the whole method would probably be synchronized. If at all anyone is still using the Singleton (anti-) pattern.
dbWhy do they call it rush hour when nothing moves? - Robin Williams
- 09-11-2012, 04:54 PM #3
Moderator
- Join Date
- Apr 2009
- Posts
- 10,460
- Rep Power
- 16
Re: Why twice condition check?
And syncrhonising is pointless for a singleton anyway:
Also I wouldn't consider a singleton to be an anti-pattern at all.Java Code:public class MySingleton { private static final MySingleton instance; private MySingleton() { } public static MySingleton getInstance() { return instance; } }
Abused, yes, but not an anti-pattern.
Edit:
Java Code:public class MySingleton { private static final MySingleton instance = new MySingleton(); private MySingleton() { } public static MySingleton getInstance() { return instance; } }Last edited by Tolls; 09-11-2012 at 06:15 PM. Reason: Idiocy
Please do not ask for code as refusal often offends.
- 09-11-2012, 05:57 PM #4
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,400
- Blog Entries
- 7
- Rep Power
- 17
- 09-11-2012, 06:14 PM #5
Moderator
- Join Date
- Apr 2009
- Posts
- 10,460
- Rep Power
- 16
Similar Threads
-
How to use class in if condition
By raj.mscking@gmail.com in forum New To JavaReplies: 8Last Post: 03-08-2012, 03:53 PM -
Condition ignored.
By Pojahn_M in forum New To JavaReplies: 8Last Post: 12-09-2011, 02:21 AM -
Waiting on a condition
By nephos in forum New To JavaReplies: 9Last Post: 04-22-2011, 10:05 AM -
basic condition
By ts96 in forum New To JavaReplies: 1Last Post: 02-16-2011, 12:23 PM -
While loop condition
By counterfox in forum New To JavaReplies: 3Last Post: 10-10-2010, 01:14 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks