@@ -449,12 +449,7 @@ public void testGcedContext() {
449
449
Assert .assertEquals (expected , handler .getLog ());
450
450
Reference <Context > gcedContextRef = new WeakReference <>(gcedContext );
451
451
gcedContext = null ;
452
- for (int i = 1 ; gcedContextRef .get () != null ; i ++) {
453
- if (i == 10 ) {
454
- throw new AssertionError ("Cannot free context." );
455
- }
456
- System .gc ();
457
- }
452
+ assertGc ("Cannot free context." , gcedContextRef );
458
453
handler = new TestHandler ();
459
454
Context newContext = Context .newBuilder ().logHandler (handler ).build ();
460
455
newContext .eval (LoggingLanguageFirst .ID , "" );
@@ -479,12 +474,7 @@ public void testGcedContext2() {
479
474
Assert .assertEquals (expected , contextHandler .getLog ());
480
475
Reference <Context > gcedContextRef = new WeakReference <>(gcedContext );
481
476
gcedContext = null ;
482
- for (int i = 1 ; gcedContextRef .get () != null ; i ++) {
483
- if (i == 10 ) {
484
- throw new AssertionError ("Cannot free context." );
485
- }
486
- System .gc ();
487
- }
477
+ assertGc ("Cannot free context." , gcedContextRef );
488
478
contextHandler .clear ();
489
479
context .eval (LoggingLanguageFirst .ID , "" );
490
480
expected = new ArrayList <>();
@@ -614,6 +604,38 @@ private static LoggerNode createLevelsTree(Map<String, Level> levels) {
614
604
return root ;
615
605
}
616
606
607
+ private static void assertGc (final String message , final Reference <?> ref ) {
608
+ int blockSize = 100_000 ;
609
+ final List <byte []> blocks = new ArrayList <>();
610
+ for (int i = 0 ; i < 50 ; i ++) {
611
+ if (ref .get () == null ) {
612
+ return ;
613
+ }
614
+ try {
615
+ System .gc ();
616
+ } catch (OutOfMemoryError oom ) {
617
+ }
618
+ try {
619
+ System .runFinalization ();
620
+ } catch (OutOfMemoryError oom ) {
621
+ }
622
+ try {
623
+ blocks .add (new byte [blockSize ]);
624
+ blockSize = (int ) (blockSize * 1.3 );
625
+ } catch (OutOfMemoryError oom ) {
626
+ blockSize >>>= 1 ;
627
+ }
628
+ if (i % 10 == 0 ) {
629
+ try {
630
+ Thread .sleep (500 );
631
+ } catch (InterruptedException ie ) {
632
+ break ;
633
+ }
634
+ }
635
+ }
636
+ Assert .fail (message );
637
+ }
638
+
617
639
public static final class LoggingContext {
618
640
private final TruffleLanguage .Env env ;
619
641
0 commit comments