One way to limit the number of threads is to use a thread pool. Make threads that wait for commands that they can run. Any time you want to run some code on another thread you put a command containing the code in a queue and the next available thread gets it from the queue and runs it. You could keep a constant number of threads in the pool or let it grow and shrink over time. Look into thread pools in Java Tiger 5.0, Doug Lea's thread packages or the Apache Commons Thread Pool.
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 ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Mind your synchronization, gentlemen. On the face of it none of the code above is threadsafe
Joined: Aug 12, 2004
Thank you for the replies.
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 non-thread-safe code?
Peter den Haan
Joined: Apr 20, 2000
Originally posted by Sarat Burle: But is there a way to simulate the error that would arise due to non-thread-safe code?
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 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...
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus