I was watching a presentation on Java, and at one point, the lecturer said:
\"Mutability is OK, sharing is nice, shared mutability is devil\'s work.\"
Assume two threads perform this task at the same time, the second thread one instruction behind the first.
The first thread creates doubleOfEven. The second thread creates doubleOfEven, the instance created by the first thread will be garbage collected. Then both threads will add the doubles of all even numbers to doubleOfEvent, so it will contain 0, 0, 4, 4, 8, 8, 12, 12, ... instead of 0, 4, 8, 12... (In reality these threads won't be perfectly in sync, so anything that can go wrong will go wrong).
Not that the second solution is that much better. You would have two threads setting the same global. In this case, they are setting it both to logically equal values, but if they set it to two different values, then you don't know which value you have afterwards. One thread will not get the result it wants.