File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Synched and NotSynched Threads Both Accessing a Shared Object

 
Yalvin Duha
Ranch Hand
Posts: 41
Eclipse IDE Java Slackware
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 20836
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Yalvin Duha
Ranch Hand
Posts: 41
Eclipse IDE Java Slackware
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic