Say I have a hash map and multiple threads. If I have a synchronized method that adds to the hash map, how would I make it possible that two different threads can put differ
However, if I am trying to add another String into an already contained key's corresponding LinkedList, I can just synchronize the hash map's get method. I think this will allow multiple threads to simultaneously (concurrently) add to the LinkedLists of different, already contained keys.
Read-only access to a HashMap
is safe: you can have multiple threads call the get
method with no synchronization at all and nothing breaks. If the linked lists are not shared between threads you don't need synchronization either. To be sure the threads never share a list the map key should be something specific to the thread, like an object created locally or the thread ID.
What's not safe is to let another thread modify a map or a list concurrently with a read or write. This is the use case for a read-write lock: it allows multiple concurrent reads but writes have to be exclusive.
The easiest answer is to use a ConcurrentHashMap
, which does exactly what you're looking for.
If you can't do that (I see you edited your post after I answered), then you'll have to duplicate the same thing that ConcurrentHashMap
does. No, simply synchronizing the method of a HashMap will not allow two threads to add a key-value pair at the same time, they have to wait and go one at a time.
The answer to your question is NO. Because synchronized block forces every tread to wait in the single queue. With ConcurrentHashMap
you have more chances for simultaneously add, because it locks only basket where element will be inserted instead of locking whole HashMap.
My current implementation is a synchronized method. Would this allow two different threads to put two different keys simultaneously into the hash map?
No. Only a ConcurrentHashMap
or a specifically designed concurrent map would support this safely, so it's impossible for you to put two keys simultaneously into the same map from two threads.
how would I make it possible that two different threads can put different keys simultaneously (concurrently) into the hash map?
You cannot, without using ConcurrentHashMap
, another ConcurrentMap
implementation, or implementing your own.