Volatile or synchronized for primitive type?

前端 未结 5 1621
栀梦
栀梦 2021-02-04 06:52

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.

What (volatile/synchronized) would be more ef

5条回答
  •  忘掉有多难
    2021-02-04 07:35

    volatile is certainly the way to go if you are only doing an assignment. I'm sure you know, but since it was brought up: if you would like to do more complex operations (increment the value for example) you would need to syncrhonize. i++ is never thread safe for any type of variable. You need to synch. i++ and the like since that is actually more than 1 operation.

    Not: It was expressed that you could use AtomicDouble but there is currently no AtomicDouble in java.util.concurrent.atomic

    If you are doing a multiple operations on x, that requires setting it to a new value at the end, it is possible to do this in a thread safe manner with no locking what so ever, and have it be thread safe, using compare and set. Example:

    AtomicLong x = new AtomicLong(SomeValue);
    public void doStuff() {
      double oldX;
      double newX;
      do {
        oldX = x.get();
        newX = calculateNewX(oldX);
      } while (!x.compareAndSet
          (Double.doubleToLongBits(oldX), Double.doubleToLongBits(newX)));
    

    This works because compareAndSet will see if the value of x has changed since the last time you read it. If x has changed then you are forced to do the computation over again and re-try setting it.

    You could of course implement your own AtomicDouble instead of doing these doubleToLongBits conversions. Take a look at AtomicFieldUpdater.

提交回复
热议问题