How do you design a system in which you want only the last thread to finish to perform a certain action?
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Otis_Gospodnetic
Posted On:   Sunday, December 23, 2001 08:57 PM

How do you design a system in which you want only the last thread to finish doing something to perform a certain action? For instance, say that I have 2 threads going through a shared list of items. When they exhaust all items in the list they have to notify somebody (e.g. their listener) that they are done with the queue (and perhaps want another set of items to go though). Consider this: public void run() { boolean keepRunning = true; while (keepRunning) { synchronized (queue) { if (queue.size() > 0) Foo f = queue.removeLast(); else { keepRunning = false; break; } }    More>>

How do you design a system in which you want only the last thread to finish doing something to perform a certain action?


For instance, say that I have 2 threads going through a shared list of items. When they exhaust all items in the list they have to notify somebody (e.g. their listener) that they are done with the queue (and perhaps want another set of items to go though).


Consider this:


			
public void run()
{
boolean keepRunning = true;
while (keepRunning)
{
synchronized (queue)
{
if (queue.size() > 0)
Foo f = queue.removeLast();
else
{
keepRunning = false;
break;
}


}

// we are done with the queue
// let some listener know about
// that
someListener.queueIsEmpty();
}
}


The problem with this is that both threads will eventually reach the someListener.queueIsEmpty() call, which is obviously not correct.


Is there a common way of handling cases like this, so that only the last thread that completes operations calls someListener.queueIsEmpty() ?

Thanks,
Otis    <<Less

Re: How do you design a system in which you want only the last thread to finish to perform a certain action?

Posted By:   Alex_Chaffee  
Posted On:   Saturday, December 29, 2001 11:10 AM

The standard way to do this is to have a third thread that waits for both worker threads to finish.



t1.start();
t2.start();
t1.join();
t2.join();
listener.notify();

Search this FAQ for "join" for more info.

Re: How do you design a system in which you want only the last thread to finish to perform a certain action?

Posted By:   Christopher_Schultz  
Posted On:   Monday, December 24, 2001 07:06 AM

You could use a class like this:




public class Flag
{
private static boolean flag = false;

public synchronized static boolean testAndSet()
{
if(!flag)
flag = true;

return(flag);
}
}



Now, at the end of each of your threads, call this:




if(Flag.testAndSet())
someListener.queueIsEmpty();



Now, only one thread will execute this code. Unfortunately, this class will only see the first thread that completes. It is up to you to decide how to figure out which thread is the 'last' one.



Hope this helps,

-chris
About | Sitemap | Contact