Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Threads and Synchronization  RSS feed

 
alzamabar
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, let's suppose that i have the following methods:
synchronized public Object obj1() {
return new Object();
}
synchronized public Object obj2() {
return new Object();
}
Forgot the logic of it, as it is not the focus of the post , but suppose to have two threads belonging to two different istances:
if thread1 calls obj1, can thread2 call obj2? From what i learned on a book, even if the two threads call different methods, thread2 cannot call any other synchronized method until thread1 has finished with its call.
Regards,
Marco
 
John Smith
Ranch Hand
Posts: 2937
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

if thread1 calls obj1, can thread2 call obj2?

The answer to this question depends on which object(s) is/are used to call methods obj1() and obj2() from threads thread1 and thread2. If it is the same object, then the methods will be run in sequence. If it is two different objects (two instances of a class that has synchronized methods), one of them can run method obj1() while the other one can run method obj2().
Perhaps this will be clear if you run the following code:

Output:
in method obj1(), sleeping
in method obj2(), sleeping
woke up, still in method obj1()
woke up, still in method obj2()
As you can see from the output, while thread1 runs method obj1(), nothing prevents thread2 from running method obj2().
However, replace the code...
Client thread1 = new Client(new FalseSafety());
Client thread2 = new Client(new FalseSafety());
with...
FalseSafety falseSafety = new FalseSafety();
Client thread1 = new Client(falseSafety);
Client thread2 = new Client(falseSafety);
... and now the methods ob1() and obj2() will be run in sequence.
The key thing to understand is that is not really a method that can be synchronized, but the object that is used to call the synchronized method. In fact,

is equivalent to

Hope this is clear,
Eugene.
[ February 15, 2003: Message edited by: Eugene Kononov ]
 
alzamabar
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Eugene, it's clear.
Marco
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!