petrbel
petrbel

Reputation: 2528

how to assure atomicity without AtomicInteger in java?

Assuming Java 6/7/8:

Is there any chance of marking some statement atomic without using e.g. AtomicInteger? From my mini research it seems not to be possible generally, however integer/byte/char operations are atomic by itself though (source).

Obviously, there is synchronized but at this point I'd like to avoid it. So the question: can I do sth like atomic(x++)?

Upvotes: 0

Views: 161

Answers (3)

nomis
nomis

Reputation: 2715

Your options are:

  • intrinsic locks via the synchronized keyword
  • using explicit locks from java.util.concurrent.locks to wrap operations you want to make atomic

Upvotes: 1

Neil Masson
Neil Masson

Reputation: 2689

If you want to read and write variables from multiple threads, then you do need to impose some atomicity on the variables. You cannot rely on operations being intrinsically atomic, because the value of a variable can be cached by a thread. Because of this, an update in one thread may not be seen by another thread. The simplest way of fixing this is to declaring a variable volatile which forces the latest value to be read. The java.util.concurrent classes give extra features and good performance.

Upvotes: 0

Hoopje
Hoopje

Reputation: 12932

My advise is: if you are doing multithreaded programming, start with synchronization as soon as possible. Atomicity works for small data types, but as soon as you want to access class instances from different threads you need to think about synchronization, either by using synchronized or by explicitly manipulating locks.

Although single int reads and writes are atomic in the sense that they will not leave the variable in an inconsistent state, this is not the only thing about atomicity that is important. In particular modern CPUs reorder instructions and cache memory, so that changes to a variable may not be visible to other threads (this can be solved by adding the volatile keyword to the variable.

Also, AtomicInteger and friends also provide operations which consist of more than one operation, for example the getAndIncrement() method, which is similar to using the postfix ++ operator. This consists of a read and a write, and if you don't synchronize or use AtomicInteger, other threads may access the variable between the read and the write.

Upvotes: 2

Related Questions