every second in the int field, a record is written (it always writes a single stream) and the value is read at any time by several threads. It seems to be necessary, because recording happens but I doubt
1 answer
In the event that writing and reading this field is an atomic operation, it will be sufficient to declare it as volatile ( JLS 17.4.5 ).
PS By the way, if you look inside AtomicInteger , you can see that the set method is implemented in the following simple way (since this operation is atomic):
public final void set(int newValue) { value = newValue; } And the value declared as:
private volatile int value; But already all sorts of pre / post-increment / decrement and other non-atomic operations in this class ( getAndDecrement() , getAndAdd() , etc.) - yes, they are implemented more cunningly, with synchronization and / or Unsafe , depending on the implementation .
- I understand it volatile - disable buffering, writing is not atomic for simple types - shkiper
- Directly assignment, that is,
a = 10is atomic (and in general, it is atomic for all primitive types, except forlonganddouble, but atomicness is guaranteed for them in JLS if thevolatileis specified). Not atomic, for example, increment and decrement operations. An indication ofvolatilein your case initiates ahappens-before order(by the link above), which guarantees that:> write to a volatile field happens. - falstaf - @falstaf: Simple
volatilemay not be enough for the TC. +1 for the correct and useful link to the standard. - VladD - @VladD, yes, in general,
volatilemay not be enough, so I clarified that this is "in the event that writing and reading this field is an atomic operation." - falstaf
|
AtomicIntegerorsynchronized? Take any, once a second - not a problem. (If more often, then it is better to measure time and compare ._ - VladD