AtomicList.hx 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package java.vm;
  2. import java.util.concurrent.atomic.AtomicReference;
  3. /**
  4. A lock-free queue implementation
  5. **/
  6. @:native('haxe.java.vm.AtomicList')
  7. @:nativeGen class AtomicList<T>
  8. {
  9. @:volatile @:private var head:AtomicNode<T>;
  10. @:volatile @:private var tail:AtomicReference<AtomicNode<T>>;
  11. public function new()
  12. {
  13. this.head = new AtomicNode(null);
  14. this.head.set(new AtomicNode(null));
  15. this.tail = new AtomicReference(head);
  16. }
  17. public function add(v:T)
  18. {
  19. var n = new AtomicNode(v), tail = this.tail;
  20. var p = null;
  21. while( !((p = tail.get()).compareAndSet(null, n)) )
  22. {
  23. tail.compareAndSet(p, p.get());
  24. }
  25. tail.compareAndSet(p, n);
  26. }
  27. public function pop():Null<T>
  28. {
  29. var p = null, pget = null, head = head;
  30. do
  31. {
  32. p = head.get();
  33. if ( (pget = p.get()) == null)
  34. return null; //empty
  35. } while(!head.compareAndSet(p, pget));
  36. var ret = pget.value;
  37. pget.value = null;
  38. return ret;
  39. }
  40. public function peek()
  41. {
  42. var ret = head.get();
  43. if (ret == null) return null; //empty
  44. return ret.value;
  45. }
  46. public function peekLast()
  47. {
  48. return tail.get().value;
  49. }
  50. }
  51. @:native('haxe.java.vm.AtomicNode')
  52. @:nativeGen class AtomicNode<T> extends AtomicReference<AtomicNode<T>>
  53. {
  54. public var value:T;
  55. public function new(value)
  56. {
  57. super();
  58. this.value = value;
  59. }
  60. }