Here is my code :
final int g = 0;
ExecutorService threadPool = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
threadPool.submit(new Runnable() {
public void run() {
g++;
myFunc(g);
}
});
}
Obviously this doesn’t work because of concurrent access on the variable g.
I’ve tried a lot of things, but didn’t manage to find a nice and easy way to fix it. Any solutions ?
Thanks.
In your example g is a primitive constant so you cannot change it.
On the other side it has to be a constant in order to be accessed from the Runnable implementation.
If you want to modify it you have to use some thread safe class like AtomicInteger.
Try this: