1

I'm new to java and was trying out synchronization with a sample program to add numbers upto 100 using multiThreading. And following is code i was able to come up with. When i test the code it sometimes gives the correct value of 4590 but sometimes doesnt give the correct value. Can anyone point out what i'm doing wrong

class Counter{
    Integer counter = 0;

    public void increment(int i){
        synchronized (counter){
            counter += i;
        }
    }
}

class ObjectTest implements Runnable{

    int i;
    Counter blah;

    public ObjectTest(Counter counter,int i){
        blah =counter;
        this.i = i;
    }
    @Override
    public void run() {
        blah.increment(i);
    }
}

public class SyncTest {

    public static void main(String args[]) throws InterruptedException {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(4,10,60, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());
        Counter counter = new Counter();
        for (int index = 0; index < 100; index++) {
            ObjectTest objectTest = new ObjectTest(counter,index);
            executor.execute(objectTest);
        }
        executor.shutdown();
        while (!executor.isTerminated()){
            Thread.sleep(1000L);
        }

        System.out.println(counter.counter);
    }
}
Markus Mitterauer
  • 1,560
  • 1
  • 14
  • 28
Sreenath Kamath
  • 663
  • 1
  • 7
  • 17

1 Answers1

2

You can't synchronize on counter because it's an Integer, which is immutable. Therefore counter += i creates a new Integer object, which is not the same that was synchronized on.

You can make it int counter and have a separate Object lock = new Object();, synchronizing on lock.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
  • 2
    You can synchronize on an Integer (or any Object), just not the one you are incrementing... – RealSkeptic Aug 29 '16 at 13:07
  • Yes my statement was applicable to this particular code. You can synchronize on the Integer you're incrementing too, it just won't result in well working code. – Kayaman Aug 29 '16 at 13:09
  • You obviously understand the problem, but your answer is not very sypmathetic to the way newbies think. Newbies don't fully grasp the difference between objects and variables and expressions. You say "because Integer is immutable", but what you really mean is, "because `Integer` objects are immutable, the `counter` variable must be _mutable_." It's the mutability of the counter variable that causes the problem, not the immutability of Integer objects. – Solomon Slow Aug 29 '16 at 13:47
  • @jameslarge That's why I closed this as a duplicate. I don't really want to be repeating things that have been said on SO dozens of times, just because "newbies" can't even use search engines. Hence my less than complete answer. The dupe has it explained properly. – Kayaman Aug 29 '16 at 13:53