I i make a call to noonsynchronized method from within my synchronized method is it thread safe?
I have 2 methods as follows:
public class MyClass{
void synchronized doSomething1(){
doSomething2();
}
void doSomething2(){
//will this block of code be synchronized if called only from d开发者_JAVA百科oSomething1??
}
}
If doSomething2()
is only called from doSomething1()
, then it will only be called by a single thread for a single instance of MyClass
. It could still be called from different threads at the same time, via different instances - so if it acts on any shared data which may not be specific to the instance of MyClass
, it's still not guaranteed to fix all threading issues.
Basically, you need to think carefully about any mutable shared state used by multiple threads - there are no easy fixes to that, if you need mutable shared state. In your particular case you'd also need to make sure that doSomething2()
was only called from doSomething1()
- which would mean making it private to start with...
When calling doSomething1()
the caller's Thread
locks on the monitor of the instance of MyClass
. Until that thread's execution exits doSomething1
the lock will remain which includes if it goes into doSomething2
. This will cause other threads to block when attempting to lock.
Keep in mind:
synchronized
does not thread-safe it make.
Further info:
- JLS 3rd Ed 17.1 Locks
If doSomething2()
is called ONLY from doSomething1()
then yes - it is thread safe.
精彩评论