Skip to content

Commit

Permalink
🐞 fix: #389 Fix race condition in V8Guard
Browse files Browse the repository at this point in the history
  • Loading branch information
caoccao committed Sep 6, 2024
1 parent 9b54446 commit 4885852
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 6 deletions.
6 changes: 4 additions & 2 deletions src/main/java/com/caoccao/javet/interop/V8Guard.java
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,11 @@ public final class V8Guard implements IJavetClosable {
*/
public void cancel() {
if (!isClosed()) {
PriorityBlockingQueue<V8Guard> v8GuardQueue = v8Runtime.getV8Host().getV8GuardDaemon().getV8GuardQueue();
boolean ignored = v8GuardQueue.remove(this);
closed = true;
synchronized (v8Runtime.getCloseLock()) {
PriorityBlockingQueue<V8Guard> v8GuardQueue = v8Runtime.getV8Host().getV8GuardDaemon().getV8GuardQueue();
boolean ignored = v8GuardQueue.remove(this);
}
}
}

Expand Down
15 changes: 11 additions & 4 deletions src/main/java/com/caoccao/javet/interop/V8Host.java
Original file line number Diff line number Diff line change
Expand Up @@ -573,7 +573,7 @@ public void run() {
if (!(!v8Guard.isDebugModeEnabled() && IS_IN_DEBUG_MODE)) {
V8Runtime v8Runtime = v8Guard.getV8Runtime();
synchronized (v8Runtime.getCloseLock()) {
if (!v8Runtime.isClosed() && v8Runtime.isInUse()) {
if (!v8Guard.isClosed() && !v8Runtime.isClosed() && v8Runtime.isInUse()) {
v8Runtime.terminateExecution();
v8Runtime.getLogger().logWarn(
"Execution was terminated after {0}ms.",
Expand All @@ -582,9 +582,16 @@ public void run() {
}
}
} else {
v8GuardQueue.add(v8Guard);
long sleepMillis = Math.min(v8Guard.getEndTimeMillis() - now, sleepIntervalMillis);
TimeUnit.MILLISECONDS.sleep(sleepMillis);
V8Runtime v8Runtime = v8Guard.getV8Runtime();
synchronized (v8Runtime.getCloseLock()) {
if (!v8Guard.isClosed() && !v8Runtime.isClosed()) {
v8GuardQueue.add(v8Guard);
long sleepMillis = Math.min(v8Guard.getEndTimeMillis() - now, sleepIntervalMillis);
if (sleepMillis > 0) {
TimeUnit.MILLISECONDS.sleep(sleepMillis);
}
}
}
}
} catch (InterruptedException ignored) {
break;
Expand Down

0 comments on commit 4885852

Please sign in to comment.