aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Synched and NotSynched Threads Both Accessing a Shared Object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Synched and NotSynched Threads Both Accessing a Shared Object" Watch "Synched and NotSynched Threads Both Accessing a Shared Object" New topic
Author

Synched and NotSynched Threads Both Accessing a Shared Object

Yalvin Duha
Ranch Hand

Joined: Apr 07, 2012
Posts: 40

The following code is confusing me a bit.

As you can see, we have two threads, "a" (Synch Accessor) and "b" (Unsynch Accessor), and two jobs, Runnable AccessingWithLock and AccessingWithoutLock, where both are accessing a shared object (SynchOrNoSynch.bObj which is an array of bytes).

Surprisingly, when the AccessingWithoutLock thread goes to sleep and AccessingWithLock enters the synchronized block, since AccessingWithLock has been engaged in intensive calculations, it will take some time for it to finish and you would not expect AccessingWithoutLock to be able to access bObj. To the contrary, it does get a hold of bObj , prints to the screen and its run() ends while the program waits for AccessingWithLock to finish its work, equally prints its outcome to the screen.

If one thread has a lock on an object, given that this thread would maintain the lock for certain duration, shouldn't it continue to have a hold on that lock until it releases it -- in this case exiting synchronized block in AccessingWithLock.run()?
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19064
    
  40

If you haven't already guessed, synchronization is cooperative. The only way for one thread to prevent another thread from doing something, is for both threads to try to obtain the same lock -- the block is at the point of trying to obtain the lock (when the other thread owns it). A thread that doesn't synchronize can do whatever the thread wants to do.

Henry

Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Yalvin Duha
Ranch Hand

Joined: Apr 07, 2012
Posts: 40

Henry Wong wrote:If you haven't already guessed, synchronization is cooperative. The only way for one thread to prevent another thread from doing something, is for both threads to try to obtain the same lock -- the block is at the point of trying to obtain the lock (when the other thread owns it). A thread that doesn't synchronize can do whatever the thread wants to do.

Henry

Point taken. I was just under a wrong impression that once a lock is acquired, then any other thread would be prevented from accessing the object -- regardless of attempting to synchronize on it or not. That clears it.

Thanks.
 
wood burning stoves
 
subject: Synched and NotSynched Threads Both Accessing a Shared Object