![]() ![]() |
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|
|
|
LinkBack | Thread Tools | Display Modes |
|
|
#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 ? |
|
|
|
|
#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 |
|
|
|
|
#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 |
|
|
|
|
| Thread Tools | |
| Display Modes | |
|
|