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

  • What doubts? AtomicInteger or synchronized ? Take any, once a second - not a problem. (If more often, then it is better to measure time and compare ._ - VladD
  • I doubt whether I should use it at all, I just wanted an int, but I forgot that the write operation is not atomic - shkiper
  • @shkiper: it is necessary to use synchronization in some form: different threads have the right to have a different view of memory. There is no concept of “real memory contents”, each thread has its own presentation. - VladD

1 answer 1

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 = 10 is atomic (and in general, it is atomic for all primitive types, except for long and double , but atomicness is guaranteed for them in JLS if the volatile is specified). Not atomic, for example, increment and decrement operations. An indication of volatile in your case initiates a happens-before order (by the link above), which guarantees that:> write to a volatile field happens. - falstaf
  • @falstaf: Simple volatile may not be enough for the TC. +1 for the correct and useful link to the standard. - VladD
  • @VladD, yes, in general, volatile may not be enough, so I clarified that this is "in the event that writing and reading this field is an atomic operation." - falstaf