同步块是否会触发数组的完整内存栅栏?

时间:2015-12-31 06:58:46

标签: java arrays multithreading volatile memory-fences

我对在Java中的线程之间安全地共享数组感到困惑,特别是内存栅栏和关键字synchronized

此Q& A很有帮助,但没有回答我的所有问题:Java arrays: synchronized + Atomic*, or synchronized suffices?

以下是演示该问题的示例代码。假设有一个工作线程池,通过方法SharedTable填充add(...)。完成所有工作线程后,最后一个线程将读取并保存数据。

演示此问题的示例代码:

public final class SharedTable {

    // Column-oriented data entries
    private final String[] data1Arr;
    private final int[] data2Arr;
    private final long[] data3Arr;
    private final AtomicInteger nextIndex;

    public SharedTable(int size) {
        this.data1Arr = new String[size];
        this.data2Arr = new int[size];
        this.data3Arr = new long[size];
        this.nextIndex = new AtomicInteger(0);
    }

    // Thread-safe: Called by worker threads
    public void addEntry(String data1, int data2, long data3) {
        final int index = nextIndex.getAndIncrement();
        data1Arr[index] = data1;
        data2Arr[index] = data2;
        data3Arr[index] = data3;
    }

    // Not thread-safe: Called by clean-up/joiner/collator thread...
    // after worker threads are complete
    public void save() {
        // Does this induce a full memory fence to ensure thread-safe reading of 
        synchronized (this) {
            final int usedSide = nextIndex.get();
            for (int i = 0; i < usedSide; ++i) {
                final String data1 = data1Arr[i];
                final int    data2 = data2Arr[i];
                final long   data3 = data3Arr[i];
                // TODO: Save data here
            }
        }
    }
}

上面的示例代码也可以使用Atomic*Array来实现,public final class SharedTable2 { // Column-oriented data entries private final AtomicReferenceArray<String> data1Arr; private final AtomicIntegerArray data2Arr; private final AtomicLongArray data3Arr; private final AtomicInteger nextIndex; public SharedTable2(int size) { ... } // Thread-safe: Called by worker threads public void addEntry(String data1, int data2, long data3) { final int index = nextIndex.getAndIncrement(); data1Arr.set(index, data1); ... } // Not thread-safe: Called by clean-up/joiner/collator thread... // after worker threads are complete public void save() { final int usedSide = nextIndex.get(); for (int i = 0; i < usedSide; ++i) { final String data1 = data1Arr.get(i); final int data2 = data2Arr.get(i); final long data3 = data3Arr.get(i); // TODO: Save data here } } } 充当“易失性值/引用数组”。

SharedTable
  1. SharedTable线程安全(和缓存一致)吗?
  2. SharedTable2(多?)效率更高,因为只需要一个内存栅栏,而Atomic*Array.set(...)会为每次调用 Upload .upload( { url: '/upload', data: { new_file_name: vm.new_name, //this is the filename I want file: vm.pdf } } ) 调用一个内存栅栏?
  3. 如果有帮助,我在64位x86硬件(Windows和Linux)上使用Java 8。

1 个答案:

答案 0 :(得分:4)

不,SharedTable不是线程安全的。只有从同步块中读取使用相同锁定从同步块写入的内容时,才会保证before-before。

由于写入是由同步块完成的,因此JMM不保证读取器线程可以看到写入。