Simple lock free stack in Java -
i implemented lock free stack follows:
import java.util.concurrent.atomic.atomicreference; /** * @author shuang.gao date: 2017/4/6 time: 14:39 */ public class stack<e> { private atomicreference<node<e>> head; public stack() { head = new atomicreference<>(); } public void push(e e) { node<e> node = new node<>(); node.item = e; (;;) { node<e> headnode = head.get(); node.next = headnode; if (head.compareandset(headnode, node)) { system.out.println("push: " + e); break; } } } public e pop() { node<e> headnode; (;;) { headnode = head.get(); if (headnode == null) { system.out.println("pop: null"); return null; } if (head.compareandset(headnode, headnode.next)) { break; } } system.out.println("pop: " + headnode.item); return headnode.item; } private class node<e> { private node<e> next; private e item; } }
lock free , no aba problem. there problem? thanks!
Comments
Post a Comment