I am running 4 and sometimes more threads. Each thread needs to
iterate through a Hashmap. And 3 threads add and remove from the
hashmap. I want to prevent a thread from iterating during an add or
remove operation. Do I need to run them one at a time? and if so,
how. Im fairly new to threads.
Thank you
Jerry
They should all synchronize on a common object, like the Hashmap itself,
during their operations on it. Only one thread will be able to enter
the synchronized block at a time.
If the computations are very long, like database lookups, synchronize on
the Hashmap while transferring batches of work data to/from it. You can
then perform lengthy processing on the local batch copy without holding
a lock on the shared Hashmap. You can also swap the Hashmap references
during a synchronization lock but you'll need to use some other object
for synchronization.
Also check out wait() and notify() while you're learning about threads.