DZone Forums
Go Back   DZone Forums > Community > Languages & Frameworks > Java
Reload this Page synchronized keyword in singleton
Notices
Reply
 
LinkBack Thread Tools Display Modes
  (#1 (permalink)) Old
Member
 
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default synchronized keyword in singleton - 02-28-2008, 11:36 AM

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 ?
Reply With Quote
  (#2 (permalink)) Old
Member
 
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-29-2008, 07:36 AM

Yes, it's needed, singleton's instance can be accessed from different threads at time.
Reply With Quote
  (#3 (permalink)) Old
Member
 
Posts: 5
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default 02-29-2008, 09:38 AM

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
Reply With Quote
  (#4 (permalink)) Old
Member
 
Posts: 3
Thanks: 0
Thanked 0 Times in 0 Posts
Join Date: Feb 2008
Default Singleton construction - 03-02-2008, 01:29 AM

You may find my article on Singleton construction, double-checked locking, etc of interest.

Alex Miller - Pure Danger Tech
Reply With Quote
Reply

Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
how to search xml file data based on the given keyword from html form nicemothi Java 0 04-04-2008 03:51 AM


Copyright 1997-2009, DZone, Inc.
vBulletin Skin developed by: vBStyles.com