![](/img/trans.png)
[英]Why is this code not thread-safe, even when using a synchronized method?
[英]If a method is called from within a synchronized method, is the inner method's access to shared mutable data thread-safe?
我有一个具有方法A的顶级服务,该方法访问共享数据并声明为同步。 方法A依次调用内部类的方法B,该类访问其自身的某些共享数据。
如果我可以保证B仅从顶级服务的API中调用,并且不会公开公开,我是否仍需要将B声明为已同步? 还是A的同步声明足以确保B也是线程安全的?
声明B同步也有性能损失吗?
关键确实是不能从其他地方调用B。 只要确保这一点,就可以了。
如果同时使B同步,则性能损失很小。
是的,你会没事的。
syncronized(object) {
do thing one;
do thing two;
}
是相同的
syncronized(object) {
doSomething();
}
void doSomething() {
do thing one;
do thing two;
}
只要在对象上持有锁,同步块内部的所有内容都是原子操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.