Reputation: 63
Suppose I have the following code:
private ConcurrentHashMap<Integer, Book> shelf;
public Library(ConcurrentHashMap<Integer, Book> shelf){
this.shelf = new ConcurrentHashMap<Integer, Book>(shelf);
}
Given that I'm using a thread safe collection would the following method be okay to use or do I need to worry about thread safety?
public void addBook(int index, Book add){
shelf.put(index, add);
}
If the above method isn't safe to use, would adding synchronized be the proper way of doing it? Like so,
public synchronized void addBook(int index, Book add){
shelf.put(index, add);
}
Upvotes: 0
Views: 115
Reputation: 1248
The synchronized
keyword essentially puts a mutex lock around the entire addBook
method.
A ConcurrentHashMap
ensures that all operations (such as put) are threadsafe, but using retrieval operations (such as get) in conjunction might cause you to come across a situation where you are retrieving contents from the Hashmap at the same time that you are putting, and get unexpected results.
Individually, all methods in the ConcurrentHashMap
are thread-safe, but used in conjunction in separate threads you cannot necessarily be certain of the order in which they execute. (Thanks to @jtahlborn for clarification).
So, in your specific case, adding the synchronized
keyword to the addBook
method is redundant.
If you're doing more complex operations involving multiple retrievals and puts, you may want to consider some extraneous locking (your own mutex).
See: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentHashMap.html
Upvotes: 0
Reputation: 34179
You don't need to worry if you are ONLY calling shelf.put
. Since put
is already threadsafe then you are ok.
You would need to worry about synchronized when you are doing multiple operations that together need to be atomic. For example, maybe you had a method called updateBook
that looks like
public void updateBook(int index, String newTitle){
Book book = shelf.get(index);
// do something with book or maybe update book.setTitle(newTitle);
shelf.put(index, book);
}
This method would have to be synchronized
because otherwise anther thread can get a book that is not updated yet.
Upvotes: 1