Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

pi/agent/skills/optional/java/java-unsafe-memory-migration/examples/jep-471.md

Raw
Rendered preview

JEP 471 / JEP 498 examples

Sources: https://openjdk.org/jeps/471 and https://openjdk.org/jeps/498

final class Counter {
    volatile int value;

    static final VarHandle VALUE;
    static {
        try {
            VALUE = MethodHandles.lookup().findVarHandle(Counter.class, "value", int.class);
        } catch (ReflectiveOperationException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    boolean compareAndSet(int expected, int update) {
        return VALUE.compareAndSet(this, expected, update);
    }
}
java --sun-misc-unsafe-memory-access=debug -jar app.jar
java --sun-misc-unsafe-memory-access=deny  -jar app.jar
# [JEP 471](https://openjdk.org/jeps/471) / [JEP 498](https://openjdk.org/jeps/498) examples

Sources: https://openjdk.org/jeps/471 and https://openjdk.org/jeps/498

```java
final class Counter {
    volatile int value;

    static final VarHandle VALUE;
    static {
        try {
            VALUE = MethodHandles.lookup().findVarHandle(Counter.class, "value", int.class);
        } catch (ReflectiveOperationException e) {
            throw new ExceptionInInitializerError(e);
        }
    }

    boolean compareAndSet(int expected, int update) {
        return VALUE.compareAndSet(this, expected, update);
    }
}
```

```bash
java --sun-misc-unsafe-memory-access=debug -jar app.jar
java --sun-misc-unsafe-memory-access=deny  -jar app.jar
```