I am testing the use of the class AtomicInteger
but increments doesn't seem to be applied under mutual exclusion control.
Here's my test:
static class AtomicIntegerRunnable implements Runnable
{
private static AtomicInteger x;
AtomicIntegerRunnable() {}
AtomicIntegerRunnable(AtomicInteger x)
{
this.x = x;
}
@Override
public void run()
{
System.out.println(x.get());
x.getAndIncrement();
}
}
public static void main(String[] args) {
ExecutorService e = Executors.newFixedThreadPool(n_whatever);
AtomicInteger x = new AtomicInteger();
int n = 10;
for (int i=0; i<n; i++) {
e.submit(new AtomicIntegerRunnable(x));
}
e.shutdown();
while (!e.isTerminated());
}
In the print I am getting something like
0 0 1 1 1 5 4 3 2 6
instead of
0 1 2 3 4 5 6 7 8 9
. What's wrong?
EDIT for @Louis Wasserman
static class AtomicIntegerRunnable implements Runnable
{
private AtomicInteger x;
AtomicIntegerRunnable() {}
AtomicIntegerRunnable(AtomicInteger x)
{
this.x = x;
}
@Override
public void run()
{
x.getAndIncrement();
}
}
public static void main(String[] args)
{
ExecutorService e = Executors.newFixedThreadPool(n_whatever);
AtomicIntegerRunnable x = new AtomicIntegerRunnable(new AtomicInteger());
int n = 10;
for (int i=0; i<n; i++)
e.submit(x);
e.shutdown();
while (!e.isTerminated());
}