0

I'm trying to write a program that launches 1000 threads. Each Thread adds 1 to a variable sum that is initially 0. Doing this by passing sum by reference to each thread and I am told to do this using an Integer wrapper object to hold sum.

Code:

public class synchronizedsum {
    public static void main(String args[]){
        int sum=0;
        ExecutorService executor = Executors.newCachedThreadPool();
        for(int i=0;i<1000;i++){
            executor.execute(new Adder(sum));
        }
        executor.shutdown();
        while(!executor.isTerminated()){

        }
        System.out.println(sum);
}
private static class Adder implements Runnable{
    private int sum;
    Adder(int sum){
        this.sum = sum;
    }

    public synchronized void run(){
        sum+=1;
    }
}
}

I think I've got something wrong cause does not seem to be working.

EDIT: I keep getting output as 0 instead of 1000 that is the problem.

EDIT: I tried doing this seems to give me right output but not sure if it meets the condition of passing sum by reference to each Thread.

CODE:

public class synchronizedsum {

    private static Interger obj = new Interger();
    public static void main(String[] args) {

        ExecutorService executor = Executors.newCachedThreadPool();
        for(int i=0;i<1000;i++){
            executor.execute(new Add1());
        }
        executor.shutdown();
        while(!executor.isTerminated()){

        }
        System.out.println(obj.getSum());
    }
private static class Interger{
    private volatile int sum =0;
    private Lock lock = new ReentrantLock();
    public void add(int amount){
        lock.lock();
        try {
            sum+=amount;
            Thread.sleep(5);
        } catch (InterruptedException ex) {
            Logger.getLogger(Practice.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            lock.unlock();
        }
    }
    public int getSum(){
        return sum;
    }

}
public static class Add1 implements Runnable{

    public  void run(){
        obj.add(1);
    }
}
}
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Bolu Okunaiya
  • 129
  • 1
  • 10
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – azurefrog Apr 11 '17 at 01:25
  • That would be because you never modify `sum` in your main method. Just because `sum` in each thread has the same name doesn't mean it's the same variable. – azurefrog Apr 11 '17 at 01:25
  • So when you say "Integer", do you mean `Integer` or do you mean `int`? – markspace Apr 11 '17 at 01:26
  • BTW, using `Integer` won't help, since it's immutable. You need to use a wrapper object that you can modify. – azurefrog Apr 11 '17 at 01:28
  • I was going to point that out next, although he's using an `int` in the code, so I assumed he really meant `int`. – markspace Apr 11 '17 at 01:29
  • You don't need to mark you edits. The point is to create a really nice final version of the question that will be searchable for others, later. – Metropolis Apr 11 '17 at 01:51
  • Your `main()` routine does not create 1000 threads. It creates 1000 _tasks_ that will be performed by a thread _pool_. The thread pool created by `newCachedThreadPool()` will use a small number of threads, chosen by an algorithm to be "optimal" for performing lots of small, compute-bound tasks on your particular operating system and hardware platform. The number of threads probably will be somewhere in the neighborhood of the number of CPUs on the host where your program runs. – Solomon Slow Apr 11 '17 at 12:56

2 Answers2

0

Will passing an AtomicInteger instead of an Integer help? You won't have to deal with synchronized methods as updating the value for AtomicInteger guarantees that for you.

Gabe
  • 431
  • 3
  • 11
0

Above code is needlessly complex. You can achieve it with a simple solution using AtomicInteger

Few suggestions:

  1. Change newCachedThreadPool() to newFixedThreadPool(Runtime.getRuntime().availableProcessors());

  2. Use incrementAndGet of AtomicInteger by removing Lock

You can refer to example code at this post and modify your code accordingly.

How can I access the property value of a running Thread

Community
  • 1
  • 1
Ravindra babu
  • 37,698
  • 11
  • 250
  • 211