我发现我经常做以下类似的事情。制作对象的副本以发送到线程。线程是唯一使用过该对象的线程,并且我们有一个happens-before关系,所以它是线程安全的。
但这让我感到紧张。正如评论所述,如果有人出现并欺骗 objForThread 怎么办?我应该使用锁吗?或者这是一个普遍接受的java模式?
class Example
{
private SomeObj mDynamicObj = new SomeObj();
public void doWorkInAThread()
{
mutateThis(mDynamicObj);
final SomeObj objForThread = new SomeObj(mDynamicObj);
myExecutorService.submit(new Runnable() { @Override public void run()
{
doSomethingWith(objForThread);
}});
mutateThis(mDynamicObj);
// Concerned that in the future someone will come
// along and mutate objForThread here making this thread unsafe
}
}