[英]Java visibility and synchronization - Thinking in Java example
I read now Thinking in Java, chapter about atomicity and visibility. 我现在阅读有关Java原子性和可见性的《 Thinking in Java》一书。 There is an example I don't understand. 有一个我不明白的例子。
public class SerialNumberGenerator {
private static volatile int serialNumber = 0;
public static int nextSerialNumber() {
return serialNumber++;
}
}
class CircularSet {
private int[] array;
private int len;
private int index = 0;
public CircularSet(int size) {
array = new int[size];
len = size;
for (int i = 0; i < size; i++) {
array[i] = -1;
}
}
synchronized void add(int i) {
array[index] = i;
index = ++index % len;
}
synchronized boolean contains(int val) {
for (int i = 0; i < len; i++) {
if (array[i] == val)
return true;
}
return false;
}
} }
public class SerialNumberChecker { 公共类SerialNumberChecker {
private static final int SIZE = 10;
private static CircularSet serials = new CircularSet(1000);
private static ExecutorService exec = Executors.newCachedThreadPool();
static class SerialChecker implements Runnable {
@Override
public void run() {
while (true) {
int serial = SerialNumberGenerator.nextSerialNumber();
if (serials.contains(serial)) {
System.out.println("Duplicate: " + serial);
System.exit(0);
}
serials.add(serial);
}
}
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < SIZE; i++) {
exec.execute(new SerialChecker());
}
}
} }
example output: 示例输出:
Duplicate: 228
I don't understand how is it possible. 我不知道怎么可能。 Even method nextSerialNumber() is not synchronized and all thread generate different values each thread has own value of serial and each are different. 即使方法nextSerialNumber()也不同步,并且所有线程生成不同的值,每个线程都有自己的serial值,并且每个线程都不同。 So how is it possible to find duplicate. 那么如何找到重复项。 I cannot imagine of threads execution. 我无法想象线程执行。
This example shows the post-increment operator is not atomic and not thread-safe. 此示例显示后递增运算符不是原子的也不是线程安全的。
What happens in this code is: 此代码中发生的是:
If the post-increment operation was thread-safe then the program would never print "Duplicate" and would never terminate, since every thread would be getting a different serial number value. 如果后递增操作是线程安全的,则该程序将永远不会打印“ Duplicate”并且永远不会终止,因为每个线程都将获得不同的序列号值。 This is not the case as two threads might get exactly the same serial number value. 并非如此,因为两个线程可能会获得完全相同的序列号值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.