AtomicList.hx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * Copyright (C)2005-2015 Haxe Foundation
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a
  5. * copy of this software and associated documentation files (the "Software"),
  6. * to deal in the Software without restriction, including without limitation
  7. * the rights to use, copy, modify, merge, publish, distribute, sublicense,
  8. * and/or sell copies of the Software, and to permit persons to whom the
  9. * Software is furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  20. * DEALINGS IN THE SOFTWARE.
  21. */
  22. package java.vm;
  23. import java.util.concurrent.atomic.AtomicReference;
  24. /**
  25. A lock-free queue implementation
  26. **/
  27. @:native('haxe.java.vm.AtomicList')
  28. @:nativeGen class AtomicList<T>
  29. {
  30. @:volatile @:private var head:AtomicNode<T>;
  31. @:volatile @:private var tail:AtomicReference<AtomicNode<T>>;
  32. public function new()
  33. {
  34. this.head = new AtomicNode(null);
  35. this.head.set(new AtomicNode(null));
  36. this.tail = new AtomicReference(head);
  37. }
  38. public function add(v:T)
  39. {
  40. var n = new AtomicNode(v), tail = this.tail;
  41. var p = null;
  42. while( !((p = tail.get()).compareAndSet(null, n)) )
  43. {
  44. tail.compareAndSet(p, p.get());
  45. }
  46. tail.compareAndSet(p, n);
  47. }
  48. public function pop():Null<T>
  49. {
  50. var p = null, pget = null, head = head;
  51. do
  52. {
  53. p = head.get();
  54. if ( (pget = p.get()) == null)
  55. return null; //empty
  56. } while(!head.compareAndSet(p, pget));
  57. var ret = pget.value;
  58. pget.value = null;
  59. return ret;
  60. }
  61. public function peek()
  62. {
  63. var ret = head.get();
  64. if (ret == null) return null; //empty
  65. return ret.value;
  66. }
  67. public function peekLast()
  68. {
  69. return tail.get().value;
  70. }
  71. }
  72. @:native('haxe.java.vm.AtomicNode')
  73. @:nativeGen class AtomicNode<T> extends AtomicReference<AtomicNode<T>>
  74. {
  75. public var value:T;
  76. public function new(value)
  77. {
  78. super();
  79. this.value = value;
  80. }
  81. }