Java – why use volatile members to generate JPA2 metamodels?

I just used org apache. openjpa. persistence. Meta. Annotation processor 6 generates a Metamodel for my JPA2 entity

@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 anyone explain why the attribute is marked volatile in this case?

thank you.

Solution

The threads that set static variables may be different from the threads that access them, so you need to use the volatile modifier to synchronize memory between all threads

The scenario without volatile is as follows:

>Your thread accesses the variable before initializing the JPA provider and gets null for the static field > JPA provider initializes from different threads and sets the static field to a non null value > your thread accesses the static field again In this case, the thread's cache memory will not see the change and will continue to return null for all static fields

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>