javaconcurrencyfalse-sharing

@jdk.internal.vm.annotation.Contended didn't work


I try to use @jdk.internal.vm.annotation.Contended with following class with java 17 and in Eclipse IDE it show "The type jdk.internal.vm.annotation.Contended is not accessible" this error. Can someone help me to solve this issue?

enter image description here

public class ContendedExample1 {

  @jdk.internal.vm.annotation.Contended 
  public volatile long count1 = 0;

  public volatile long count2 = 0;

}

public class FalseSharingMain {

  public static void main(String[] args) {
    
    ContendedExample1 obj1 = new ContendedExample1();
    
    long iteration = 1_000_000_000;
    
    new Thread(() -> {
        long sTime = System.currentTimeMillis();
        for(long i = 0; i < iteration; i++) {
            obj1.count1++;
        }
        long eTime = System.currentTimeMillis();
        System.out.println(eTime - sTime);
    }).start();
    
    new Thread(() -> {
        long sTime = System.currentTimeMillis();
        for(long i = 0; i < iteration; i++) {
            obj1.count2++;
        }
        long eTime = System.currentTimeMillis();
        System.out.println(eTime - sTime);
    }).start();;
  }
}

and when I run this program it shows like this.

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
jdk.internal.vm.annotation cannot be resolved to a type

at falseSharingExample.ContendedExample1.<init>(ContendedExample1.java:5)
at falseSharingExample.FalseSharingMain.main(FalseSharingMain.java:7)

and when I run this with IntelliJ IDEA it shows this error

java: exporting a package from system module java.base is not allowed with --release


Solution

  • As the name indicates, this annotation is for use internally within the JDK. It is not intended for general purposes. You cannot use it because it is not exported from the java.base module.

    If your intention was to use this for documentation purposes, create your own annotation, or find a library that offers similar annotations. If your intention was to get the same effect has it has for Java internal code: you can't.