java - Is it possible to allow different thread both read to and write from the same collection? -
i have following wrapper:
public usercontianer{ private list<user> users; public void add(user u){ users.add(u) } public void update(user u){ if(users.contains(u)) //updating new value u } public user get(int index){ return users.get(index); } } i need allow multiple thread read , write container simultaneously such that
- if read , written element of list different- should ok
if read , written element of list same then
if there's thread updating element read operation should blocked untill write operation's finished
if there's thread reading element, write operations should blocked until reading's finished
first of all, such requirements make sense? i'm new multithreading , maybe that's actualy not wanted.
secondly, possible implement requirements in java?
one option wrap existing list in synchronized version collections.synchronizedlist(list<t> list). allows thread-safe use of list, if access through synchronized wrapper.
note elements in list references. if want lock list while you're making changes objects, you'll need synchronize @ higher level. 1 way mark methods synchronized.
public synchronized void update(user u) { ... }
Comments
Post a Comment