Synchronization question
David Holmes
david.holmes at oracle.com
Tue Dec 20 23:15:05 PST 2011
Not sure why you sent this to serviceability-dev as this has nothing to
do with the JDK/JVM serviceability APIs
On 21/12/2011 4:32 PM, Lee Ming wrote:
> Currently We are developing a system that requires a lot of usages of
> Java concurrency. There seem to be some
> concurrent bugs in our system. Thus I just wonder about the following
> usage of lock
>
> class Test{
> private final PInfo obj = new PInfo();
> private ReentrantLock lock = new ReentrantLock();
> ...
>
> public void put(long n){
> try{
> lock.lock();
> obj.put(n);
> }
> finally { lock.unlock();}
> }
> }
First the lock.lock() should be outside of the try block. lock.lock()
may throw OutOfMemoryError for example, then you'd try to unlock and
trigger an IllegalMonitorStateException.
> The question is: does the *lock.lock()* statement will guarantee that
> subsequent methods stacks
> which involved! with *obj.put(n)* will be synchronized ? that is to say,
> the fields of the object *obj
> *will be read/write directly from main memory and never cache.
I don't quite understand your question but thinking about caches is the
wrong way to think about this. The Java Memory Model defines the rules
for visibility and ordering of variables. This impacts not only
potential caching affects on a given piece of hardware but also allowed
optimizations by a JIT. The use of a Lock not only provides mutual
exclusion for all sections of code protected by the same lock (and by
extension, mutual exclusion to data if all accesses occur within those
sections of code) but also ensures visibility of state changes made by
one thread, to another thread that acquires the same lock.
So the lock() in the above ensures that calls to put() are serialized
for a given instance of Test. If there were a corresponding get() that
also acquired the lock then it would ensure that the thread doing the
get saw the updates made to the PInfo object via its put method. But if
you access the PInfo objects outside of that lock then there are no
guarantees as to what state you will see that PInfo in.
Hope that helps.
David Holmes
------------
>
> Thank you and regards
>
> Bhm
More information about the serviceability-dev
mailing list