AtomicInteger does not increase at the same time

I am testing the use of a class AtomicInteger, but increments do not apply when mutually exclusive.

Here is 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 print, I get something like

0 0 1 1 1 5 4 3 2 6

instead

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());
}
+3
source share
1 answer

You get it and increase it by two separate actions. You print the first thing that makes your own code non-atomic.

Each AtomicInteger operation is an atom in itself , but you cannot use two in a sequence and consider a combination of an atom - by definition, two operations are not atomic.

To fix this:

@Override
public void run()
{
    System.out.println(x.getAndIncrement());
}

, , - . . , , .

printAndIncrement.

AtomicInteger , , , , (, ) ( - ).

+10

All Articles