FileChannel channel
没有volatile
,但boolean closed
有volatile
。以下是Java 8标准库中的内容。
public class FileInputStream{
private FileChannel channel = null;
private volatile boolean closed = false;
}
字段只在同步块中分配,因此不需要volatile。监视器锁定可保证可见性。
public FileChannel getChannel() {
synchronized (this) {
if (channel == null) {
channel = FileChannelImpl.open(fd, path, true, false, this);
}
return channel;
}
}
另请参阅volatile关键字的作用是什么?