Unit tests for Java WeakHashMap and Reference Queues

Java’s WeakHashMap can look like a predictable cache until its keys become eligible for garbage collection. At that point, cleanup depends on JVM activity rather than a method call, so ordinary assertions may pass on one run and fail on another. A resilient suite must distinguish fixed map contracts from behaviour that can only be observed eventually.

Unit-testing Java’s WeakHashMap alongside a ReferenceQueue becomes simpler when the roles of each object are explicit. The map stores values against weakly referenced keys, while a ReferenceQueue reports weak references whose referents have been cleared. Neither the queue nor System.gc() guarantees that cleanup has finished at a precise instant, which makes timing assumptions the main source of flaky tests.

A strong suite separates fixed map contracts from collection-dependent behaviour behind bounded waits and clear postconditions. This balance creates a useful foundation for teams in Sydney, Melbourne, and Brisbane, where distributed engineers often review the same build from different offices and home locations.

How weak keys shape map behaviour

WeakHashMap uses weak references for keys and an internal queue for reclaimed entries. Lookup still uses equals and hashCode, yet reachability is based on object identity. This split matters when two keys are equal: they can address the same logical map entry, while only the original referent controls whether its weak reference is reclaimed.

Queue notification follows the same lifecycle. Once the referent is cleared, the JVM enqueues the Reference object; the queue does not retain the key itself. WeakHashMap also owns an internal queue and removes stale entries when map operations trigger its cleanup pass. You cannot retrieve that internal reference for an identity assertion, so observe map cleanup and a separately registered reference rather than expecting them to be the same object.

Separating deterministic and eventual assertions

Many WeakHashMap behaviours need no garbage collection at all. A strongly reachable key should remain discoverable through get and containsKey, value replacement should work normally, and removing an entry should make subsequent lookups fail. These checks are deterministic and belong in the fast unit-test layer.

For queue behaviour, register your own WeakReference with a ReferenceQueue while keeping a strong local reference to the key. The queue must remain empty during that interval. In Java 9 and later, Reference.reachabilityFence can protect the key through the assertion, preventing the optimiser from ending its lifetime sooner than the test intends.

Building a focused JUnit test

Use JUnit 5 with AssertJ and Awaitility for the small collection-sensitive suite. The helper returns only the watched WeakReference, so neither it nor the test retains the original key accidentally. Keep this test separate from ordinary map tests because it depends on reference processing and a collection cycle.

@Test
void eventuallyEnqueuesReferenceAndRemovesWeakEntry() {
    WeakHashMap<Object, String> map = new WeakHashMap<>();
    ReferenceQueue<Object> queue = new ReferenceQueue<>();
    WeakReference<Object> watched = putAndWatch(map, queue);

    await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
        System.gc();
        assertThat(queue.poll()).isSameAs(watched);
    });

    assertThat(watched.get()).isNull();
    assertThat(map).isEmpty();
}

private WeakReference<Object> putAndWatch(
        WeakHashMap<Object, String> map,
        ReferenceQueue<Object> queue) {
    Object key = new Object();
    map.put(key, "cached");
    return new WeakReference<>(key, queue);
}

The assertions have two linked postconditions: the external queue returns the exact reference registered by the test, and the map exposes no stale entry. Polling inside Awaitility avoids a fixed sleep and gives the JVM time to process cleared references. It also avoids queue.remove() without a timeout, which could block the test thread indefinitely.

Treat System.gc() as a request rather than a command. Some JVMs disable explicit collection or run it concurrently, so the deadline remains necessary. If explicit collection is unavailable in the build, run the tagged check in a dedicated forked test JVM with it available; this preserves the application’s normal garbage-collection policy. The practical testing philosophy at Test Detective favours observable contracts over private implementation assumptions.

Comparing map cleanup with queue signals

The map and queue answer different questions. A map assertion proves that a stale key is no longer exposed to callers. A queue assertion proves that reference processing occurred and identifies the Reference object that was notified. Neither check replaces the other.

Scenario WeakHashMap check ReferenceQueue check Reliable strategy
Strongly reachable key get and containsKey succeed Watched reference is not enqueued Deterministic test with strong reachability
Cleared weak key A later map access omits the entry Watched reference appears; get() is null Bounded eventual assertion
Separate watched reference Entry cleanup remains visible through the map poll() returns the same watched instance Compare by identity
Null key Lookup behaves like a normal key No reference is enqueued Deterministic contract test
Value retains its key Entry remains reachable through the strong value Watched reference is not enqueued Prevent an accidental retention cycle

External queue identity is especially important. The WeakReference held inside WeakHashMap is private and will never equal the test’s watched reference. Asserting that the map’s internal reference was enqueued would test an inaccessible implementation detail.

After collection, WeakHashMap can retain a stale entry internally until an operation triggers cleanup. Calls such as size, get, put, or remove can cause that pass, so trigger it explicitly before asserting the final state. Do not require the queue event and map cleanup to occur in a fixed order.

Handling edge cases and JVM timing

Null keys deserve a dedicated case because WeakHashMap supports them through a permanent internal key representation; they never produce a queue notification. Equal-but-distinct keys also expose the difference between map equality and referent lifetime. Create each scenario in isolation so one key’s reachability cannot mask another’s.

A strong value can prevent weak-key collection when that value points back to the key. This is correct Java reachability rather than a WeakHashMap defect, yet it surprises teams expecting every cache entry to vanish. Tests should therefore use values that do not retain their keys unless retention is the behaviour under examination.

Collection and reference processing can occur on different schedules. The JVM may clear an object before the reference handler enqueues it, and concurrent explicit collection can delay visibility further. Avoid allocating unbounded memory to force collection; use bounded pressure in an isolated JVM, and assert only that the reference eventually arrives before the test deadline.

Practices for a resilient test suite

Reliable suites combine fast contract coverage with a small number of lifecycle checks. Keep garbage-collection-dependent methods in a dedicated class so developers can run ordinary tests on every change while the full suite retains coverage of cleanup and notification.

Useful practices for the suite include:

Retries belong at the event-waiting boundary, not around individual assertions. Repeating an assertion hides partial failures and can conceal a broken queue relationship. A failed run should report whether the reference never appeared, the wrong reference appeared, or the map retained a stale entry.

Moving tests into Australian delivery pipelines

Delivery context matters in Australia. Teams in Sydney, Melbourne, and Brisbane often overlap only briefly across time zones, and a morning video stand-up is a common daily checkpoint. Running the collection-sensitive group before that checkpoint turns a latent cleanup regression into a visible build failure while there is still time to diagnose it.

Australian fintech, online retail, and government services also make careful fixture handling a local compliance concern. Where personal information is involved, the Privacy Act 1988 and the OAIC Notifiable Data Breaches scheme may apply, so use synthetic customer records rather than copied production data. Clock scheduling and log correlation should remain clear across Australian daylight-saving changes.

Cloud regions around Sydney and Melbourne make it practical to run integration checks close to Australian users. Ordinary unit tests still belong in the pull-request pipeline, while the bounded reference-queue check can also run in a separate nightly job with stable heap settings. The first implementation step is adding one deterministic strong-key test and one tagged eventual-cleanup test to an existing JUnit module, then executing that module ten times on the CI JDK before expanding coverage.