Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Reference.reachabilityFence — preserving strong reachability

Reference.reachabilityFence(ref) keeps an object strongly reachable at least until the call completes. It is useful when premature reclamation could interfere with an operation.

Version: Java SE 21; repository runtime, production runtime not attested

Syntax

public static void reachabilityFence(Object ref)

Reference.reachabilityFence(ref) from java.lang.ref.Reference, available since Java 9, prevents GC from reclaiming the referenced object at least until the call completes. Passing null has no effect; the call itself initiates neither GC nor finalization.

Variable scope does not determine object lifetime. The JVM may consider an object unnecessary after its last use, even while its method is executing, if subsequent computation uses previously loaded field values. This matters when premature finalization releases an external resource still being used.

Place the call after the protected operation, usually in finally, to cover exceptional paths too. It controls reachability; it is neither a mutual-exclusion lock nor a replacement for explicit resource closure.

The example demonstrates this placement and prints 42. It manages no external resource, so the fence is unnecessary for its correctness; it also does not prove that a GC race occurred or was prevented.

Examples

import java.lang.ref.Reference;

public class FenceDemo {
    private final int value = 42;

    int read() {
        try {
            int snapshot = value;
            return process(snapshot);
        } finally {
            Reference.reachabilityFence(this);
        }
    }

    private static int process(int snapshot) {
        return snapshot;
    }

    public static void main(String[] args) {
        System.out.println(new FenceDemo().read());
    }
}

Result

42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources