Solved

Java Singleton

Posted on 2011-02-23
3
495 Views
Last Modified: 2012-05-11
I have a singleton class. If I have a business logic method (Mulitple threads will invoke this method). Do I need to put it as synchronized method. Please see the codes below:  
public class Resource{
    public static Resource self = new Resource();
    Public static ConcurrentLinkedQueue<Item> queue = new CurrentLinkedQueue<Item>();
    
    public static Resource getInstance(){
          return Reource();
    }  
    
    private Resource(){
            
    } 

    public Item getNextItem(){                           <----------------------Is Synchronized key word needed for this method?
          return queue.poll(); 
    } 
}

Open in new window

0
Comment
Question by:JianJunShen
  • 2
3 Comments
 
LVL 40

Expert Comment

by:gurvinder372
ID: 34967509
if <<return queue.poll(); >> is only fetching the value and not updating anything, then you dont need the Synchronized keyword.
Else, it is required and it will depend upon where you want the sync control to be. And i would suggest that you put the synchronize keyword in the CurrentLinkedQueue class itself if at all you want that resource to be shared.



0
 
LVL 92

Expert Comment

by:objects
ID: 34967529
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 34967537
> Is Synchronized key word needed for this method?

your queue is already thread safe, so no
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…
This video teaches viewers about errors in exception handling.

759 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now