Lock.hx 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package java.vm;
  2. import java.Lib;
  3. @:native('haxe.java.vm.Lock') class Lock
  4. {
  5. @:private @:volatile var releasedCount = 0;
  6. /**
  7. Creates a new lock, which is initially locked
  8. **/
  9. public function new()
  10. {
  11. }
  12. /**
  13. Waits for a lock to be released and acquire it.
  14. If `timeout` (in seconds) is not null and expires then the returned value is false
  15. **/
  16. public function wait(?timeout : Float) : Bool
  17. {
  18. var ret = false;
  19. untyped __lock__(this,
  20. {
  21. if (--releasedCount >= 0)
  22. return true;
  23. if (timeout == null)
  24. {
  25. try
  26. {
  27. untyped __java__("this.wait()");
  28. }
  29. catch(e:Dynamic) {
  30. throw e;
  31. }
  32. } else {
  33. var t:Dynamic = this;
  34. try
  35. {
  36. var t:haxe.Int64 = cast timeout * 1000;
  37. untyped __java__("this.wait(t)");
  38. }
  39. catch(e:Dynamic) {
  40. throw e;
  41. }
  42. }
  43. ret = this.releasedCount >= 0;
  44. if (!ret && ++this.releasedCount == 0) //even if timeout failed, we should release the lock; Other locks may be released then
  45. {
  46. untyped this.notify();
  47. }
  48. });
  49. return ret;
  50. }
  51. /**
  52. Release a lock. The thread does not need to own the lock to be able to release it.
  53. If a lock is released several times, it can be acquired as many times
  54. **/
  55. public function release()
  56. {
  57. untyped __lock__(this,
  58. {
  59. if (++releasedCount >= 0)
  60. {
  61. untyped this.notify();
  62. }
  63. });
  64. }
  65. }