在阅读java concurrency in practice(btw,一本优秀的书)时,我最终得到了以下相关问题。第一个是关于记录线程安全性,第二个是关于证明依赖于接口的类是线程安全的。
问题1。在接口上使用@ThreadSafe是否有意义?它是一种沟通方式,所有实现必须是线程安全的吗?我仍然想在这里下定决心,不确定这是不是一个好习惯。
请考虑以下示例。
public interface Point {
int getX();
}
class ImmutablePoint implements Point {
private final int x;
public ImmutablePoint(int x) {
this.x = x;
}
@Override
public int getX() {
return x;
}
}
class MutablePoint implements Point {
public int x;
public MutablePoint(int x) {
this.x = x;
}
@Override
public int getX() {
return x;
}
}
问题2。我们假设您需要决定以下类是否为ThreadSafe
// How can someone possibly know if this class is thread safe or not?
class IsItThreadSafe {
private final int aRandomField;
// the custom Point defined before
private final Point point;
public IsItThreadSafe(int aRandomField, Point point) {
this.aRandomField = aRandomField;
this.point = point;
}
public int add(){
return aRandomField + point.getX();
}
}
由于这个类只依赖于接口Point,而且我们现在对这个实现一无所知(哈哈),你怎么知道你的类是否是线程安全的?
我可以想象以下场景(pseydo代码)
class ConcurrentRunner{
public void run() {
MutablePoint mutablePoint = new MutablePoint(42);
IsItThreadSafe isItThreadSafe = new IsItThreadSafe(13, mutablePoint);
// here pass isItThreadSafe and mutablePoint to multiple threads
// each thread can modify mutablePoint and then run add()
// different threads may get different results, the class is not behaving
// the same, so it should not be treated as thread safe.
}
}
你觉得伙计们怎么样?我确信我在这里缺少一些基本的东西,但我不知道是什么!