Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

threads synchronized methods

 
girish
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am a bit confused about locks obtained by threads.
My doubt is:
When a thread obtains lock on particular object ,
can other thread execute another method of that object which is not declared synchronized
Please help
 
Gary Smith
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In short, yes.
Be clear about the difference between synchronised methods and synchronised blocks. The former lock the monitor of the object (i.e. 'this') whereas the latter can synchronise on 'this' or any other object you specify.
So, if you have a thread running in a synchronised method of an object, then other threads that attempt to synchronise on 'this' or enter other synchronised methods in the object will be blocked _but_ other threads can enter non-synchronised methods without a bother, as would happen if no synchronisation was used at all. That is, it is the threads that are blocked not the object.
 
girish
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Gary.That really solves my problem.
 
Sushma
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
Can u pl throw more light on 'locking on the monitor of the object'?
A synchronised method can call a non synchronised method, so if this is true, what if some other thread which could access thsi method changed the data in this and this was called by the synchronized method???
I'm really confused....Pl help me.
Regards,
Sushma
[This message has been edited by Sushma (edited May 11, 2000).]
[This message has been edited by Sushma (edited May 11, 2000).]
 
bongadi
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And you are right. A thread without the lock can run
unsynchronized method "and change the data".

So, all the methods which are modifying and accessing the data in
critical section should be synchronized to prevent
data corruption.

Originally posted by Sushma:
Hi,
Can u pl throw more light on 'locking on the monitor of the object'?
A synchronised method can call a non synchronised method, so if this is true, what if some other thread which could access thsi method changed the data in this and this was called by the synchronized method???
I'm really confused....Pl help me.
Regards,
Sushma
[This message has been edited by Sushma (edited May 11, 2000).]
[This message has been edited by Sushma (edited May 11, 2000).]


[This message has been edited by bongadi (edited May 11, 2000).]
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic