简体   繁体   中英

Hashmaps used in multithreaded environment

public class Test {
    private final Map<URI, Set<TestObject>> uriToTestObject = new HashMap<URI, Set<TestObject>>();
    private final Map<Channel, TestObject> connToTestObject = new HashMap<Channel, TestObject>();

    private static class TestObject {
        private URI server;
        private Channel channel;
        private final long startNano = System.nanoTime();
        private AtomicInteger count = new AtomicInteger(0);
    }
}

This is a class which I am planning to use as a connection manager. There are two maps one will have server uri to connection details ie Test object and other will have channel to TestObject ie connection entry details, when connection is created then put channel testobject and server uri as per required in both the maps , when give another request first check in the map for that server uri and obtain a channel, similarly when channel is close remove from both the maps, its corresponding entries ie channel object and test object, should I use concurrent hash map or should I use HashMap and then synchronize on the add remove methods, also I shall be using count AtomicInteger variable for statistics purpose it will be incremented and decremented.

My question here is in the multithreaded environment do I need to make my methods synchronized even if I use ConcurrentHashmap , as I would be doing some operations on both maps in one method.

Yes, you need synchronization in multi-threaded environment. Its better if you go with block level synchronization instead of method level synchronization.

Code snippet:

Object lock = new Object();

void method1(){
   synchronized(lock){
   //do your operation on hash map
   }
}

void method2(){
   synchronized(lock){
   //do your operation on hash map
   }
}

And about ConcurrentHashMap

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove).

So yes you still may need to syncronization even you used ConcurrentHashMap .

Since you need operate two Maps at the same time,
Make the method synchronized is better choice.
And HashMap is enough if method is synchronized

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM