0

I need to synchronize only the obj1 and obj2 of the following singleton class such that multiple threads can obtain the single instance of this class however only one thread can access obj1 or obj2 at a time.

  public class Sample{

    private static LinkedHashMap<String, String> obj1;
    private static LinkedHashMap<String, String> obj2;

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

    private Sample() {

    }

    public void add(LinkedHashMap lhm){
        //steps
        }

    public void remove(LinkedHashMap lhm){
        //steps
        }

}

How should i go about doing that ?

1 Answer 1

4

First, make the 2 variables instance variables rather than static variables.

Second, synchronize the methods of the singleton:

public synchronized void add(LinkedHashMap lhm){
    //steps
}

I would avoid lazy instanciation of the singleton. Most of the time, there's no added value:

private static final Sample INSTANCE = new Sample();

public static Sample getInstance() {
    return INSTANCE;
}

If you really want to keep is lazily initialized, then the getInstance() method should also be synchronized, alse two threads might get two different instances of your singleton.

Sign up to request clarification or add additional context in comments.

4 Comments

Have to synchronize getInstance() (erm, and actually have an instance field), or make instance static and initialize it there, or use an enum and be done with the whole thing :)
@BrianRoach: yes, I missed that.
@JBNizet if i synchronize method in my class then wont that synchronize the entire instance of the class? I want multiple threads to be able to modify those linkedhashmap objects but only one at a time per variable. I need a variable specific lock to precise
That's what synchronization is all about. And since the singleton doesn't hold any other state than these maps, that's what you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.