@@ -0,0 +1,2106 @@
+import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;%0A%0A/**%0A * A safe finalize example that relies on piggybacking of a volatile write and read.%0A *%0A * %3Cp%3EThe use of the volatile field ensures a reference to %22this%22 is held until the%0A * end of the work method. Since the field is volatile, the instruction can not be%0A * reordered. In addition, the field is copied to a public static field during%0A * finalization to prevent a theoretical optimizer from eliminating the field.%3C/p%3E%0A *%0A * %3Cp%3EThe advantage of this approach is that does not involve any form of locking.%0A * It does, however, require a StoreLoad barrier after every pre-finalization%0A * method call.%3C/p%3E%0A */%0Apublic final class SafeFinalizeVolatileFieldUsingUpdaterExample %7B%0A    public static int STATIC_COUNTER = 0;%0A%0A    private static AtomicIntegerFieldUpdater%3CSafeFinalizeVolatileFieldUsingUpdaterExample%3E%0A            updater = AtomicIntegerFieldUpdater.newUpdater(SafeFinalizeVolatileFieldUsingUpdaterExample.class, %22counter%22);%0A    // Initialize with current static field value for an additional optimizer safe-guard%0A    private volatile int counter = STATIC_COUNTER;%0A%0A%0A%0A%0A    public void work() throws Exception %7B%0A        try %7B%0A            System.err.println(%22Work starting%22);%0A            System.gc();%0A%0A            // Do some work here, potentially blocking (simulate with sleep)%0A            Thread.sleep(10000L);%0A            System.err.println(%22Work completed%22);%0A        %7D finally %7B%0A            updater.lazySet(this, counter + 1);  // program order rule, prevents reordering of this call%0A        %7D%0A    %7D%0A%0A    protected void finalize() throws Throwable %7B%0A        super.finalize();%0A%0A        // Copy value to a public static for an additional optimizer safe-guard%0A        STATIC_COUNTER = counter;%0A        System.err.println(%22Finalize%22);%0A    %7D%0A%0A    public static void main(String%5B%5D args) throws Exception %7B%0A        for (int i = 0; i %3C 2; i++) %7B%0A            System.out.println(%22Run %22 + (i + 1));%0A            new SafeFinalizeVolatileFieldUsingUpdaterExample().work();%0A            System.gc();%0A            Thread.sleep(2000);%0A        %7D%0A    %7D%0A%7D%0A

Add updater example