Are java.lang.Class methods thread safe?

后端 未结 2 1809
一生所求
一生所求 2021-02-08 18:46

Under IBM JVM we have faced an issue when multiple threads are trying to call Class.getAnnotation at the same time on different objects (but with the same annotation). Threads a

2条回答
  •  终归单人心
    2021-02-08 19:30

    Your problem might be related to bug fixed in version 8 of Oracle Java.

    One thread calls isAnnotationPresent on an annotated class where the annotation is not yet initialised for its defining classloader. This will result in a call on AnnotationType.getInstance, locking the class object for sun.reflect.annotation.AnnotationType. getInstance will result in a Class.initAnnotationsIfNecessary for that annotation, trying to acquire a lock on the class object of that annotation.

    In the meanwhile, another thread has requested Class.getAnnotations for that annotation(!). Since getAnnotations locks the class object it was requested on, the first thread can't lock it when it runs into Class.initAnnotationsIfNecessary for that annotation. But the thread holding the lock will try to acquire the lock for the class object of sun.reflect.annotation.AnnotationType in AnnotationType.getInstance which is hold by the first thread, thus resulting in the deadlock.

    JDK-7122142 : (ann) Race condition between isAnnotationPresent and getAnnotations

提交回复
热议问题