#Synchronized Question

12 messages · Page 1 of 1 (latest)

inland pendant
#

Is the following use of synchronized correct?

I know that the code below doesn't need to use synchronized because it doesn't run on a different thread, I just want to know if it's correct to use.

import java.util.*;

class HelloWorld {
    private static Map<String, String> map = new HashMap<>();
    
    public static void main(String[] args) {
        synchronized (all())
        {
          for(String str : all())
          {
            //Some Stuff
          }
        }
    }
    
    public static Collection<String> all()
    {
        return map.values();
    }
}
earnest sunBOT
#

This post has been reserved for your question.

Hey @inland pendant! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

inland pendant
broken willow
inland pendant
#

then java will lock the values reference of the map?

broken willow
#

yep pretty sure all() is synchronized. It's better to show it in a method where race condition could actually occur. (I guess it depends on how the application works but chances are there aren't multiple threads calling the main method at the same time)

#

here is my example

#

./run java ```

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class SynchPrac {

private static Map<String, String> map = new HashMap<>();

public static void main(String[] args) {

    map.putAll(Map.of("key1", "value1", "key2", "value2", "key3", "value3"));

    new Thread(() -> {
        try {
            for (int i = 0; i < 4; i++) {
                all();
                Thread.sleep(500);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }).start();
    new Thread(() -> {
        try {
            for (int i = 0; i < 4; i++) {
                all();
                Thread.sleep(40);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }).start();


}

public static Collection<String> all() {
    synchronized (map) {

        System.out.println(Thread.currentThread());
        return map.values();
    }
}

}

drowsy surgeBOT
#

Here is your java(15.0.2) output @broken willow

Thread[Thread-0,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-1,5,main]
Thread[Thread-0,5,main]
inland pendant
#

thanks