java - Is Map<String,AtomicLong> enough to be thread safe? -


i have simple class:

public class idprovider {      private map<string,atomiclong> idmap;      public idprovider(){         idmap = new hashmap<>();     }      public long getavailableid(string conversation){         atomiclong id = idmap.get(conversation);         if(id == null){             id = new atomiclong(0);             idmap.put(conversation,id);         }         return id.getandincrement();     }   } 

different methods asynchronously may pass same conversation identifier , call getavailableid() returned unique id.

is thread safe? i'm guaranteed no 2 methods receive same id or need opt else?

there's multiple ways make thread safe, below simplest, think. first, need safely publish initial map. need make each access of map thread safe.

public class idprovider {      private final map<string,atomiclong> idmap;      public idprovider(){         idmap = new hashmap<>();     }      public synchronized long getavailableid(string conversation){         atomiclong id = idmap.get(conversation);         if(id == null){             id = new atomiclong(0);             idmap.put(conversation,id);         }         return id.getandincrement();     }   } 

the final keyword 1 way provide "safe publication". (that's actual term in java, up.)

and without being tricky, synchronizing whole method easiest way provide both synchronization , atomicity. shouldn't try more unless can profile code , determine in fact performance bottle-neck. keep simple.


Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -