• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Do I need to have synchronized keyword in the code ???

 
Ryan Raina
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All

Consider the following code

[Added code tags - see UseCodeTags for details]


Output

A about to wait.
B about to wait.
A interrupted.
A terminating.
B interrupted.
B terminating.


my question is that do i need to have synchronized keyword here is the run method..It looks like I need that but I want to understand why??

I am calling run method on two different objects..so every object will have it's own method copy..so they should not block here...and every thread get's it's local thread copy..

Any suggestions??
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason is your call to wait(). If you look at the Javadocs for java.lang.Object#wait(), you'll see:
This method should only be called by a thread that is the owner of this object's monitor. See the notify method for a description of the ways in which a thread can become the owner of a monitor.

Throws:
IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.


The thread owns an object's monitor if it's in code synchronized on that object. So if you took out the synchronized keyword you'd get an IllegalMonitorStateException.
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Are you asking if you need the keyword "synchronized"? or do you need something to synchronize (mutex) your code?

In the beginning, the only way to write thread safe code was to use the keyword "synchronized"

Java 5 implemented a number of new classes and methods for synchronization, so you can use things like ReadWriteLock and achieve the same effect. So the keyword is not the only way to do it, but you must write thread safe code if you use threads.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic