简体   繁体   English

Java可见性和同步-Java示例思考

[英]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: 此代码中发生的是:

  • many (up to 100) threads are started, each executing the same code 启动了许多(最多100个)线程,每个线程执行相同的代码
  • in an infinite loop: 在无限循环中:
    • an unsynchronized method nextSerialNumber is called, which returns the result of the post-increment operator called on a static variable 调用了一个未同步的方法nextSerialNumber,该方法返回在静态变量上调用的后增量运算符的结果
    • a synchronized method contains is called, which checks if the returned value exists in the underlying collection 调用了一个同步方法contains,该方法检查返回的值是否存在于基础集合中
    • if yes, the program is terminated 如果是,程序终止
    • if not, the value is added to the underlying collection 如果不是,则将值添加到基础集合

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM