Reputation: 13
Suppose you have two threads that have access to the same public object. One thread has a block of code that reads the object's fields.
synchronized(object)
{
read object fields
}
While the read object field code is executing in thread 1, if thread 2 wants to update the object's fields, will it have to wait until thread 1 finishes reading the object's fields before updating (e.g. is the object locked from access by other threads while the synchronized code block is executing)?
Upvotes: 1
Views: 85
Reputation: 10653
Synchronized block only protects the code inside it. So if two or more threads try to run code inside synchronized block (protected by same object monitor) they will be executed exclusively. Meaning if one thread has entered synchronized block others will have to wait till it gets out.
Synchronized block does not lock the object in anyway, it just uses object's monitor to guard the code inside it. If you want to make method of object thread safe then you have to declare them synchronized.
synchronized getField()
synchronized setField()
Now getField() and setField() can safely be called by multiple threads.
However using synchronized has a performance cost instead you can try using Locks, or Atomic classes in java.util.concurrent.atomic like AtomicInteger, AtomicBoolean or AtomicReference.
Upvotes: 0
Reputation: 29946
No, the second thread will not wait, unless it has a synchronized
block on the same object too.
synchronized(object)
{
// read object fields
}
... in other thread:
synchronized(object)
{
// write object fields
}
Upvotes: 0
Reputation: 312219
Synchronizing on an object does not "lock" it in any way. Unless updating the object's fields is synchronized in the same fashion, it may very well interleave with the reading code you presented here.
Upvotes: 1