什么是瞬态和挥发性改性剂? [英] What are Transient and Volatile Modifiers?
问题描述
有人可以解释一下 transient
和 volatile
修饰符在Java中意味着什么?
Can someone explain what the transient
and volatile
modifiers mean in Java?
推荐答案
volatile
和瞬态
修饰符可以是适用于类 1 的字段,与字段类型无关。除此之外,它们是无关的。
The volatile
and transient
modifiers can be applied to fields of classes1 irrespective of field type. Apart from that, they are unrelated.
transient
修饰符告诉Java对象序列化子系统在排除字段时序列化类的实例。然后反序列化对象时,该字段将初始化为默认值;即 null
表示引用类型,零或 false
表示基本类型。请注意JLS(参见 8.3.1.3 )没有说 transient
意味着什么,但是按照 Java对象序列化规范。其他序列化机制可能注意字段的 transient
-ness。或者他们可能会忽略它。
The transient
modifier tells the Java object serialization subsystem to exclude the field when serializing an instance of the class. When the object is then deserialized, the field will be initialized to the default value; i.e. null
for a reference type, and zero or false
for a primitive type. Note that the JLS (see 8.3.1.3) does not say what transient
means, but defers to the Java Object Serialization Specification. Other serialization mechanisms may pay attention to a field's transient
-ness. Or they may ignore it.
(请注意,JLS允许将 static
字段声明为 transient
。这种组合对Java对象序列化没有意义,因为它无论如何都不会序列化静态。但是,它在其他情况下可能有意义,因此有一些理由不完全禁止它。)
(Note that the JLS permits a static
field to be declared as transient
. This combination doesn't make sense for Java Object Serialization, since it doesn't serialize statics anyway. However, it could make sense in other contexts, so there is some justification for not forbidding it outright.)
volatile
修饰符告诉JVM写入字段应始终同步刷新到内存,并且该字段应始终从内存中读取。这意味着可以在多线程应用程序中安全地访问和更新标记为volatile的字段,而无需使用本机或基于库的同步。同样,对volatile字段的读写也是原子的。 (这不适用于>>非易失性<<< long
或 double
字段,这可能受制于在一些JVM上撕裂。)JLS的相关部分是 8.3.1.4 , 17.4 和 17.7 。
The volatile
modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. Similarly, reads and writes to volatile fields are atomic. (This does not apply to >>non-volatile<< long
or double
fields, which may be subject to "word tearing" on some JVMs.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.
1 - 但不是局部变量或参数。
这篇关于什么是瞬态和挥发性改性剂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!