volatile 引用和引用对象有什么区别
java中的volatile关键字仅保证对变量本身的读写操作具有原子性和可见性,而不会保证该变量所指向对象的内部状态变化对其他线程的可见性。这意味着当使用volatile修饰一个引用时,只有将该引用重新赋值为一个新的对象实例,其他线程才能立即看到这一变化;如果仅仅修改了该引用所指向对象的字段或属性,由于缺乏同步机制,其他线程可能仍然读取到旧的数据。因此,volatile适用于“引用本身”的变化场景,而对于“引用对象”的状态变更,则需要借助synchronized、lock或java.util.concurrent包下的原子类等同步手段来确保数据一致性。

如何验证volatile对引用的可见性
要验证volatile对引用的可见性,可以编写一个简单的多线程程序,其中一个线程不断修改共享的volatile引用指向的新对象,另一个线程则持续检查该引用是否已更新。在这个场景中,主线程负责创建新的对象并赋值给volatile变量,工作线程则循环读取该变量并打印其内容。通过观察输出结果,可以看到工作线程能够及时感知到引用的变化,从而证明volatile确实保证了引用的可见性。

public class VolatileReferenceTest {
private static volatile SharedObject sharedObject = new SharedObject("Initial");
public static void main(String[] args) throws InterruptedException {
Thread updater = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try { Thread.sleep(100); } catch (InterruptedException e) {}
sharedObject = new SharedObject("Updated " + i);
}
});
Thread reader = new Thread(() -> {
String lastSeen = null;
while (true) {
String current = sharedObject.getValue();
if (!current.equals(lastSeen)) {
System.out.println("Reader sees: " + current);
lastSeen = current;
}
if (lastSeen != null && lastSeen.contains("4")) break;
}
});
updater.start();
reader.start();
reader.join();
}
}
class SharedObject {
private final String value;
public SharedObject(String value) { this.value = value; }
public String getValue() { return value; }
}为什么volatile不能保证引用对象内部状态的可见性
尽管volatile确保了引用本身的可见性,但它并不提供对引用对象内部字段的任何同步保障。例如,如果一个线程修改了某个非volatile字段的值,即使该字段所在的对象被volatile引用指向,其他线程也可能因为缓存一致性协议的原因而无法立即看到这些更改。为了演示这一点,我们可以扩展之前的示例,让SharedObject包含一个非volatile字段,并在多个线程间并发修改它。此时,如果不加额外的同步措施,读者线程可能会读到不一致或过时的数据。
立即学习“Java免费学习笔记(深入)”;
public class VolatileObjectStateTest {
private static volatile SharedObjectWithState sharedObject = new SharedObjectWithState();
public static void main(String[] args) throws InterruptedException {
Thread modifier = new Thread(() -> {
for (int i = 0; i < 100; i++) {
sharedObject.setCounter(i);
}
});
Thread checker = new Thread(() -> {
int maxSeen = 0;
while (maxSeen < 99) {
int current = sharedObject.getCounter();
if (current > maxSeen) {
System.out.println("Checker sees counter: " + current);
maxSeen = current;
}
}
});
modifier.start();
checker.start();
checker.join();
}
}
class SharedObjectWithState {
private int counter; // Not volatile
public void setCounter(int counter) { this.counter = counter; }
public int getCounter() { return counter; }
}


















