-3

I've a singleton class like this:

private static StringsHandler INSTANCE = null;
private int count = 0;
//I have 2 methods so I don't have to be sending/checking nulls on getInstance
//once it's created
public static void createInstance(List<String> strings){
    if(StringsHandler.INSTANCE == null)
        StringsHandler.INSTANCE = new StringsHandler(strings);
}

public static StringsHandler getInstance(){
    return StringsHandler.INSTANCE;
}

public synchronized File use(){
    count++;
    System.out.println("threads using .use " + count);
    while(true){} //Keep the thread here so count should stay as 1
}

Instance is created on the application main class, main method just like this:

if(stringList.isEmpty()){
        LOGGER.error("List was empty");
        System.exit(0);
    }
StringsHandler.createInstance(stringList);

And I call it using something like this:

list.parallelStream().forEach(element -> {
    SingletonClass.getInstance().use();
});

This should print threads using .use 1 but it prints threads using .use 5 why is the synchronized keyword allowing for more than 1 thread?

Artemio Ramirez
  • 1,116
  • 1
  • 10
  • 23

1 Answers1

2

The synchronized keyword only allows one thread to lock the particular object on which it is used. So if you have more than one instance of this object, and call use on more than one of them at a time, they will be able to execute at the same time.

It is your responsibility to decide on, and consistently enforce, a mapping of data elements to exclusion methods. If more than one exclusion method protects the same data element, then you will not get correct exclusion.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278