954,523 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

pass variable by reference to each thread

Write a program that launches 100 threads. Each thread adds 1 to a variable sum that initially zero. You need to pass sum by reference to each thread. In order to pass it by reference, define an integer wrapper object to hold sum. Run the program with and without synchronization to see its effect.

code so far:

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
 
//class that hold the variable SUM and add the value 1 into it.
 class MutableInteger {
	   private int i;
	   //default constructor that sets the value to 0
	   public MutableInteger() { 
		   this(0); 
		   }
	   //constructor to pass and user defined value
	   public MutableInteger(int i) { 
		   this.i= i; 
		   }
	
	   public int inc() { 
		   return ++i; 
		   }
	   public synchronized int syncInc() { 
		   return ++i; 
		   }
	}
	 
 
public class mythread{
	private static int countthread;
	
  public static void main(String[] args){

	  /* Get an executor service that will run a maximum of 100 threads at a time: */
	  ExecutorService exec = Executors.newFixedThreadPool(100);
	  /* For all the 100 tasks to be done altogether... */
	  for ( countthread = 0; countthread <= 100; countthread++) {
	      /* ...execute the task to run concurrently as a runnable: */
	      exec.execute(new sum());
	  }
	  /* Tell the executor that after these 100 steps above, it will be done: */
	  exec.shutdown();
	  try {
	      /* The tasks are now running concurrently.wait until all work is done, 
	       * with a timeout of 50 seconds: */
	      boolean b = exec.awaitTermination(50, TimeUnit.SECONDS);
	      /* If the execution timed out, false is returned: */
	      System.out.println("All done: " + b);
	  } catch (InterruptedException e) { e.printStackTrace(); }}
}

class sum extends Thread {
	private MutableInteger sum = new MutableInteger(); 

    public void run() {
    	
        /* do the work to be done in its own thread */
        System.out.println("at " + Thread.currentThread()+"sum is "+sum.syncInc());
        
    }
};


what i don't understand...

Im not sure wht does the question want by meaning this “Each thread adds 1 to a variable sum that initially zero”…

So does that mean the each thread will come out like this :

At thread 1 sum is 0
At thread 2 sum is 1
At thread 3 sum is 2

Or something like this:

At thread 1 sum is 1
At thread 2 sum is 1
At thread 3 sum is 1

Because each thread does add 1 to its value which is the variable sum where in the question itself will start as sum=0;

So meaning thread 1 will become 1, thread 2 will become 1 as shown here:

At thread 1 sum is 1
At thread 2 sum is 1
At thread 3 sum is 1

But, thread does uses other thread resources which is “at thread 2 sum is 1” but when thread 3 comes in it will uses the resources at thread 2 where the value itself have been already changed to the value 1 and when thread 3 comes it will add 1 to the value of variable sum so it should be “at thread 3 sum is 2” :

At thread 1 sum is 0
At thread 2 sum is 1
At thread 3 sum is 2

You guys please decide which is the correct output for the question???

And above code answer which I think the output is gonna be like this:


At thread 1 sum is 1
At thread 2 sum is 1
At thread 3 sum is 1

mrar85
Light Poster
34 posts since Oct 2010
Reputation Points: 10
Solved Threads: 1
 

no, it will always add 1, but, without synchronization, you may have:

...
At thread 28 sum is 28
At thread 29 sum is 29
At thread 30 sum is 30
...

but, you can also get:

...
At thread 29 sum is 29
At thread 28 sum is 28
At thread 30 sum is 30
...

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 

What happens when you execute the program?

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

so meaning that, the value of sum that start with zero is going to increment by the number of thread that are running? which mean, if the thread started the 100th thread, the value of sum will change to 100 yeah?

so does that mean with synchornization the increment will properly followed by 1-100 sequence?

and without synhcronization the 1-100 will become unsequence?

oh yeah norm1: the output of the code above is as follows because i don't understand the qeustion need at first:

at Thread[pool-1-thread-1,5,main]sum is 1
at Thread[pool-1-thread-4,5,main]sum is 1
at Thread[pool-1-thread-2,5,main]sum is 1
at Thread[pool-1-thread-3,5,main]sum is 1
at Thread[pool-1-thread-3,5,main]sum is 1
at Thread[pool-1-thread-5,5,main]sum is 1
All done: true


i've changed the value of pool to just 5 thread running.....so this is not the correct output?

mrar85
Light Poster
34 posts since Oct 2010
Reputation Points: 10
Solved Threads: 1
 

well ... 'm not sure whether it is correct or not. the bigger the loop, the bigger the chance for 'inconsistencies'.
but yes, without synchronization, you can never tell up front in what order it will happen.

here you can find a simple example provided by Oracle

stultuske
Posting Sensei
3,137 posts since Jan 2007
Reputation Points: 1,114
Solved Threads: 433
 
Im not sure wht does the question want by meaning this “Each thread adds 1 to a variable sum that initially zero”…


First off; the question explicitly mentions "launching" threads which is bit different from creating a "pool" of threads. No need to extend the `Thread` class, just make your work class implement Runnable. Your logic is flawed in the sense that you are "not" sharing the MutableInteger between all those "work" instances. Each Runnable has its own "sum" variable and hence you don't see the effect of synchronization/non-synchronization since there is nothing shared.

You would have to:create two "runnable" classes (classes which implement Runnable interface); in one you will call `sum.inc()` and in the other class you will call `sum.syncInc()`. Let's call them Work and WorkSync respectively.
These classes should have a constructor which takes a "MutableInteger" parameter.
You create a single "Mutable" integer and pass it to all the 100 instances of your Work class instance. After that, create a new Thread for each Runnable and launch that thread (call start on it).
Repeat the same for WorkSync class (make sure you start from scratch; i.e. create new Mutable integer, create new 100 threads etc.)
Observe the result and draw your conclusion

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Here's an article that explains simply and briefly what this exercise is all about:
http://www.informit.com/guides/content.aspx?g=java&seqNum=248

JamesCherrill
Posting Genius
Moderator
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

Not exactly; all AtomicXXX classes use lock/wait free constructs whereas "synchronized", which is what the OP has to use, is inherently a lock based approach. Though I agree the article would be the next logical step i.e. going from synchronized to lock-free implementation.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

Yes.
I was just thinking about the first part - explaining the problem of lost updates, and exactly how the actual output may vary from the expected output.
I agree that the rest of the article, no matter how relevant it may be to real life, isn't exactly what the OP's homework is calling for.

JamesCherrill
Posting Genius
Moderator
6,371 posts since Apr 2008
Reputation Points: 2,130
Solved Threads: 1,073
 

alrite....my effect of synchronization/non-synchronization it is not shared...i can see that ...the code for two "runnable classes" is it something like this:

class work implements Runnable{

	private MutableInteger par1= new MutableInteger(0);
	
	public work(MutableInteger par1){
		this.par1=par1;
	}

	public void run() {
		
		 System.out.println("at " + Thread.currentThread().getName()+" sum is "+par1.inc());
		
	}
	
}
class worksync implements Runnable{
	private MutableInteger par2= new MutableInteger(0);
	
	public worksync( MutableInteger par2){
		this.par2=par2;
	}

	public void run() {
		System.out.println("at " + Thread.currentThread().getName()+" sum is "+par2.syncInc());
		
	}
	
}

but this line i dont understand...You create a single "Mutable" integer and pass it to all the 100 instances of your Work class instance

shouldn't i just call in the main method something like this to create 100 thread?

MutableInteger par3=new MutableInteger();
	  for (countthread=0; countthread<=100; countthread++){
	  
		  (new Thread(new work(par3))).start();
}


i am new to thread and synchronization...and my lecturer is not helpful as i've never actually seen her code anything in JAVA or any programming languages...and about thethreadpool thing, she said that is how you create multithreading....explain that please

mrar85
Light Poster
34 posts since Oct 2010
Reputation Points: 10
Solved Threads: 1
 

and the ouput of the program is something like this now:

at Thread-0 sum is 1
at Thread-1 sum is 2
at Thread-2 sum is 3
at Thread-4 sum is 4
at Thread-3 sum is 5


so is this the ouput should be like?

mrar85
Light Poster
34 posts since Oct 2010
Reputation Points: 10
Solved Threads: 1
 

The output will depend on when each of the threads is executed and whether there were any collisions.
Have you run your test with a large number of threads and looked at the output?
Using synchronized and without it.

NormR1
Posting Expert
Moderator
6,677 posts since Jun 2010
Reputation Points: 1,138
Solved Threads: 656
 

> shouldn't i just call in the main method something like this to create 100 thread?

Yes, except that you have a one-off error in your code; you are iterating 101 times, not 100 times. And make sure variables have logical name and not numbers tacked on to the end.

> and about the thread pool thing, she said that is how you create multi-threading....explain that please

Thread pools are the new abstraction offered by the standard library to replace the old Thread() construct for doing background activities and submitting tasks. But if your assignment specifically asks for 100 threads, creating a pool with 100 threads wouldn't be the same, because it is quite possible that when you submit the 50th task, it might be processed by the same thread that processed the first task. i.e. there is no guarantee that a new thread would be used. If this isn't a problem, go ahead and use the pooling approach. Otherwise, stick with the new Thread() stuff.

> so is this the ouput should be like?

That isn't something you should ask us. I would rather want you to test both sync and non-sync runs and draw the conclusion based on what you have learned.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
 

i'm sorry for the variable names...it;s just for a testing purpose..

and i think i've got it now...

thanks you guys especially SOS...you've been a big help

cheers..

mrar85
Light Poster
34 posts since Oct 2010
Reputation Points: 10
Solved Threads: 1
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: