Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronized collection vs synchronized method?

I have a class container containing a collection which is going to be used by multiple threads:

public class Container{

    private Map<String, String> map;

    //ctor, other methods reading the map

    public void doSomeWithMap(String key, String value){
        //do some threads safe action
        map.put(key, value);
        //do something else, also thread safe
    }
}

What would be better, to declare the method synchronized:

public synchronized void doSomeWithMap(String key, String value)

or to use standard thread-safe decorator?

Collections.synchronizedMap(map);
like image 359
St.Antario Avatar asked Jun 05 '26 00:06

St.Antario


1 Answers

Generally speaking, synchronizing the map will protect most access to it without having to think about it further. However, the "synchronized map" is not safe for iteration which may be an issue depending on your use case. It is imperative that the user manually synchronize on the returned map when iterating over any of its collection views.

Consider using ConcurrentHashMap if that will meet your use case.

If there is other state to this object that needs to be protected from concurrency errors, then you will need to use synchronized or a Lock.

like image 169
Tim Bender Avatar answered Jun 06 '26 14:06

Tim Bender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!