Skip to content

Commit b422b7c

Browse files
committedMay 15, 2020
Prevent run being called when not in appropriate state
1 parent 5c3e077 commit b422b7c

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed
 

‎src/java.base/share/classes/java/lang/VirtualThread.java

+17-7
Original file line numberDiff line numberDiff line change
@@ -193,11 +193,15 @@ private void runContinuation() {
193193

194194
// set state to ST_RUNNING
195195
short initialState = stateGet();
196-
assert initialState == ST_STARTED || initialState == ST_RUNNABLE;
197-
stateGetAndSet(ST_RUNNING);
198-
if (initialState == ST_RUNNABLE) {
196+
if (initialState == ST_STARTED
197+
&& stateCompareAndSet(ST_STARTED, ST_RUNNING)) {
198+
// first run
199+
} else if (initialState == ST_RUNNABLE
200+
&& stateCompareAndSet(ST_RUNNABLE, ST_RUNNING)) {
199201
// consume parking permit
200-
parkPermitGetAndSet(false);
202+
parkPermitSet(false);
203+
} else {
204+
throw new RuntimeException();
201205
}
202206

203207
boolean firstRun = (initialState == ST_STARTED);
@@ -369,7 +373,7 @@ private void yieldFailed() {
369373
throw new InternalError();
370374

371375
// consume parking permit
372-
parkPermitGetAndSet(false);
376+
parkPermitSet(false);
373377

374378
// switch back to virtual thread
375379
thread.setVirtualThread(this);
@@ -436,7 +440,7 @@ static void parkNanos(long nanos) {
436440
} else {
437441
// consume permit when not parking
438442
vthread.tryYield();
439-
vthread.parkPermitGetAndSet(false);
443+
vthread.parkPermitSet(false);
440444
}
441445
}
442446

@@ -891,7 +895,7 @@ private StackTraceElement[] tryGetStackTrace() {
891895
// -- wrappers for VarHandle methods --
892896

893897
private short stateGet() {
894-
return (short) STATE.get(this);
898+
return state;
895899
}
896900

897901
private short stateGetAndSet(short newValue) {
@@ -902,6 +906,12 @@ private boolean stateCompareAndSet(short expectedValue, short newValue) {
902906
return STATE.compareAndSet(this, expectedValue, newValue);
903907
}
904908

909+
private void parkPermitSet(boolean newValue) {
910+
if (parkPermit != newValue) {
911+
parkPermit = newValue;
912+
}
913+
}
914+
905915
private boolean parkPermitGetAndSet(boolean newValue) {
906916
return (boolean) PARK_PERMIT.getAndSet(this, newValue);
907917
}

0 commit comments

Comments
 (0)
Please sign in to comment.