Skip to content

How to build a blocking Aeron based API

Problem

You want to provide an API that hides the asynchronous nature of Aeron.

Solution

Poll the subscription within a while loop, checking a flag indicating if the result is returned. If set, return the result. You will need to construct a FragmentHandler which sets the flag and captures the result.

Sample

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//timeout clock
EpochClock clock = new SystemEpochClock();

public Object apiMethod(Object input)
{
    //prepare the input message
    DirectBuffer toAgent = convert(input);
    publication.offer(toAgent,...);

    //create a 1 second timeout
    long timeout = clock.getTime() + 1000; 

    while(!received && clock.getTime() <= timeout)
    {
        subscription.poll(fragmentHandler);
        if (resultReturned)
        {
            return result;
        }
        else
        {
            idleStrategy.idle();
        }
    }

    throw timeout;
}

Discussion

This is absolutely terrible for performance. Try to keep to an asynchronous API.

See Also

Back to top