Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does AtomicInteger work?

Tags:

java

I didn't think threading would be this difficult sigh. Anyways, the only way I could think of executing a function after a thread has completed is to use a static counter to increment whenever a thread ran.

if(++threadcounter==3){doSomething(); threadcounter =0;}

I found this wasn't a good idea because the threadcounter at times never reaches 4.

So I used atomic integer

if(atomicint.incrementAndGet()==4){doSomething(); atomicint.set(0);}

The counter is 5 or 0 and the app freezes. I don't know what's happening. How to use a correct counter? Thanks

EDIT:

like image 668
Lews Therin Avatar asked Jan 19 '23 06:01

Lews Therin


1 Answers

The simplest way to tackle this is with a good old-fashioned lock:

boolean shouldDoSomething;
synchronized {
    ++threadCounter;
    if (threadCounter == 4) {
        threadCounter = 0;
        shouldDoSomething = true;
    }
    else {
        shouldDoSomething = false;
    }
}
if (shouldDoSomething) doSomething();

This will create contention on the lock, but over a very, very brief piece of code - a load, a store, and a few arithmetic instructions.

Your use of AtomicInteger is wrong, because there is no locking or other concurrency control linking the incrementAndGet and the set, which means there is a potential race condition (value is 3, thread A increments to 4, thread B increments to 5, thread A sets to 0).

like image 143
Tom Anderson Avatar answered Jan 24 '23 21:01

Tom Anderson