I have a requirement to restrict the number of active threads.
I have 3 classes, say A, B & C. B implements Runnable. C has a class level static variable, say, 'count'. 'A' has the main method.
When 'A' starts, it spawns threads of B, lets say 2 in number. B increments the value of the variable 'count'. After this, A terminates.
Now, again if 'A' is started, then before spawning the thread for 'B', what should be the value of the variable 'count'? Should it be '0' or '2'?
I am getting '0' but I was expecting '2'.
Is there something wrong or my expectation is incorrect?
Please let me know.
This code will show 0.
if you change it:
It will display 2.
[ August 28, 2004: Message edited by: Stefan Wagner ]
Regarding the static counter ... you could use that technique to increment it every time a thread starts, but be sure to decrement it when the thread ends.
To limit the number of threads running you'd have to do some kinda tricky stuff:
The next challenge is interrupting this thing when we decrement the counter. Lemme know if you think of a good way to do that!
[ August 28, 2004: Message edited by: Stan James ]
Stefan, I am incrementing the count in the run method. But my question was what would be the value when class A is run for the second time (assuming that the threads have incremented the value in the first run of A)?
Stan, I am sure going to decrement the count when the thread completes its processing. The incrementing part was just for testing.
Peter, if I have synchronized decrement & increment methods for variable (after making the variable private), I think the code would be thread-safe then. But is there a way to simulate the error that would arise due to
Not easily in this case, since the critical section is so small (between the load-increment-store operation in counter++). You can sort-of simulate it by coding out your increments and decrementsand putting a Thread.sleep() in between:Then running the result with a couple of threads.
Originally posted by Sarat Burle:
But is there a way to simulate the error that would arise due to
Originally posted by Peter den Haan:
Not easily in this case, since the critical section is so small (between the load-increment-store operation in counter++).
To make it even more complicated, wether you get an error might also heavily depend no the runtime environment. For example problems arising from cached memory not being updated with current values might only occur with certain VMs on multiprocessor systems...
'A' has the main method.
But my question was what would be the value when class A is run for the second time
If you don't run A from the same JVM (which is the normal situation), you get a separate room, with a new static C.count, which doesn't know anything about the other JVM, and the C.count used by it.