Is the following code thread-safe on concurrent access to List?
Does the volatile qualifies add any value here?
class concurrentList{
private AtomicBoolean locked = new AtomicBoolean(true);
volatile List<Integer> list=new LinkedList<Integer>();
long start = System.currentTimeMillis();
long end = start + 60*100;
public void push(int e){
while(!locked.get());
list.add(e);
while(!locked.compareAndSet(true,false));
}
public int pop(){
int elem;
while(locked.get());
elem=(Integer)list.remove(0);
while(!locked.compareAndSet(false,true));
return elem;
}
....
}
No, it's not thread-safe. Two threads calling push()
can perfectly both read the locked as true, then add concurrently to the linked list. Since a LinkedList is not thread-safe, your code is not thread-safe.
To lock, use a lock, not an AtomicBoolean.