Skip to content

Commit 4885852

Browse files
committed
🐞 fix: #389 Fix race condition in V8Guard
1 parent 9b54446 commit 4885852

File tree

2 files changed

+15
-6
lines changed

2 files changed

+15
-6
lines changed

src/main/java/com/caoccao/javet/interop/V8Guard.java

+4-2
Original file line numberDiff line numberDiff line change
@@ -83,9 +83,11 @@ public final class V8Guard implements IJavetClosable {
8383
*/
8484
public void cancel() {
8585
if (!isClosed()) {
86-
PriorityBlockingQueue<V8Guard> v8GuardQueue = v8Runtime.getV8Host().getV8GuardDaemon().getV8GuardQueue();
87-
boolean ignored = v8GuardQueue.remove(this);
8886
closed = true;
87+
synchronized (v8Runtime.getCloseLock()) {
88+
PriorityBlockingQueue<V8Guard> v8GuardQueue = v8Runtime.getV8Host().getV8GuardDaemon().getV8GuardQueue();
89+
boolean ignored = v8GuardQueue.remove(this);
90+
}
8991
}
9092
}
9193

src/main/java/com/caoccao/javet/interop/V8Host.java

+11-4
Original file line numberDiff line numberDiff line change
@@ -573,7 +573,7 @@ public void run() {
573573
if (!(!v8Guard.isDebugModeEnabled() && IS_IN_DEBUG_MODE)) {
574574
V8Runtime v8Runtime = v8Guard.getV8Runtime();
575575
synchronized (v8Runtime.getCloseLock()) {
576-
if (!v8Runtime.isClosed() && v8Runtime.isInUse()) {
576+
if (!v8Guard.isClosed() && !v8Runtime.isClosed() && v8Runtime.isInUse()) {
577577
v8Runtime.terminateExecution();
578578
v8Runtime.getLogger().logWarn(
579579
"Execution was terminated after {0}ms.",
@@ -582,9 +582,16 @@ public void run() {
582582
}
583583
}
584584
} else {
585-
v8GuardQueue.add(v8Guard);
586-
long sleepMillis = Math.min(v8Guard.getEndTimeMillis() - now, sleepIntervalMillis);
587-
TimeUnit.MILLISECONDS.sleep(sleepMillis);
585+
V8Runtime v8Runtime = v8Guard.getV8Runtime();
586+
synchronized (v8Runtime.getCloseLock()) {
587+
if (!v8Guard.isClosed() && !v8Runtime.isClosed()) {
588+
v8GuardQueue.add(v8Guard);
589+
long sleepMillis = Math.min(v8Guard.getEndTimeMillis() - now, sleepIntervalMillis);
590+
if (sleepMillis > 0) {
591+
TimeUnit.MILLISECONDS.sleep(sleepMillis);
592+
}
593+
}
594+
}
588595
}
589596
} catch (InterruptedException ignored) {
590597
break;

0 commit comments

Comments
 (0)