Skip to content

How to terminate an Agrona Agent

Problem

A process is built with one or more Agrona Agents. A terminal error has occured in an agent, and you want the agent to terminate.

Solution

Within your agent's duty cycle, throw an AgentTerminationException.

Sample

Sample duty cycle in an Agent:

1
2
3
4
5
6
7
8
int doWork()
{
    if (terminalError) 
    {
        throw new AgentTerminationException("reason");
    }
    ...
}

Discussion

Typically, AgentRunner is used to manage Agents running on their own dedicated (or shared via CompositeAgent) threads. In the run() method of AgentRunner, the duty cycle executes in a while loop that checks the isRunning flag:

1
2
3
4
while (isRunning)
{
    doDutyCycle(idleStrategy, agent);
}

If your Agent throws AgentTermination exception, the isRunning flag is set to false:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
private void doDutyCycle(final IdleStrategy idleStrategy, final Agent agent)
{
    try
    {
        ...
    }
    catch (final AgentTerminationException ex)
    {
        isRunning = false;
        handleError(ex);
    }
    ...
}

The primary alternate to AgentRunner, AgentInvoker has a similar construct:

```java linenums="1" public void start() { ... isRunning = true; ... }

And again, if the `Agent` throws `AgentTermination` exception during the `AgentInvoker.invoke()` method call, the `isRunning` flag is set to false:

```java linenums="1" 
public int invoke()
{
    try
    {
        ...
    }
    catch (final AgentTerminationException ex)
    {
        isRunning = false;
        ...
    }
    ...
}

Since the AgentInvoker requires the caller to run invoke(), you can confirm the state of isRunning by calling the AgentInvoker.isRunning() method.

See Also

Back to top