Next: Traveling around in a
Up: Performing time consuming operations
Previous: Test it out
  Contents
package org.kaariboga.agents;
import java.lang.Thread;
import org.kaariboga.core.Kaariboga;
import org.kaariboga.core.KaaribogaEvent;
/**
* Demonstrates the handling of time consuming applications by
* couning up to a given number.
*/
public class Counter extends Kaariboga
{
/**
* Used to end the thread.
*/
volatile Thread shouldLive;
/**
* Count up to i.
*/
int i;
/**
* Creates a new counter that counts up to a given number.
*/
public Counter (String name){
super("GoodCounter_" + name);
}
/**
* The run method just counts and ends when the thread is set to null.
* Transfered to another base it continues counting.
*/
public void run(){
shouldLive = Thread.currentThread();
Thread current = Thread.currentThread();
current.setPriority(4);
while (shouldLive == current && i < 100000){
++i;
System.out.println("Counting " + i);
current.yield();
}
fireDestroyRequest();
}
/**
* Called by the kaariboga base before the agent is dispatched to another base.
* Used here to end the current thread.
*/
public void onDispatch(){
shouldLive = null;
}
/**
* Called by the kaariboga base when this agent has to be destroyed.
* Used to end the current thread.
*/
public void onDestroy(){
shouldLive = null;
}
}
The new thing is how time consuming operations may be interrupted. If you program mobile
agents you must make shure that your agent is terminated properly. If an agent has to be
terminated on one computer the base server calls the method onDispatch or onDestroy. Both
must provide proper clean up code.
public void onDestroy(){
shouldLive = null;
}
Here the variable shouldLive is set to null. shouldLive is declared as volatile Thread
shouldLive so it can be immediately checked by the thread.
Let's see what happens to the main thread.
public void run(){
shouldLive = Thread.currentThread();
Thread current = Thread.currentThread();
current.setPriority(4);
while (shouldLive == current && i < 100000){
++i;
System.out.println("Counting " + i);
current.yield();
}
fireDestroyRequest();
}
Here the variable shouldLive is continuously compared to the current thread. If shouldLive is
set to null for some reason the agent fires a destroy request to kill itself. If your agent operates
on some data you should do some proper clean up before fireDestroyRequest.
Note that current.setPriority(4) sets the thread's priority to a lower value and
current.yield() is called. Both commands are necessary on some machines to give other
threads a chance to execute.
Dirk
2002-09-01