@@ -136,8 +136,11 @@ const WARM_MIN_CLASSES = 200;
136136
137137const WOKEN_RUN = 16 ;
138138
139- // instructions a thread runs per turn
139+ // instructions a thread runs per turn, at most and at least
140140const SLICE = 20000 ;
141+ const MIN_SLICE = 200 ;
142+ // a turn this long (ms) is a spin or a long computation
143+ const LONG_TURN = 0.05 ;
141144
142145export class JVM {
143146 readonly opts : JvmOptions ;
@@ -164,6 +167,7 @@ export class JVM {
164167 // threads another thread woke in its turn: they run before the rotation, so a hand-off does not wait behind spinners
165168 private woken : JThread [ ] = [ ] ;
166169 private wokenStreak = 0 ;
170+ private shortTurns = 0 ;
167171 private queued = new Set < JThread > ( ) ;
168172 private scheduled = false ;
169173 private hashSeed = 0x2545f491 ;
@@ -1109,12 +1113,32 @@ export class JVM {
11091113 this . queued . delete ( t ) ;
11101114 if ( t . state !== RUNNABLE ) continue ;
11111115 sched . thread = t ;
1112- spent += SLICE - runThread ( t , SLICE ) ;
1116+ const q = t . quantum || SLICE ;
1117+ // only a thread that stayed runnable is timed, so hand-offs read no clock
1118+ const t0 = t . timed ? performance . now ( ) : 0 ;
1119+ spent += q - runThread ( t , q ) ;
11131120 if ( t . unmounting !== null ) unmountBlocked ( t ) ;
1114- if ( t . state === RUNNABLE && ! this . queued . has ( t ) ) {
1115- this . queued . add ( t ) ;
1116- this . runQueue . push ( t ) ;
1121+ if ( t . state !== RUNNABLE ) {
1122+ this . shortTurns ++ ;
1123+ t . quantum = SLICE ;
1124+ t . timed = false ;
1125+ } else {
1126+ // a thread that runs long turns while others run short ones gets shorter turns
1127+ const now = performance . now ( ) ;
1128+ const dt = now - t0 ;
1129+ const others = this . shortTurns !== t . shortSeen && ( this . runQueue . length > 0 || this . woken . length > 0 ) ;
1130+ const long = t . timed && dt > LONG_TURN ;
1131+ if ( t . timed && q === SLICE && ! long ) this . shortTurns ++ ;
1132+ t . quantum = ! others ? SLICE : long ? Math . max ( MIN_SLICE , q >> 1 ) : q ;
1133+ t . timed = true ;
1134+ if ( ! this . queued . has ( t ) ) {
1135+ this . queued . add ( t ) ;
1136+ this . runQueue . push ( t ) ;
1137+ }
1138+ if ( now > end ) break ;
1139+ spent = 0 ;
11171140 }
1141+ t . shortSeen = this . shortTurns ;
11181142 if ( sched . pause ) break ;
11191143 if ( spent >= SLICE ) {
11201144 if ( performance . now ( ) > end ) break ;
0 commit comments