For the purpose of threading, ++ and += treated as two operations (four for double and long ). In this way, updates can be compressed with each other. Not only one, but the scheduler, acting at the wrong time, can destroy the milliseconds of updates.
java.util.concurrent.atomic is your friend.
Your code can be made safe if you do not mind every element that is updated individually, and you do not change the size (!), Like:
for (int i=0; i < vec.size(); i++) { synchronized (vec) { vec.set(i, vec.get(i) + value); } }
If you want to add size to Vector , you need to move the synchronized statement outside the for loop, and you can just use a simple new ArrayList . For a synchronized list there is actually not much use.
But you can use AtomicIntegerArray :
private final AtomicIntegerArray ints = new AtomicIntegerArray(KNOWN_SIZE); [...] int len = ints.length(); for (int i=0; i<len; ++i) { ints.addAndGet(i, value); } }
This has the advantage of no locks (!) And no boxing. The implementation is also quite interesting, and you will need to understand that it makes a more complex update (random number generators, for example).
source share