Java多线程
todo
Java Memory Model
http://www.cs.umd.edu/~pugh/java/memoryModel/jsr-133-faq.html
其中的volatile语义要求jvm乱序执行时,保证内存屏障
这里提到的CopyOnWriteArrayList的Set方法
/** * Replaces the element at the specified position in this list with the * specified element. * * @throws IndexOutOfBoundsException {@inheritDoc} */ public E set(int index, E element) { final ReentrantLock lock = this.lock; lock.lock(); try { Object[] elements = getArray(); Object oldValue = elements[index]; if (oldValue != element) { int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len); newElements[index] = element; setArray(newElements); } else { // Not quite a no-op; ensures volatile write semantics setArray(elements); } return (E)oldValue; } finally { lock.unlock(); } }
其中的else分支,是因为要涉及到操作elements(private volatile transient Object[] array;),保证不被重排序。
http://cs.oswego.edu/pipermail/concurrency-interest/2010-February/006888.html
set() wants to guarantee safe publication. So if some unsynchronized writes have been made to element prior to the call to set(), then we ensure that those are ordered before any subsequent get()s. addAllAbsent() probably does not want to make this guarantee if no elements are absent.
https://www.quora.com/How-does-System-out-println-affect-memory-visibility-under-concurrent-enviroment