Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
322 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...