DZone ForumsDZone Forums  

Go Back   DZone Forums > Community > Languages & Frameworks > Java
FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
LinkBack Thread Tools Display Modes

Topic: synchronized keyword in singleton
Old 02-28-2008, 10:36 AM   #1 (permalink)
Member
 
Join Date: Feb 2008
Posts: 1
Good day, all.

I'm new to multi-thread and cannot emulate this issue properly, so if anyone could help by comment, I would appreciate much.

The question is, whether synchronized keyword is needed in non-static methods of singleton ?

E.g.

public class MySingleton {
private static MySingleton instance;

public static synchronized MySingleton getInstance() {
if (instance == null) {
instance = new MySingleton();
}
return instance;
}

public void myMethod() {
// do something
}
}

Does method myMethod need to be synchronized or not ?
radkat is offline   Reply /w Quote -


Old 02-29-2008, 06:36 AM   #2 (permalink)
Member
 
Join Date: Feb 2008
Posts: 2
Yes, it's needed, singleton's instance can be accessed from different threads at time.
vadimf is offline   Reply /w Quote -


Old 02-29-2008, 08:38 AM   #3 (permalink)
Member
 
Join Date: Feb 2008
Posts: 5
Hi,
it depends. The synchronized is not needed to guarantee that your singleton is indeed a singleton. That's what the synchronized on the static method getInstance() is for. If your myMethod() performs something that should be thread safe, you should make it synchronized.

kind regards,
Christiaan
christiaan_se is offline   Reply /w Quote -


Topic: Singleton construction
Old 03-02-2008, 12:29 AM   #4 (permalink)
Member
 
Join Date: Feb 2008
Posts: 3
You may find my article on Singleton construction, double-checked locking, etc of interest.

Alex Miller - Pure Danger Tech
puredanger is offline   Reply /w Quote -


Thread Tools
Display Modes




All times are GMT -5. The time now is 08:13 PM.