org.agrona.concurrent.SigInt Java Examples

The following examples show how to use org.agrona.concurrent.SigInt. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SendHackSelectReceiveUdpPing.java    From aeron with Apache License 2.0 6 votes vote down vote up
private void run() throws IOException
{
    receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));

    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final Selector selector = Selector.open();
    receiveChannel.register(selector, OP_READ, this);
    final NioSelectedKeySet keySet = Common.keySet(selector);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (running.get())
    {
        measureRoundTrip(HISTOGRAM, SEND_ADDRESS, buffer, sendChannel, selector, keySet, running);

        HISTOGRAM.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}
 
Example #2
Source File: SampleUtil.java    From artio with Apache License 2.0 6 votes vote down vote up
public static void runAgentUntilSignal(
    final Agent agent, final MediaDriver mediaDriver) throws InterruptedException
{
    final AtomicCounter errorCounter =
        mediaDriver.context().countersManager().newCounter("exchange_agent_errors");
    final AgentRunner runner = new AgentRunner(
        CommonConfiguration.backoffIdleStrategy(),
        Throwable::printStackTrace,
        errorCounter,
        agent);

    final Thread thread = AgentRunner.startOnThread(runner);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (running.get())
    {
        Thread.sleep(100);
    }

    thread.join();
}
 
Example #3
Source File: BenchServer.java    From rpc-bench with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("PMD.NullAssignment")
public BenchServer() {
  running = new AtomicBoolean(true);
  SigInt.register(() -> running.set(false));
  driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
  ctx = new Aeron.Context();
  if (EMBEDDED_MEDIA_DRIVER) {
    ctx.aeronDirectoryName(driver.aeronDirectoryName());
  }
  fragmentHandler = new FragmentAssembler(this::onMessage);
  aeron = Aeron.connect(ctx);
  publication = aeron.addPublication(REP_CHAN, REP_STREAM_ID);
  subscription = aeron.addSubscription(REQ_CHAN, REQ_STREAM_ID);
}
 
Example #4
Source File: EmbeddedBufferClaimIpcThroughput.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception
{
    loadPropertiesFiles(args);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    final MediaDriver.Context ctx = new MediaDriver.Context()
        .threadingMode(ThreadingMode.SHARED);

    try (MediaDriver ignore = MediaDriver.launch(ctx);
        Aeron aeron = Aeron.connect();
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID);
        Publication publication = aeron.addPublication(CHANNEL, STREAM_ID))
    {
        final ImageRateSubscriber subscriber = new ImageRateSubscriber(FRAGMENT_COUNT_LIMIT, running, subscription);
        final Thread subscriberThread = new Thread(subscriber);
        subscriberThread.setName("subscriber");
        final Thread publisherThread = new Thread(new Publisher(running, publication));
        publisherThread.setName("publisher");
        final Thread rateReporterThread = new Thread(new ImageRateReporter(MESSAGE_LENGTH, running, subscriber));
        rateReporterThread.setName("rate-reporter");

        rateReporterThread.start();
        subscriberThread.start();
        publisherThread.start();

        subscriberThread.join();
        publisherThread.join();
        rateReporterThread.join();
    }
}
 
Example #5
Source File: EmbeddedExclusiveBufferClaimIpcThroughput.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception
{
    loadPropertiesFiles(args);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    final MediaDriver.Context ctx = new MediaDriver.Context()
        .threadingMode(ThreadingMode.SHARED);

    try (MediaDriver ignore = MediaDriver.launch(ctx);
        Aeron aeron = Aeron.connect();
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID);
        Publication publication = aeron.addExclusivePublication(CHANNEL, STREAM_ID))
    {
        final ImageRateSubscriber subscriber = new ImageRateSubscriber(FRAGMENT_COUNT_LIMIT, running, subscription);
        final Thread subscriberThread = new Thread(subscriber);
        subscriberThread.setName("subscriber");
        final Thread publisherThread = new Thread(new Publisher(running, publication));
        publisherThread.setName("publisher");
        final Thread rateReporterThread = new Thread(new ImageRateReporter(MESSAGE_LENGTH, running, subscriber));
        rateReporterThread.setName("rate-reporter");

        rateReporterThread.start();
        subscriberThread.start();
        publisherThread.start();

        subscriberThread.join();
        publisherThread.join();
        rateReporterThread.join();
    }
}
 
Example #6
Source File: BasicSubscriber.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args)
{
    System.out.println("Subscribing to " + CHANNEL + " on stream id " + STREAM_ID);

    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final Aeron.Context ctx = new Aeron.Context()
        .availableImageHandler(SamplesUtil::printAvailableImage)
        .unavailableImageHandler(SamplesUtil::printUnavailableImage);

    if (EMBEDDED_MEDIA_DRIVER)
    {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }

    final FragmentHandler fragmentHandler = SamplesUtil.printStringMessage(STREAM_ID);
    final AtomicBoolean running = new AtomicBoolean(true);

    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));

    // Create an Aeron instance using the configured Context and create a
    // Subscription on that instance that subscribes to the configured
    // channel and stream ID.
    // The Aeron and Subscription classes implement "AutoCloseable" and will automatically
    // clean up resources when this try block is finished
    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID))
    {
        SamplesUtil.subscriberLoop(fragmentHandler, FRAGMENT_COUNT_LIMIT, running).accept(subscription);

        System.out.println("Shutting down...");
    }

    CloseHelper.quietClose(driver);
}
 
Example #7
Source File: AeronStat.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static void workLoop(final long delayMs, final Runnable outputPrinter) throws Exception
{
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    do
    {
        clearScreen();
        outputPrinter.run();
        Thread.sleep(delayMs);
    }
    while (running.get());
}
 
Example #8
Source File: ReplayedBasicSubscriber.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args)
{
    System.out.println("Subscribing to " + CHANNEL + " on stream id " + STREAM_ID);

    final FragmentHandler fragmentHandler = SamplesUtil.printStringMessage(STREAM_ID);
    final AtomicBoolean running = new AtomicBoolean(true);

    SigInt.register(() -> running.set(false));

    // Create a unique response stream id so not to clash with other archive clients.
    final AeronArchive.Context archiveCtx = new AeronArchive.Context()
        .controlResponseStreamId(AeronArchive.Configuration.controlResponseStreamId() + 2);

    try (AeronArchive archive = AeronArchive.connect(archiveCtx))
    {
        final long recordingId = findLatestRecording(archive);
        final long position = 0L;
        final long length = Long.MAX_VALUE;

        final long sessionId = archive.startReplay(recordingId, position, length, CHANNEL, REPLAY_STREAM_ID);
        final String channel = ChannelUri.addSessionId(CHANNEL, (int)sessionId);

        try (Subscription subscription = archive.context().aeron().addSubscription(channel, REPLAY_STREAM_ID))
        {
            SamplesUtil.subscriberLoop(fragmentHandler, FRAGMENT_COUNT_LIMIT, running).accept(subscription);
            System.out.println("Shutting down...");
        }
    }
}
 
Example #9
Source File: HistogramLogReader.java    From artio with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws IOException
{
    if (args.length < 1)
    {
        System.err.println("Usage: HistogramLogReader <logFile>");
        System.err.println("Where <logFile> is the path to histogram log file");
        System.exit(-1);
    }

    final String path = args[0];
    final File file = new File(path);
    final double scalingFactor = MICROSECONDS.toNanos(1);
    final BackoffIdleStrategy idleStrategy = new BackoffIdleStrategy(0, 0, MILLISECONDS.toNanos(1),
        MINUTES.toNanos(1));

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    try (HistogramLogReader logReader = new HistogramLogReader(file))
    {
        do
        {
            final int sampleCount = logReader.read(
                (recordedAtTime, name, histogram) -> prettyPrint(recordedAtTime, histogram, name, scalingFactor));

            idleStrategy.idle(sampleCount);
        }
        while (running.get());
    }
}
 
Example #10
Source File: AeronNDArrayResponder.java    From nd4j with Apache License 2.0 4 votes vote down vote up
/**
 * Launch a background thread
 * that subscribes to  the aeron context
 * @throws Exception
 */
public void launch() throws Exception {
    if (init.get())
        return;
    // Register a SIGINT handler for graceful shutdown.
    if (!init.get())
        init();

    log.info("Subscribing to " + channel + " on stream Id " + streamId);

    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));

    // Create an Aeron instance with client-provided context configuration, connect to the
    // media driver, and add a subscription for the given channel and stream using the supplied
    // dataHandler method, which will be called with new messages as they are received.
    // The Aeron and Subscription classes implement AutoCloseable, and will automatically
    // clean up resources when this try block is finished.
    //Note here that we are either creating 1 or 2 subscriptions.
    //The first one is a  normal 1 subscription listener.
    //The second one is when we want to send responses
    boolean started = false;
    int numTries = 0;
    while (!started && numTries < 3) {
        try {
            try (final Subscription subscription = aeron.addSubscription(channel, streamId)) {
                log.info("Beginning subscribe on channel " + channel + " and stream " + streamId);
                AeronUtil.subscriberLoop(new FragmentAssembler(NDArrayResponseFragmentHandler.builder().aeron(aeron)
                                .context(ctx).streamId(responseStreamId).holder(ndArrayHolder).build()),
                                fragmentLimitCount, running, launched).accept(subscription);
                started = true;
            }


        } catch (Exception e) {
            numTries++;
            log.warn("Failed to connect..trying again", e);
        }
    }

    if (numTries >= 3)
        throw new IllegalStateException("Was unable to start responder after " + numTries + "tries");


}
 
Example #11
Source File: AeronNDArraySubscriber.java    From nd4j with Apache License 2.0 4 votes vote down vote up
/**
 * Launch a background thread
 * that subscribes to  the aeron context
 * @throws Exception
 */
public void launch() throws Exception {
    if (init.get())
        return;
    // Register a SIGINT handler for graceful shutdown.
    if (!init.get())
        init();

    log.info("Subscribing to " + channel + " on stream Id " + streamId);
    log.info("Using aeron directory " + ctx.aeronDirectoryName());

    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));

    // Create an Aeron instance with client-provided context configuration, connect to the
    // media driver, and add a subscription for the given channel and stream using the supplied
    // dataHandler method, which will be called with new messages as they are received.
    // The Aeron and Subscription classes implement AutoCloseable, and will automatically
    // clean up resources when this try block is finished.
    //Note here that we are either creating 1 or 2 subscriptions.
    //The first one is a  normal 1 subscription listener.
    //The second one is when we want to send responses

    if (channel == null)
        throw new IllegalStateException("No channel for subscriber defined");
    if (streamId <= 0)
        throw new IllegalStateException("No stream for subscriber defined");
    if (aeron == null)
        throw new IllegalStateException("No aeron instance defined");
    boolean started = false;
    while (!started) {
        try (final Subscription subscription = aeron.addSubscription(channel, streamId)) {
            this.subscription = subscription;
            log.info("Beginning subscribe on channel " + channel + " and stream " + streamId);
            AeronUtil.subscriberLoop(new FragmentAssembler(new NDArrayFragmentHandler(ndArrayCallback)),
                            fragmentLimitCount, running, launched).accept(subscription);
            started = true;

        } catch (Exception e) {
            log.warn("Unable to connect...trying again on channel " + channel, e);
        }
    }

}
 
Example #12
Source File: AeronNDArrayResponder.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
/**
 * Launch a background thread
 * that subscribes to  the aeron context
 * @throws Exception
 */
public void launch() throws Exception {
    if (init.get())
        return;
    // Register a SIGINT handler for graceful shutdown.
    if (!init.get())
        init();

    log.info("Subscribing to " + channel + " on stream Id " + streamId);

    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));

    // Create an Aeron instance with client-provided context configuration, connect to the
    // media driver, and add a subscription for the given channel and stream using the supplied
    // dataHandler method, which will be called with new messages as they are received.
    // The Aeron and Subscription classes implement AutoCloseable, and will automatically
    // clean up resources when this try block is finished.
    //Note here that we are either creating 1 or 2 subscriptions.
    //The first one is a  normal 1 subscription listener.
    //The second one is when we want to send responses
    boolean started = false;
    int numTries = 0;
    while (!started && numTries < 3) {
        try {
            try (final Subscription subscription = aeron.addSubscription(channel, streamId)) {
                log.info("Beginning subscribe on channel " + channel + " and stream " + streamId);
                AeronUtil.subscriberLoop(new FragmentAssembler(NDArrayResponseFragmentHandler.builder().aeron(aeron)
                                .context(ctx).streamId(responseStreamId).holder(ndArrayHolder).build()),
                                fragmentLimitCount, running, launched).accept(subscription);
                started = true;
            }


        } catch (Exception e) {
            numTries++;
            log.warn("Failed to connect..trying again", e);
        }
    }

    if (numTries >= 3)
        throw new IllegalStateException("Was unable to start responder after " + numTries + "tries");


}
 
Example #13
Source File: AeronStat.java    From nd4j with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception {
    Pattern typeFilter = null;
    Pattern identityFilter = null;
    Pattern sessionFilter = null;
    Pattern streamFilter = null;
    Pattern channelFilter = null;

    if (0 != args.length) {
        checkForHelp(args);

        for (final String arg : args) {
            final int equalsIndex = arg.indexOf('=');
            if (-1 == equalsIndex) {
                System.out.println("Arguments must be in opName=pattern format: Invalid '" + arg + "'");
                return;
            }

            final String argName = arg.substring(0, equalsIndex);
            final String argValue = arg.substring(equalsIndex + 1);

            switch (argName) {
                case COUNTER_TYPE_ID:
                    typeFilter = Pattern.compile(argValue);
                    break;

                case COUNTER_IDENTITY:
                    identityFilter = Pattern.compile(argValue);
                    break;

                case COUNTER_SESSION_ID:
                    sessionFilter = Pattern.compile(argValue);
                    break;

                case COUNTER_STREAM_ID:
                    streamFilter = Pattern.compile(argValue);
                    break;

                case COUNTER_CHANNEL:
                    channelFilter = Pattern.compile(argValue);
                    break;

                default:
                    System.out.println("Unrecognised argument: '" + arg + "'");
                    return;
            }
        }
    }

    final AeronStat aeronStat = new AeronStat(mapCounters(), typeFilter, identityFilter, sessionFilter,
                    streamFilter, channelFilter);
    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (running.get()) {
        System.out.print("\033[H\033[2J");

        System.out.format("%1$tH:%1$tM:%1$tS - Aeron Stat%n", new Date());
        System.out.println("=========================");

        aeronStat.print(System.out);
        System.out.println("--");

        Thread.sleep(ONE_SECOND);
    }
}
 
Example #14
Source File: SimpleSubscriber.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args)
{
    // 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();

    // Create an Aeron instance with client-provided context configuration, connect to the
    // media driver, and add a subscription for the given channel and stream using the supplied
    // dataHandler method, which will be called with new messages as they are received.
    // The Aeron and Subscription classes implement AutoCloseable, and will automatically
    // 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...");
    }
}
 
Example #15
Source File: AeronNDArraySubscriber.java    From deeplearning4j with Apache License 2.0 4 votes vote down vote up
/**
 * Launch a background thread
 * that subscribes to  the aeron context
 * @throws Exception
 */
public void launch() throws Exception {
    if (init.get())
        return;
    // Register a SIGINT handler for graceful shutdown.
    if (!init.get())
        init();

    log.info("Subscribing to " + channel + " on stream Id " + streamId);
    log.info("Using aeron directory " + ctx.aeronDirectoryName());

    // Register a SIGINT handler for graceful shutdown.
    SigInt.register(() -> running.set(false));

    // Create an Aeron instance with client-provided context configuration, connect to the
    // media driver, and add a subscription for the given channel and stream using the supplied
    // dataHandler method, which will be called with new messages as they are received.
    // The Aeron and Subscription classes implement AutoCloseable, and will automatically
    // clean up resources when this try block is finished.
    //Note here that we are either creating 1 or 2 subscriptions.
    //The first one is a  normal 1 subscription listener.
    //The second one is when we want to send responses

    if (channel == null)
        throw new IllegalStateException("No channel for subscriber defined");
    if (streamId <= 0)
        throw new IllegalStateException("No stream for subscriber defined");
    if (aeron == null)
        throw new IllegalStateException("No aeron instance defined");
    boolean started = false;
    while (!started) {
        try (final Subscription subscription = aeron.addSubscription(channel, streamId)) {
            this.subscription = subscription;
            log.info("Beginning subscribe on channel " + channel + " and stream " + streamId);
            AeronUtil.subscriberLoop(new FragmentAssembler(new NDArrayFragmentHandler(ndArrayCallback)),
                            fragmentLimitCount, running, launched).accept(subscription);
            started = true;

        } catch (Exception e) {
            log.warn("Unable to connect...trying again on channel " + channel, e);
        }
    }

}
 
Example #16
Source File: HackSelectReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
private void run() throws IOException
{
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));

    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final Selector selector = Selector.open();
    final NioSelectedKeySet keySet = Common.keySet(selector);

    final ToIntFunction<SelectionKey> handler =
        (key) ->
        {
            try
            {
                buffer.clear();
                receiveChannel.receive(buffer);

                final long receivedSequenceNumber = buffer.getLong(0);
                final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

                buffer.clear();
                buffer.putLong(receivedSequenceNumber);
                buffer.putLong(receivedTimestamp);
                buffer.flip();

                sendChannel.send(buffer, sendAddress);
            }
            catch (final IOException ex)
            {
                ex.printStackTrace();
            }

            return 1;
        };

    receiveChannel.register(selector, OP_READ, null);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        while (selector.selectNow() == 0)
        {
            if (!running.get())
            {
                return;
            }
        }

        keySet.forEach(handler);
    }
}
 
Example #17
Source File: ReceiveWriteUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws IOException
{
    int numChannels = 1;
    if (1 == args.length)
    {
        numChannels = Integer.parseInt(args[0]);
    }

    final ByteBuffer buffer = ByteBuffer.allocateDirect(MTU_LENGTH_DEFAULT);

    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++)
    {
        receiveChannels[i] = DatagramChannel.open();
        Common.init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", Common.PING_PORT + i));
    }

    final InetSocketAddress writeAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final DatagramChannel writeChannel = DatagramChannel.open();
    Common.init(writeChannel, writeAddress);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        buffer.clear();

        boolean available = false;
        while (!available)
        {
            if (!running.get())
            {
                return;
            }

            for (int i = receiveChannels.length - 1; i >= 0; i--)
            {
                if (null != receiveChannels[i].receive(buffer))
                {
                    available = true;
                    break;
                }
            }
        }

        final long receivedSequenceNumber = buffer.getLong(0);
        final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

        buffer.clear();
        buffer.putLong(receivedSequenceNumber);
        buffer.putLong(receivedTimestamp);
        buffer.flip();

        writeChannel.write(buffer);
    }
}
 
Example #18
Source File: ReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws IOException
{
    int numChannels = 1;
    if (1 == args.length)
    {
        numChannels = Integer.parseInt(args[0]);
    }

    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel[] receiveChannels = new DatagramChannel[numChannels];
    for (int i = 0; i < receiveChannels.length; i++)
    {
        receiveChannels[i] = DatagramChannel.open();
        init(receiveChannels[i]);
        receiveChannels[i].bind(new InetSocketAddress("localhost", Common.PING_PORT + i));
    }

    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);
    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        buffer.clear();

        boolean available = false;
        while (!available)
        {
            if (!running.get())
            {
                return;
            }

            for (int i = receiveChannels.length - 1; i >= 0; i--)
            {
                if (null != receiveChannels[i].receive(buffer))
                {
                    available = true;
                    break;
                }
            }
        }

        final long receivedSequenceNumber = buffer.getLong(0);
        final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

        buffer.clear();
        buffer.putLong(receivedSequenceNumber);
        buffer.putLong(receivedTimestamp);
        buffer.flip();

        sendChannel.send(buffer, sendAddress);
    }
}
 
Example #19
Source File: SendSelectReceiveUdpPing.java    From aeron with Apache License 2.0 4 votes vote down vote up
private void run() throws IOException
{
    final Histogram histogram = new Histogram(TimeUnit.SECONDS.toNanos(10), 3);
    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PONG_PORT));

    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final Selector selector = Selector.open();

    final IntSupplier handler =
        () ->
        {
            try
            {
                buffer.clear();
                receiveChannel.receive(buffer);

                final long receivedSequenceNumber = buffer.getLong(0);
                final long timestampNs = buffer.getLong(SIZE_OF_LONG);

                if (receivedSequenceNumber != sequenceNumber)
                {
                    throw new IllegalStateException(
                        "data Loss:" + sequenceNumber + " to " + receivedSequenceNumber);
                }

                final long durationNs = System.nanoTime() - timestampNs;
                histogram.recordValue(durationNs);
            }
            catch (final IOException ex)
            {
                ex.printStackTrace();
            }

            return 1;
        };

    receiveChannel.register(selector, OP_READ, handler);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (running.get())
    {
        measureRoundTrip(histogram, SEND_ADDRESS, buffer, sendChannel, selector, running);

        histogram.reset();
        System.gc();
        LockSupport.parkNanos(1000 * 1000 * 1000);
    }
}
 
Example #20
Source File: SelectReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
private void run() throws IOException
{
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);

    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));

    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final Selector selector = Selector.open();

    final IntSupplier handler =
        () ->
        {
            try
            {
                buffer.clear();
                receiveChannel.receive(buffer);

                final long receivedSequenceNumber = buffer.getLong(0);
                final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

                buffer.clear();
                buffer.putLong(receivedSequenceNumber);
                buffer.putLong(receivedTimestamp);
                buffer.flip();

                sendChannel.send(buffer, sendAddress);
            }
            catch (final IOException ex)
            {
                ex.printStackTrace();
            }

            return 1;
        };

    receiveChannel.register(selector, OP_READ, handler);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        while (selector.selectNow() == 0)
        {
            if (!running.get())
            {
                return;
            }
        }

        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> iter = selectedKeys.iterator();

        while (iter.hasNext())
        {
            final SelectionKey key = iter.next();
            if (key.isReadable())
            {
                ((IntSupplier)key.attachment()).getAsInt();
            }

            iter.remove();
        }
    }
}
 
Example #21
Source File: RateSubscriber.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args) throws Exception
{
    System.out.println("Subscribing to " + CHANNEL + " on stream id " + STREAM_ID);

    final MediaDriver driver = EMBEDDED_MEDIA_DRIVER ? MediaDriver.launchEmbedded() : null;
    final ExecutorService executor = Executors.newFixedThreadPool(1);
    final Aeron.Context ctx = new Aeron.Context()
        .availableImageHandler(SamplesUtil::printAvailableImage)
        .unavailableImageHandler(SamplesUtil::printUnavailableImage);

    if (EMBEDDED_MEDIA_DRIVER)
    {
        ctx.aeronDirectoryName(driver.aeronDirectoryName());
    }

    final RateReporter reporter = new RateReporter(TimeUnit.SECONDS.toNanos(1), SamplesUtil::printRate);
    final AtomicBoolean running = new AtomicBoolean(true);

    SigInt.register(() ->
    {
        reporter.halt();
        running.set(false);
    });

    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(CHANNEL, STREAM_ID))
    {
        final Future<?> future = executor.submit(() -> SamplesUtil.subscriberLoop(
            rateReporterHandler(reporter), FRAGMENT_COUNT_LIMIT, running).accept(subscription));

        reporter.run();

        System.out.println("Shutting down...");
        future.get();
    }

    executor.shutdown();
    if (!executor.awaitTermination(5, TimeUnit.SECONDS))
    {
        System.out.println("Warning: not all tasks completed promptly");
    }

    CloseHelper.quietClose(driver);
}
 
Example #22
Source File: Pong.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args)
{
    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);
    System.out.println("Using exclusive publications " + EXCLUSIVE_PUBLICATIONS);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    try (Aeron aeron = Aeron.connect(ctx);
        Subscription subscription = aeron.addSubscription(PING_CHANNEL, PING_STREAM_ID);
        Publication publication = EXCLUSIVE_PUBLICATIONS ?
            aeron.addExclusivePublication(PONG_CHANNEL, PONG_STREAM_ID) :
            aeron.addPublication(PONG_CHANNEL, PONG_STREAM_ID))
    {
        final BufferClaim bufferClaim = new BufferClaim();
        final FragmentHandler fragmentHandler = (buffer, offset, length, header) ->
            pingHandler(bufferClaim, publication, buffer, offset, length, header);

        while (running.get())
        {
            idleStrategy.idle(subscription.poll(fragmentHandler, FRAME_COUNT_LIMIT));
        }

        System.out.println("Shutting down...");
    }

    CloseHelper.quietClose(driver);
}
 
Example #23
Source File: MultipleSubscribersWithFragmentAssembly.java    From aeron with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args)
{
    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...");
    }
}
 
Example #24
Source File: SampleServer.java    From artio with Apache License 2.0 4 votes vote down vote up
public static void main(final String[] args)
{
    final MessageValidationStrategy validationStrategy = MessageValidationStrategy.targetCompId(ACCEPTOR_COMP_ID)
        .and(MessageValidationStrategy.senderCompId(Collections.singletonList(INITIATOR_COMP_ID)));

    final AuthenticationStrategy authenticationStrategy = AuthenticationStrategy.of(validationStrategy);

    // Static configuration lasts the duration of a FIX-Gateway instance
    final String aeronChannel = "aeron:udp?endpoint=localhost:10000";
    final EngineConfiguration configuration = new EngineConfiguration()
        .bindTo("localhost", 9999)
        .libraryAeronChannel(aeronChannel);
    configuration.authenticationStrategy(authenticationStrategy);

    cleanupOldLogFileDir(configuration);

    final Context context = new Context()
        .threadingMode(SHARED)
        .dirDeleteOnStart(true);

    final Archive.Context archiveContext = new Archive.Context()
        .threadingMode(ArchiveThreadingMode.SHARED)
        .deleteArchiveOnStart(true);

    try (ArchivingMediaDriver driver = ArchivingMediaDriver.launch(context, archiveContext);
        FixEngine gateway = FixEngine.launch(configuration))
    {
        final LibraryConfiguration libraryConfiguration = new LibraryConfiguration();

        // You register the new session handler - which is your application hook
        // that receives messages for new sessions
        libraryConfiguration
            .sessionAcquireHandler((session, acquiredInfo) -> onConnect(session))
            .sessionExistsHandler(new AcquiringSessionExistsHandler())
            .libraryAeronChannels(singletonList(aeronChannel));

        final IdleStrategy idleStrategy = CommonConfiguration.backoffIdleStrategy();

        try (FixLibrary library = SampleUtil.blockingConnect(libraryConfiguration))
        {
            final AtomicBoolean running = new AtomicBoolean(true);
            SigInt.register(() -> running.set(false));

            while (running.get())
            {
                idleStrategy.idle(library.poll(1));

                if (session != null && session.state() == DISCONNECTED)
                {
                    break;
                }
            }
        }
    }

    System.exit(0);
}
 
Example #25
Source File: BenchServer.java    From rpc-bench with Apache License 2.0 4 votes vote down vote up
public BenchServer() {
  running = new AtomicBoolean(true);
  SigInt.register(() -> running.set(false));
  server = new Server(WRITE_BUFFER, OBJECT_BUFFER);
}