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

need synchronize clarification

 
Higgledy Smith
Ranch Hand
Posts: 192
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a class has a synchronized method and a non-synchnized method.
Two threads running; both operating on 1 instance of the above class.

If thread A gets the lock and is in the synchronized method.
Can thread B access the non-synchronized method while thread A has the lock and is using the synch'd method?

If I had 2 instances of the same class, there would be 2 locks available. 1 for each instance. Is this correct thinking? In other words locks are associated to instances of a class not to the Class.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A synchronized method requires that the executing thread obtain the lock. A non-synchronized method does not require a lock to be obtained. So you are correct: Non-synchronized methods can be accessed while another thread has the lock.

There are 2 types of locks: An object lock (one for each instance) and a class lock. The class lock is needed for accessing synchronized static code. So if you have 2 instances of the same class, then there are 2 distinct object locks, but there is only 1 class lock. Which lock is required depends on whether the synchronized code is static or not.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic