最近发现了这样的java并发面试任务:
使用push和pop两种方法编写简单的无锁堆栈。
I made the content:
import java.util.concurrent.atomic.AtomicInteger;
public class Stack {
private AtomicInteger count = new AtomicInteger(-1);
private Object[] data = new Object[1000];
public void push(Object o) {
int c = count.incrementAndGet();
data[c] = o;
}
public Object pop() {
Object top;
int c;
while (true) {
c = count.get();
if (c == -1) return null;
top = data[c];
if (count.compareAndSet(c, c-1))
return top;
}
}
}
是否与预期的方法相似?或者"无锁堆栈"意味着不同的东西?请帮助java面试新手。
考虑使用Java的原子整数和原子函数,您的方向肯定是正确的。因此,这将是一个无锁堆栈,如:没有显式锁。
当并发访问时,它仍然是不正确的,然而,这是相对简单的证明:想象你的push()线程在获取计数和向堆栈添加新元素之间阻塞(data[c] = 0),同时pop()线程出现,获得更高的计数,然后弹出…怎么啦?在堆栈中那个位置的内存中发生的任何东西,但不包括对象0(因为它还没有插入)。
这就是无锁,数组支持堆栈的问题,理论上你有两件事需要调整,特定单元格的计数和内容,你不能同时原子地做这两件事。我不知道有任何无锁的数组支持的堆栈算法。
有一些链表支持的堆栈算法是无锁的,因为在这种情况下,你可以创建一个新的节点,给它分配内容,你只需要自动执行一个操作:改变顶部指针。
如果你对这个论点感兴趣,最好的文学作品是Shavit和Herlihy的《the Art of Multiprocessor Programming》,它描述了许多不同的数据结构,包括无锁和基于锁的。虽然Maged Michael在他的SMR论文第8页第4.2点提到了它,但我现在找不到任何详细描述"通常"无锁堆栈算法的论文,而且我自己也做了一个C99实现。
import java.util.Random;
import java.util.concurrent.atomic.AtomicReference;
public class LockFreeStack {
public static void main(String... args) {
LFStack<String> stack = new LFStack<String>();
for (int i = 0; i < 10; i++) {
Thread t = new Thread(new RandomStackUse(stack));
t.setName("My stack thread " + i);
t.start();
}
}
private static class LFStack<E> {
private volatile AtomicReference<Node<E>> head = new AtomicReference<Node<E>>();
public E peek() {
E payload = null;
Node<E> node = head.get();
if (node != null) { payload = node.payload; }
return payload;
}
public E pop() {
E payload;
while (true) {
Node<E> oldHeadNode = head.get();
if (oldHeadNode == null) { return null; }
payload = head.get().payload;
if (head.compareAndSet(oldHeadNode, oldHeadNode.next.get())) { break; }
//System.out.println("Retry");
}
return payload;
}
public void push(E e) {
Node<E> oldHeadNode = new Node<E>(e);
while (true) {
Node<E> oldRootNode = head.get();
if (oldRootNode != null) { oldHeadNode.next.set(oldRootNode); }
if (head.compareAndSet(oldRootNode, oldHeadNode)) { break; }
//System.out.println("Retry");
}
}
}
//to be used as LinkedList chain <Node> => <Node> => <Node> => null
private static class Node<E> {
private E payload;
private AtomicReference<Node<E>> next;
public Node(E e) {
payload = e;
next = new AtomicReference<Node<E>>();
}
}
public static class RandomStackUse implements Runnable {
private LFStack<String> stack;
private Random rand = new Random();
public RandomStackUse(LFStack<String> stack) {this.stack = stack;}
@Override
public void run() {
long counter = 0;
while (true) {
if (rand.nextInt() % 3 == 0) {
stack.push(String.valueOf(counter++));
//System.out.println(String.format("%s pushed %d", Thread.currentThread().getName(), counter));
}
if (rand.nextInt() % 3 == 1) {
String value = stack.pop();
//System.out.println(String.format("%s pop %s", Thread.currentThread().getName(), value));
}
if (rand.nextInt() % 3 == 2) {
String value = stack.peek();
//System.out.println(String.format("%s peek %s", Thread.currentThread().getName(), value));
}
}
}
}
}
public class MyConcurrentStack<T>
{
private AtomicReference<Node> head = new AtomicReference<Node>();
public MyConcurrentStack()
{
}
public void push(T t)
{
Node<T> n = new Node<T>(t);
Node<T> current;
do
{
current = head.get();
n.setNext(current);
}while(!head.compareAndSet(current, n));
}
public T pop()
{
Node<T> currentHead = null;
Node<T> futureHead = null;
do
{
currentHead = head.get();
if(currentHead == null)
{
return null;
}
futureHead = currentHead.next;
}while(!head.compareAndSet(currentHead, futureHead));
return currentHead.data;
}
public T peek()
{
Node<T> n = head.get();
if(n==null)
{
return null;
}
else
{
return n.data;
}
}
private static class Node<T>
{
private final T data;
private Node<T> next;
private Node(T data)
{
this.data = data;
}
private void setNext(Node next)
{
this.next = next;
}
}
public static void main(String[] args)
{
MyConcurrentStack m = new MyConcurrentStack();
m.push(12);
m.push(13);
m.push(15);
System.out.println(m.pop());
System.out.println(m.pop());
System.out.println(m.pop());
System.out.println(m.pop());
}
}
代码是不言自明的。如果有人需要解释,请告诉我。堆栈按照下面的图形成:
... ... ...
| |-->| | -->| |
... ... ...
^
|
current head
可以使用BlockingQueue use方法put()插入元素,使用方法drainTo(Collection c)获取元素。然后从c的末尾读取元素。