esuslogo
 [To advertise Java(tm) Events here, contact joris@esus.com!]
banner

Java™
by example!






New @ Esus.com


  gb  In-house search engine for better results!

  gb  Get updates with the esus.com
newsletter!









  Home 
 Browse Categories 
 Ask a Java Question 
 Help 
  For Java Tips & Tricks, subscribe to the esus.com newsletter!
Search Java Q&A, Links, API's:   adv 

How do I create a thread-safe singleton class?
The best way is:


public class ExampleSingleton {

private static ExampleSingleton instance;

public static ExampleSingleton getInstance() {
if( instance == null ) {
synchronized( ExampleSingleton.class ) {
if ( instance == null ) {
instance = new ExampleSingleton();
}
}//sync ends
}

return instance;
}
}


to make it threadsafe you have to use synchronization. But if you sync the whole method, you will create a tiny unnecessary performance overhead. Watch that the second if-condition is vitally important. Lets say instance is null, at this point two threads are executing the method. one thread goes in the sync block and the other starts waiting. when the second thread gets the lock and enters sync block, the Singleton has already been creates by the first thread. If you ommit the second if-condition, the second thread will create a second instance of the singleton.

Hope it helps.


Further Information
Author of answer: Zakaria

Comments
Comments to this answer are only viewable by members. Login or become a member!





Terms of Service | Privacy Policy | Contact

Copyright © 2000-2003 Esus.com - All Rights Reserved 
Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. Esus.com is independent of Sun Microsystems, Inc. All other trademarks are the sole property of their respective owners.