Ver código fonte

[java] Use ReentrantLock instead of Semaphore as the implementation of java's Mutex

Closes #4878
Cauê Waneck 9 anos atrás
pai
commit
550d4bfa4d
2 arquivos alterados com 30 adições e 6 exclusões
  1. 6 6
      std/java/vm/Mutex.hx
  2. 24 0
      tests/unit/src/unit/issues/Issue4878.hx

+ 6 - 6
std/java/vm/Mutex.hx

@@ -20,11 +20,11 @@
  * DEALINGS IN THE SOFTWARE.
  */
  package java.vm;
-import java.util.concurrent.Semaphore;
+import java.util.concurrent.locks.ReentrantLock;
 
 @:native('haxe.java.vm.Mutex') class Mutex
 {
-	@:private var lock:Semaphore;
+	@:private var lock:ReentrantLock;
 
 	/**
 		Creates a mutex, which can be used to acquire a temporary lock to access some resource.
@@ -32,7 +32,7 @@ import java.util.concurrent.Semaphore;
 	**/
 	public function new()
 	{
-		this.lock = new Semaphore(1);
+		this.lock = new ReentrantLock();
 	}
 
 	/**
@@ -40,7 +40,7 @@ import java.util.concurrent.Semaphore;
 	**/
 	public function tryAcquire():Bool
 	{
-		return this.lock.tryAcquire();
+		return this.lock.tryLock();
 	}
 
 	/**
@@ -49,7 +49,7 @@ import java.util.concurrent.Semaphore;
 	**/
 	public function acquire():Void
 	{
-		this.lock.acquire();
+		this.lock.lock();
 	}
 
 	/**
@@ -57,6 +57,6 @@ import java.util.concurrent.Semaphore;
 	**/
 	public function release():Void
 	{
-		this.lock.release();
+		this.lock.unlock();
 	}
 }

+ 24 - 0
tests/unit/src/unit/issues/Issue4878.hx

@@ -0,0 +1,24 @@
+package unit.issues;
+#if java
+import java.vm.Thread;
+import java.vm.Mutex;
+#end
+
+class Issue4878 extends Test {
+  function test() {
+#if java
+    var mutex = new Mutex();
+    var thread = Thread.create(function() {
+      mutex.acquire();
+      mutex.acquire();
+      mutex.release();
+      Sys.sleep(.2);
+      mutex.release();
+    });
+    Sys.sleep(0.05);
+    f(mutex.tryAcquire());
+    Sys.sleep(.3);
+    t(mutex.tryAcquire());
+#end
+  }
+}