原始类型的易失性或同步

原始类型的易失性或同步

本文介绍了原始类型的易失性或同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,如果变量的大小小于或等于32位,则赋值是原子的,但如果大于32位则不是。

In Java, assignment is atomic if the size of the variable is less than or equal to 32 bits but is not if more than 32 bits.

什么(volatile / synchronized)在双重或长期分配的情况下使用会更有效吗?

What (volatile/synchronized) would be more efficient to use in case of double or long assignment?

赞,

  volatile double x = y;

synchronized不适用于原始参数。在这种情况下如何使用synchronized?当然我不想锁定我的类,所以不应该使用这个

synchronized is not applicable with primitive argument. How do I use synchronized in this case? Of course I don't want to lock my class, so this should not be used.

推荐答案

如果你发现对象本身的锁定太重,那么同步就是要走的路。在Java 1.5之前,volatile可能是一个不错的选择,但是现在volatile可以通过在赋值发生的方法上强制执行指令来产生非常大的影响。创建一个单独的对象( private final Object X_LOCK = new Object(); )并在设置或获取该double的值时对其进行同步。这将为您提供对锁定的精细控制,这似乎是您所需要的。

If you find locking on the object itself too heavy, then synchronized is the way to go. Prior to Java 1.5 volatile may have been a good choice, but now volatile can have a very large impact by forcing instruction ordering on the method where the assignment happens. Create a separate object (private final Object X_LOCK = new Object();) and synchronize on it when setting or getting the value of that double. This will give you a fine level of control over the locking, which it seems that you need.

在新的并发包中有更多选项,例如AtomicReference,它可能是如果你真的需要避免同步,那么它是volatile的一个很好的替代品。

In the new concurrency package there are more options, such as AtomicReference which may be a good replacement for volatile if you really need to avoid synchronization.

这篇关于原始类型的易失性或同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:23