Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

synchronizing a method  RSS feed

 
Mathew Kuruvilla
Ranch Hand
Posts: 145
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we use
public class test {
synchronized aMethod1() {
}
aMethod2() {
}
}
for a method, we obtain a lock on the instance of the class where that code is executing. Am I right?
In this case, can we execute a call aMethod1 and aMethod2 concurrently and have them both execute the code concurently? Or would aMethod2 have to wait till that instance completes the method call to aMethod1?
Thanks.
 
Thomas Thomas
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
u r right the lock is obtained on instance of the class /Object..
u can execute a sync method & non sync method same time using multiple threads.
but if a class has two sync methods only one can be run at a time.
if u r using a complex method in which a small part is to be synchrinized .u can synchronized blocks
synchronized(this/object){
}
u can use blocks of code in method rather than sync the whole method
thomas
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!