If a synchronized method calls another synchronized method, is it thread safe?
void synchronized method1() { method2() } void synchronized method2() { }
Yes, they can run simultaneously both threads. If you create 2 objects of the class as each object contains only one lock and every synchronized method requires lock. So if you want to run simultaneously, create two objects and then try to run by using of those object reference.
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed.
When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
The synchronized keyword can be used to mark four different types of blocks: Instance methods. Static methods. Code blocks inside instance methods.
Yes, when you mark methods as synchronized
, then you are really doing this:
void method1() { synchronized (this) { method2() } } void method2() { synchronized (this) { } }
When the thread call gets into method2 from method1, then it will ensure that it holds the lock to this
, which it will already, and then it can pass through.
When the thread gets directly into method1 or method2, then it will block until it can get the lock (this
), and then it will enter.
As noted by James Black in the comments, you do have to be aware with what you do inside of the method body.
private final List<T> data = new ArrayList<T>(); public synchronized void method1() { for (T item : data) { // .. } } public void method3() { data.clear(); }
Suddenly it's not thread safe because you are looking at a ConcurrentModificationException
in your future because method3
is unsynchronized, and thus could be called by Thread A while Thread B is working in method1
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With