Why is JPA2 MetaModel generated with mutable members?

I just used org.apache.openjpa.persistence.meta.AnnotationProcessor6 to create a MetaModel for my JPA2 entities.

 @javax.annotation.Generated (value="org.apache.openjpa.persistence.meta.AnnotationProcessor6", date="Tue Nov 22 09:49:03 CET 2011") public class Entity_ { public static volatile SingularAttribute<Entity,Entity> id; public static volatile SingularAttribute<Entity,String> value; public static volatile SingularAttribute<Entity,String> order; } 

Can someone explain why in this case the attributes are marked as volatile?

Thanks.

+6
source share
2 answers

A thread that sets static variables may not be the same as the thread you use to access them, so the volatile needed to synchronize memory between all threads.

The scenario without volatile as follows:

  • Your thread accesses variables before the JPA provider is initialized and gets null for static fields
  • JPA provider initializes from another thread and sets static fields to non-zero values
  • Your thread accesses static fields again. In this case, the cached memory of your stream will not see the change and continue to return null for all static fields.
+7
source

Despite the meaning of the volatile keyword and the answer of Ingo, it is worth noting that every JPA generator needs to generate variable metadata fields (JPA 2.0 FR, 6.2.1.1 Canonical Metamodel).

On page 199 you can read:

For each persistent non-collection attribute y declared to be class X, where type y is Y, the metamodel class should contain as follows:

public static volatile SingularAttribute<X, Y> y;

+2
source

Source: https://habr.com/ru/post/904096/


All Articles