i came across example below of java class claimed thread-safe. please explain how thread-safe? can see last method in class not being guarded against concurrent access of reader thread. or, missing here?
public class account { private lock lock = new reentrantlock(); private int value = 0; public void increment() { lock.lock(); value++; lock.unlock(); } public void decrement() { lock.lock(); value--; lock.unlock(); } public int getvalue() { return value; } }
the short answer :
by definition,account thread-safe class though gevalue method not guarded
the long answer
from java concurrency in practice class said thread safe when :
no set of operations performed sequentially or concurrently on instances of thread-safe class can cause instance in invalid state.
since the getvalue method not result in account class being in invalid state @ given time, class said thread safe.
the documentation collections#synchronizedcollection resonates sentiment :
returns synchronized (thread-safe) collection backed specified collection. in order guarantee serial access, critical access backing collection accomplished through returned collection. imperative user manually synchronize on returned collection when iterating on it:
collection c = collections.synchronizedcollection(mycollection); ... synchronized (c) { iterator = c.iterator(); // must in synchronized block while (i.hasnext()) foo(i.next()); }
notice how documentation says collection (which object of inner class named synchronizedcollection in collections class) thread-safe , yet asks client code guard collection while iterating on it. infact, iterator method in synchronizedcollection not synchronized. similar example account thread-safe client code still needs ensure atomicity when calling getvalue.
Comments
Post a Comment