@@ -383,9 +383,9 @@ export function setMaxHeap(bytes: number) {
383383 explicitMaxHeap = true ;
384384}
385385export function hasMaxHeap ( ) { return explicitMaxHeap ; }
386- let allocationCheck : { cap : number ; step : number ; allocated : number ; baseline : number ; enabled : boolean ; usage : ( ) => number ; gc ?: ( ) => void } | null = null ;
386+ let allocationCheck : { cap : number ; step : number ; allocated : number ; baseline : number ; enabled : boolean ; over : boolean ; usage : ( ) => number ; gc ?: ( ) => void } | null = null ;
387387export function setAllocationCheck ( cap : number , usage : ( ) => number , gc ?: ( ) => void ) {
388- allocationCheck = { cap, step : Math . min ( cap , Math . max ( 4 << 20 , cap / 16 ) ) , allocated : 0 , baseline : 0 , enabled : false , usage, gc } ;
388+ allocationCheck = { cap, step : Math . min ( cap , Math . max ( 4 << 20 , cap / 16 ) ) , allocated : 0 , baseline : 0 , enabled : false , over : false , usage, gc } ;
389389}
390390export function clearAllocationCheck ( ) { allocationCheck = null ; }
391391export function resetAllocationCheck ( ) {
@@ -400,10 +400,15 @@ function allocated(bytes: number) {
400400 check . allocated += bytes ;
401401 if ( check . gc ? check . allocated < check . step : check . allocated <= check . cap ) return ;
402402 check . allocated = 0 ;
403- if ( check . usage ( ) - check . baseline > check . cap ) {
404- check . gc ?.( ) ;
405- if ( check . usage ( ) - check . baseline > check . cap ) throw new PendingThrow ( "java/lang/OutOfMemoryError" , "Java heap space" ) ;
403+ if ( check . usage ( ) - check . baseline > check . cap ) check . gc ?.( ) ;
404+ // node frees array buffers after a collection, not during it, so one reading
405+ // over the cap can still count garbage: throw on the second in a row
406+ const over = check . usage ( ) - check . baseline > check . cap ;
407+ if ( over && check . over ) {
408+ check . over = false ;
409+ throw new PendingThrow ( "java/lang/OutOfMemoryError" , "Java heap space" ) ;
406410 }
411+ check . over = over ;
407412}
408413const ELEM_SIZE : Record < string , number > = { Z : 1 , B : 1 , C : 2 , S : 2 , I : 4 , F : 4 , J : 8 , D : 8 , L : 4 } ;
409414
0 commit comments