java - Using Synchronized with Thread-Safe Collection? -


suppose have following code:

    private concurrenthashmap<integer, book> shelf;      public library(concurrenthashmap<integer, book> shelf){                  this.shelf = new concurrenthashmap<integer, book>(shelf);            } 

given i'm using thread safe collection following method okay use or need worry thread safety?

    public void addbook(int index, book add){         shelf.put(index, add);     } 

if above method isn't safe use, adding synchronized proper way of doing it? so,

public synchronized void addbook(int index, book add){     shelf.put(index, add); } 

the synchronized keyword puts mutex lock around entire addbook method.

a concurrenthashmap ensures operations (such put) threadsafe, using retrieval operations (such get) in conjunction might cause come across situation retrieving contents hashmap @ same time putting, , unexpected results.

individually, methods in concurrenthashmap thread-safe, used in conjunction in separate threads cannot of order in execute. (thanks @jtahlborn clarification).

so, in specific case, adding synchronized keyword addbook method redundant.

if you're doing more complex operations involving multiple retrievals , puts, may want consider extraneous locking (your own mutex).

see: https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/concurrenthashmap.html


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -