Search in sources :

Example 1 with IdleStrategy

use of org.agrona.concurrent.IdleStrategy in project Aeron by real-logic.

the class Configuration method agentIdleStrategy.

/**
     * Get the {@link IdleStrategy} that should be applied to {@link org.agrona.concurrent.Agent}s.
     *
     * @param strategyName       to be created.
     * @param controllableStatus status indicator for what the strategy should do.
     * @return the newly created IdleStrategy.
     */
public static IdleStrategy agentIdleStrategy(final String strategyName, final StatusIndicator controllableStatus) {
    IdleStrategy idleStrategy = null;
    switch(strategyName) {
        case DEFAULT_IDLE_STRATEGY:
            idleStrategy = new BackoffIdleStrategy(AGENT_IDLE_MAX_SPINS, AGENT_IDLE_MAX_YIELDS, AGENT_IDLE_MIN_PARK_NS, AGENT_IDLE_MAX_PARK_NS);
            break;
        case CONTROLLABLE_IDLE_STRATEGY:
            idleStrategy = new ControllableIdleStrategy(controllableStatus);
            controllableStatus.setOrdered(ControllableIdleStrategy.PARK);
            break;
        default:
            try {
                idleStrategy = (IdleStrategy) Class.forName(strategyName).newInstance();
            } catch (final Exception ex) {
                LangUtil.rethrowUnchecked(ex);
            }
            break;
    }
    return idleStrategy;
}
Also used : ControllableIdleStrategy(org.agrona.concurrent.ControllableIdleStrategy) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) ControllableIdleStrategy(org.agrona.concurrent.ControllableIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) ConfigurationException(io.aeron.driver.exceptions.ConfigurationException)

Example 2 with IdleStrategy

use of org.agrona.concurrent.IdleStrategy in project Aeron by real-logic.

the class MultipleSubscribersWithFragmentAssembly method main.

public static void main(final String[] args) throws Exception {
    System.out.format("Subscribing to %s on stream ID %d and stream ID %d%n", CHANNEL, STREAM_ID_1, STREAM_ID_2);
    final Aeron.Context ctx = new Aeron.Context().availableImageHandler(MultipleSubscribersWithFragmentAssembly::eventAvailableImage).unavailableImageHandler(MultipleSubscribersWithFragmentAssembly::eventUnavailableImage);
    final FragmentAssembler dataHandler1 = new FragmentAssembler(reassembledStringMessage1(STREAM_ID_1));
    final FragmentAssembler dataHandler2 = new FragmentAssembler(reassembledStringMessage2(STREAM_ID_2));
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription1 = aeron.addSubscription(CHANNEL, STREAM_ID_1);
        Subscription subscription2 = aeron.addSubscription(CHANNEL, STREAM_ID_2)) {
        final IdleStrategy idleStrategy = new BackoffIdleStrategy(100, 10, TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100));
        int idleCount = 0;
        while (running.get()) {
            final int fragmentsRead1 = subscription1.poll(dataHandler1, FRAGMENT_COUNT_LIMIT);
            final int fragmentsRead2 = subscription2.poll(dataHandler2, FRAGMENT_COUNT_LIMIT);
            if ((fragmentsRead1 + fragmentsRead2) == 0) {
                idleStrategy.idle(idleCount++);
            } else {
                idleCount = 0;
            }
        }
        System.out.println("Shutting down...");
    }
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron) FragmentAssembler(io.aeron.FragmentAssembler)

Example 3 with IdleStrategy

use of org.agrona.concurrent.IdleStrategy in project Aeron by real-logic.

the class GapFillLossTest method shouldGapFillWhenLossOccurs.

@Test(timeout = 10000)
public void shouldGapFillWhenLossOccurs() throws Exception {
    final UnsafeBuffer srcBuffer = new UnsafeBuffer(ByteBuffer.allocateDirect(MSG_LENGTH));
    srcBuffer.setMemory(0, MSG_LENGTH, (byte) 7);
    final MediaDriver.Context ctx = new MediaDriver.Context().threadingMode(ThreadingMode.SHARED).publicationTermBufferLength(TERM_BUFFER_LENGTH);
    final LossReport lossReport = mock(LossReport.class);
    ctx.lossReport(lossReport);
    final LossGenerator dataLossGenerator = DebugChannelEndpointConfiguration.lossGeneratorSupplier(0.20, 0xcafebabeL);
    final LossGenerator noLossGenerator = DebugChannelEndpointConfiguration.lossGeneratorSupplier(0, 0);
    ctx.sendChannelEndpointSupplier((udpChannel, statusIndicator, context) -> new DebugSendChannelEndpoint(udpChannel, statusIndicator, context, noLossGenerator, noLossGenerator));
    ctx.receiveChannelEndpointSupplier((udpChannel, dispatcher, statusIndicator, context) -> new DebugReceiveChannelEndpoint(udpChannel, dispatcher, statusIndicator, context, dataLossGenerator, noLossGenerator));
    try (MediaDriver ignore = MediaDriver.launch(ctx);
        Aeron aeron = Aeron.connect();
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID);
        Subscription subscription = aeron.addSubscription(UNRELIABLE_CHANNEL, STREAM_ID)) {
        final IdleStrategy idleStrategy = new YieldingIdleStrategy();
        final Subscriber subscriber = new Subscriber(subscription);
        final Thread subscriberThread = new Thread(subscriber);
        subscriberThread.start();
        long position = 0;
        for (int i = 0; i < NUM_MESSAGES; i++) {
            srcBuffer.putLong(0, i);
            while ((position = publication.offer(srcBuffer)) < 0L) {
                idleStrategy.idle();
            }
        }
        FINAL_POSITION.set(position);
        subscriberThread.join();
        assertThat(subscriber.messageCount, lessThan(NUM_MESSAGES));
        verify(lossReport).createEntry(anyLong(), anyLong(), anyInt(), eq(STREAM_ID), anyString(), anyString());
    } finally {
        ctx.deleteAeronDirectory();
    }
}
Also used : YieldingIdleStrategy(org.agrona.concurrent.YieldingIdleStrategy) LossGenerator(io.aeron.driver.ext.LossGenerator) YieldingIdleStrategy(org.agrona.concurrent.YieldingIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) LossReport(io.aeron.driver.reports.LossReport) DebugSendChannelEndpoint(io.aeron.driver.ext.DebugSendChannelEndpoint) DebugSendChannelEndpoint(io.aeron.driver.ext.DebugSendChannelEndpoint) DebugReceiveChannelEndpoint(io.aeron.driver.ext.DebugReceiveChannelEndpoint) DebugReceiveChannelEndpoint(io.aeron.driver.ext.DebugReceiveChannelEndpoint) MediaDriver(io.aeron.driver.MediaDriver) UnsafeBuffer(org.agrona.concurrent.UnsafeBuffer) Test(org.junit.Test)

Example 4 with IdleStrategy

use of org.agrona.concurrent.IdleStrategy in project Aeron by real-logic.

the class Pong method main.

public static void main(final String[] args) throws Exception {
    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context ctx = new Aeron.Context();
    if (EMBEDDED_MEDIA_DRIVER) {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }
    if (INFO_FLAG) {
        ctx.availableImageHandler(SamplesUtil::printAvailableImage);
        ctx.unavailableImageHandler(SamplesUtil::printUnavailableImage);
    }
    final IdleStrategy idleStrategy = new BusySpinIdleStrategy();
    System.out.println("Subscribing Ping at " + PING_CHANNEL + " on stream Id " + PING_STREAM_ID);
    System.out.println("Publishing Pong at " + PONG_CHANNEL + " on stream Id " + PONG_STREAM_ID);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));
    try (Aeron aeron = Aeron.connect(ctx);
        Publication pongPublication = aeron.addPublication(PONG_CHANNEL, PONG_STREAM_ID);
        Subscription pingSubscription = aeron.addSubscription(PING_CHANNEL, PING_STREAM_ID)) {
        final FragmentAssembler dataHandler = new FragmentAssembler((buffer, offset, length, header) -> pingHandler(pongPublication, buffer, offset, length));
        while (running.get()) {
            idleStrategy.idle(pingSubscription.poll(dataHandler, FRAME_COUNT_LIMIT));
        }
        System.out.println("Shutting down...");
    }
    CloseHelper.quietClose(driver);
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MediaDriver(io.aeron.driver.MediaDriver) BusySpinIdleStrategy(org.agrona.concurrent.BusySpinIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) BusySpinIdleStrategy(org.agrona.concurrent.BusySpinIdleStrategy) Publication(io.aeron.Publication) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron) FragmentAssembler(io.aeron.FragmentAssembler)

Example 5 with IdleStrategy

use of org.agrona.concurrent.IdleStrategy in project Aeron by real-logic.

the class SimpleSubscriber method main.

public static void main(final String[] args) throws Exception {
    // Maximum number of message fragments to receive during a single 'poll' operation
    final int fragmentLimitCount = 10;
    // The channel (an endpoint identifier) to receive messages from
    final String channel = "aeron:udp?endpoint=localhost:40123";
    // A unique identifier for a stream within a channel. Stream ID 0 is reserved
    // for internal use and should not be used by applications.
    final int streamId = 10;
    System.out.println("Subscribing to " + channel + " on stream Id " + streamId);
    final AtomicBoolean running = new AtomicBoolean(true);
    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));
    // dataHandler method is called for every new datagram received
    final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> {
        final byte[] data = new byte[length];
        buffer.getBytes(offset, data);
        System.out.println(String.format("Received message (%s) to stream %d from session %x term id %x term offset %d (%d@%d)", new String(data), streamId, header.sessionId(), header.termId(), header.termOffset(), length, offset));
        // Received the intended message, time to exit the program
        running.set(false);
    };
    // Create a context, needed for client connection to media driver
    // A separate media driver process need to run prior to running this application
    final Aeron.Context ctx = new Aeron.Context();
    // clean up resources when this try block is finished.
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(channel, streamId)) {
        final IdleStrategy idleStrategy = new BackoffIdleStrategy(100, 10, TimeUnit.MICROSECONDS.toNanos(1), TimeUnit.MICROSECONDS.toNanos(100));
        // Try to read the data from subscriber
        while (running.get()) {
            // poll delivers messages to the dataHandler as they arrive
            // and returns number of fragments read, or 0
            // if no data is available.
            final int fragmentsRead = subscription.poll(fragmentHandler, fragmentLimitCount);
            // Give the IdleStrategy a chance to spin/yield/sleep to reduce CPU
            // use if no messages were received.
            idleStrategy.idle(fragmentsRead);
        }
        System.out.println("Shutting down...");
    }
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) Aeron(io.aeron.Aeron) Subscription(io.aeron.Subscription) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) FragmentHandler(io.aeron.logbuffer.FragmentHandler) SigInt(org.agrona.concurrent.SigInt) IdleStrategy(org.agrona.concurrent.IdleStrategy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) IdleStrategy(org.agrona.concurrent.IdleStrategy) FragmentHandler(io.aeron.logbuffer.FragmentHandler) BackoffIdleStrategy(org.agrona.concurrent.BackoffIdleStrategy) Subscription(io.aeron.Subscription) Aeron(io.aeron.Aeron)

Aggregations

IdleStrategy (org.agrona.concurrent.IdleStrategy)5 Aeron (io.aeron.Aeron)3 Subscription (io.aeron.Subscription)3 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)3 BackoffIdleStrategy (org.agrona.concurrent.BackoffIdleStrategy)3 FragmentAssembler (io.aeron.FragmentAssembler)2 MediaDriver (io.aeron.driver.MediaDriver)2 Publication (io.aeron.Publication)1 ConfigurationException (io.aeron.driver.exceptions.ConfigurationException)1 DebugReceiveChannelEndpoint (io.aeron.driver.ext.DebugReceiveChannelEndpoint)1 DebugSendChannelEndpoint (io.aeron.driver.ext.DebugSendChannelEndpoint)1 LossGenerator (io.aeron.driver.ext.LossGenerator)1 LossReport (io.aeron.driver.reports.LossReport)1 FragmentHandler (io.aeron.logbuffer.FragmentHandler)1 TimeUnit (java.util.concurrent.TimeUnit)1 BusySpinIdleStrategy (org.agrona.concurrent.BusySpinIdleStrategy)1 ControllableIdleStrategy (org.agrona.concurrent.ControllableIdleStrategy)1 SigInt (org.agrona.concurrent.SigInt)1 UnsafeBuffer (org.agrona.concurrent.UnsafeBuffer)1 YieldingIdleStrategy (org.agrona.concurrent.YieldingIdleStrategy)1