StringInterner { public static String intern(final String s) { final String exists = map.putIfAbsent(s, s); return (exists == null) ? s : exists; } private  StringInterner(); static String intern(final String s); static void clear(); static void cleanUpGarbage(); static int size();  }
@Test public void testWeakRefStringInterner() { final double value = Math.random(); final String text = "HELLO WORLD! "; String firstToBeInterned = text + value; String firstInterned = StringInterner.intern(firstToBeInterned); assertSame(firstInterned, firstToBeInterned, "first interned received different reference"); final String secondToBeInterned = text + value; assertNotSame(firstToBeInterned, secondToBeInterned, "first and second interned are same reference - VM is breaking this test with optimizations"); String secondInterned = StringInterner.intern(secondToBeInterned); assertEquals(secondInterned, firstInterned, "second interned changed value during interning - first vs second"); assertEquals(secondInterned, secondToBeInterned, "second interned changed value during interning - second input vs output"); assertNotSame(secondInterned, secondToBeInterned, "second interned delivered same reference back"); assertSame(firstInterned, secondInterned, "first interned received different reference"); final var referenceQueue = new ReferenceQueue<String>(); final var weakRef = new WeakReference<>(firstInterned, referenceQueue); firstToBeInterned = null; firstInterned = null; secondInterned = null; int i = 0; final int maxAttempts = 3; while (referenceQueue.poll() == null && i < maxAttempts) { ++i; System.gc(); System.runFinalization(); } assertTrue(i < maxAttempts, "GC did not remove the WeakReference within " + maxAttempts + " attempts"); }