Java: is there no AtomicFloat or AtomicDouble?

后端 未结 8 1451
误落风尘
误落风尘 2020-12-01 03:12

I have found AtomicInteger, AtomicLong, but where is AtomicFloat (or AtomicDouble)? Maybe there is some trick?

8条回答
  •  鱼传尺愫
    2020-12-01 04:03

    It would be horrible inefficient to implement (but it would be possible). Per se its senseless to speak from atomic datatypes, because operations on datatypes are atomic, not the datatypes itself (maybe you know it, but just want to clear this point). With all this object stuff it gets mixed up. You need them very often in OS to manage locks and semaphores, thats why many processors have atomic integer instructions. For floats they are usually not implemented, so they get implemented, by wrapping the float operation in a block protected by a semaphore (which is implemented with atomic ints).

    In high level java its no problem to make this locking for floats yourself (and you are right, they could have implemented it), but for efficiency you must implement them with the low level asm, so its very practical if you provide for the high level java folks some function that utilizes the low level asm instructions.

    In reality I saw very seldom applications where atomic float operations are useful. I came across them, but very rare and it was always possible to reformulate the problem that the concurrency did not happen on the float part.

提交回复
热议问题