I have a top-level service which has a method A, which accesses shared data and is declared synchronized. Method A in turn calls method B of an internal class, which accesses some shared data of its own.
If I can guarantee that B is only called from the API of the top level service and is not publicly exposed, do I still need to declare B as synchronized? Or is the synchronized declaration of A enough to ensure that B is thread-safe too?
Is there a performance penalty in declaring B synchronized as well?
The key really is that B is not called from somewhere else. As long as this is ensured, you are fine.
There is a small performance penalty if you make B synchronized as well.
Yes, you will be fine.
syncronized(object) {
do thing one;
do thing two;
}
is the same as
syncronized(object) {
doSomething();
}
void doSomething() {
do thing one;
do thing two;
}
as long as a lock is held on the object , everything that goes inside the syncronized block will be an atomic operation
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.