java关键字transient和volatile的基本含义和使用方法

  • transient

transient关键字为类型修饰符,英文本意为“短暂的”,在对象序列化过程中,标记了transient的变量不会被序列化。

HashMap中的size属性就标注了transient关键字。

    transient int size;

    /**
     * The number of times this HashMap has been structurally modified
     * Structural modifications are those that change the number of mappings in
     * the HashMap or otherwise modify its internal structure (e.g.,
     * rehash).  This field is used to make iterators on Collection-views of
     * the HashMap fail-fast.  (See ConcurrentModificationException).
     */
  • volatile

volatile关键字也是一个变量修饰符,被修饰的成员变量,在每次被线程访问时,都强迫从共享内存中重读该成员变量的值。当变量值发生变化时,又强迫线程将变化值写回共享内存。
这样就保证了任何时刻,多个不同线程总会看到某个成员变量的同一个值。

Thread类中的name、threadStatus属性就有volatile关键字修饰。

    private volatile String name;

    private volatile int threadStatus = 0;

另外:在java语言设计规范中,允许线程保存共享成员变量的私有拷贝,而且只当线程进入或者离开同步代码块时才与共享成员变量的原始值对比。所以,当多个线程同时与某个对象交互时,需要注意关注该成员变量的最新值。volatile关键字就规定成员变量不能保存线程的私有拷贝,而是直接与共享变量交互。

发布了92 篇原创文章 · 获赞 13 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_41885819/article/details/103167570
今日推荐