(Java) Problem creating and passing an Integer object?

Status
Not open for further replies.

Toshiro

In Runtime
Messages
115
First off, I'm not asking for code or anything, I just need a solution to fix what I have apparently missed. I seriously doubt we'd be given an assignment that can't actually be completed the way the instructions describe. I must be missing something rather obvious...

Anyway, I've run into a problem on a Java assignment for my Computer Science class. The instructions are as follows:
"(Synchronizing threads) Write a program that launches one thousand threads. Each thread adds 1 to a variable "sum" that initially is 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."

I've got everything working except one thing: the Integer wrapper object being passed to the threads. I know how to use wrapper classes, that they're immutable, and that I have to create a new one each time I want to use a different value, but the way the assignment wants me to use it doesn't seem to work. The way I'm currently doing it is like so:

for(int i = 0; i < 1000; i++) {
Integer intSum = new Integer(primSum);
executor.execute(new SumTask(intSum));
}


...where "primSum" is a public int variable initialized to zero and which is updated directly from the SumTask task, and "SumTask" is a thread class I have created to receive the Integer object with its constructor then call a synchronized method from its run method to perform the increment. The primSum variable is then manually updated (like primSum++, since my thread class is an inner class of the public class) so that the next intSum being created will supposedly be created with the new primSum value.

I thought at first that my synchronization was somehow being ignored or something, then I realized (with some clever placement system.out prints) that the loop iterates faster than the threads finish, so most of the Integer objects and threads in the loop are created with old values which haven't had a chance to be updated yet. I know the point of the assignment is actually the synchronization, which I have done, but which doesn't make any difference if I can't get the Integers to be created with the correct new values. I tried modifying the code to pass the primitive int by itself (by value) and that works like a charm.

I considered creating a mutable custom wrapper class, but the instructions specify the Integer wrapper class, so I guess I'm stuck with that.

It all boils down to this: How can I get it to create a new Integer object only after the "primSum" variable has been incremented via the SumTask thread... But still be passing the int by reference?


(I can post my code if it will help... It's only about 40 lines)
 
Status
Not open for further replies.
Back
Top Bottom