java - Volatile and ArrayBlockingQueue and perhaps other concurrent objects -
i understand (or @ least think do;) ) principle behind volatile
keyword. when looking concurrenthashmap
source, can see nodes , values declared volatile
, makes sense because value can written/read more 1 thread:
static class node<k,v> implements map.entry<k,v> { final int hash; final k key; volatile v val; volatile node<k,v> next; ... }
however, looking arrayblockingqueue
source, it's plain array being updated/read multiple threads:
private void enqueue(e x) { // assert lock.getholdcount() == 1; // assert items[putindex] == null; final object[] items = this.items; items[putindex] = x; if (++putindex == items.length) putindex = 0; count++; notempty.signal(); }
how guaranteed value inserted items[putindex]
visible thread, providing element inside array not volatile (i know declaring array doesnt have effect anyhow on elements themselves) ? couldn't thread hold cached copy of array?
thanks
notice enqueue
private
. calls (offer(e), offer(e, long, timeunit), put(e)
). notice every 1 of looks like:
public void put(e e) throws interruptedexception { checknotnull(e); final reentrantlock lock = this.lock; lock.lockinterruptibly(); try { // stuff. enqueue(e); } { lock.unlock(); } }
so can conclude every call enqueue
protected lock.lock() ... lock.unlock()
don't need volatile
because lock.lock/unlock
memory barrier.
Comments
Post a Comment