Why do the JPA2 MetaModel get generated with volatile members?

感情迁移 提交于 2019-11-26 21:39:26

问题


I have just used org.apache.openjpa.persistence.meta.AnnotationProcessor6 to generate the 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 please explain why the attributes are marked volatile in this case?

Thanks.


回答1:


The thread that sets the static variables might not be the same as the thread that you use to access them, so the volatile modifier is required to synchronize memory between all threads.

The scenario without volatile is like this:

  1. Your thread accesses the variables before the JPA provider is initialized and gets null for the static fields
  2. The JPA provider is initialized from a different thread and sets the static fields to non-null values
  3. Your thread accesses the static fields again. In this case the cached memory of your thread will not see the changes and continue to return null for all static fields.



回答2:


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

On page 199 you can read:

For every persistent non-collection-valued attribute y declared by class X, where the type of y is Y, the metamodel class must contain a declaration as follows:

public static volatile SingularAttribute<X, Y> y;



来源:https://stackoverflow.com/questions/8564482/why-do-the-jpa2-metamodel-get-generated-with-volatile-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!