views:

373

answers:

2

How do I modify an int atomically and thread-safely in Java?

Atomically increment, test & set, etc...?

+10  A: 

Use AtomicInteger.

Bombe
Which is fine if all you need is the limited set of operations it provides. The "etc" in the question suggests more flexibility.
skaffman
Does it ? If he's looking for more, he should be more explicit. AtomicInteger seems to be the right answer in the meantime
Brian Agnew
Also have a look at the other classes in the java.util.concurrent package. They can be helpful for the "etc"-stuff
Roland Schneider
+2  A: 

Thread safety can be achieved via synchronized functions. Wrap your int (or such data) in a class which provides the required functionalities via synchronized methods, e.g.

public class X
{
  protected int x;
  public synchronized void set( int value )
  {
    x = value;
  }
}

You can also use classes from the java.util.concurrent.atomic package, e.g. AtomicInteger or AtomicIntegerArray

CsTamas