io.aeron.logbuffer.BufferClaim Java Examples

The following examples show how to use io.aeron.logbuffer.BufferClaim. 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: ILink3SenderEndPoint.java    From artio with Apache License 2.0 6 votes vote down vote up
public Action onReplayComplete(final long connectionId)
{
    final BufferClaim bufferClaim = this.bufferClaim;
    final long position = inboundPublication.tryClaim(REPLAY_COMPLETE_LENGTH, bufferClaim);

    if (Pressure.isBackPressured(position))
    {
        return ABORT;
    }

    replayComplete
        .wrapAndApplyHeader(bufferClaim.buffer(), bufferClaim.offset(), messageHeader)
        .connection(connectionId)
        .libraryId(libraryId);

    bufferClaim.commit();

    return CONTINUE;
}
 
Example #2
Source File: PossDupEnabler.java    From artio with Apache License 2.0 6 votes vote down vote up
public PossDupEnabler(
    final UtcTimestampEncoder utcTimestampEncoder,
    final BufferClaim bufferClaim,
    final Claimer claimer,
    final PreCommit onPreCommit,
    final Consumer<String> onIllegalStateFunc,
    final ErrorHandler errorHandler,
    final EpochClock clock,
    final int maxPayloadLength,
    final LogTag logTag)
{
    this.utcTimestampEncoder = utcTimestampEncoder;
    this.bufferClaim = bufferClaim;
    this.claimer = claimer;
    this.onPreCommit = onPreCommit;
    this.onIllegalStateFunc = onIllegalStateFunc;
    this.errorHandler = errorHandler;
    this.clock = clock;
    this.maxPayloadLength = maxPayloadLength;
    this.logTag = logTag;
}
 
Example #3
Source File: ILinkReplayerSession.java    From artio with Apache License 2.0 6 votes vote down vote up
public ILinkReplayerSession(
    final long connectionId,
    final BufferClaim bufferClaim,
    final IdleStrategy idleStrategy,
    final int maxClaimAttempts,
    final ExclusivePublication publication,
    final ReplayQuery replayQuery,
    final int beginSeqNo,
    final int endSeqNo,
    final long sessionId)
{
    super(connectionId, bufferClaim, idleStrategy, maxClaimAttempts, publication, replayQuery, beginSeqNo, endSeqNo,
        sessionId, 0);

    state = State.REPLAYING;
}
 
Example #4
Source File: ReplayerSession.java    From artio with Apache License 2.0 6 votes vote down vote up
protected ReplayerSession(
    final long connectionId,
    final BufferClaim bufferClaim,
    final IdleStrategy idleStrategy,
    final int maxClaimAttempts,
    final ExclusivePublication publication,
    final ReplayQuery replayQuery,
    final int beginSeqNo,
    final int endSeqNo,
    final long sessionId,
    final int sequenceIndex)
{
    this.connectionId = connectionId;
    this.bufferClaim = bufferClaim;
    this.idleStrategy = idleStrategy;
    this.maxClaimAttempts = maxClaimAttempts;
    this.publication = publication;
    this.replayQuery = replayQuery;
    this.beginSeqNo = beginSeqNo;
    this.endSeqNo = endSeqNo;
    this.sessionId = sessionId;
    this.sequenceIndex = sequenceIndex;
}
 
Example #5
Source File: EngineContext.java    From artio with Apache License 2.0 6 votes vote down vote up
private Replayer newReplayer(
    final ExclusivePublication replayPublication, final ReplayQuery replayQuery)
{
    final EpochFractionFormat epochFractionFormat = configuration.sessionEpochFractionFormat();
    return new Replayer(
        replayQuery,
        replayPublication,
        new BufferClaim(),
        configuration.archiverIdleStrategy(),
        errorHandler,
        configuration.outboundMaxClaimAttempts(),
        inboundLibraryStreams.subscription("replayer"),
        configuration.agentNamePrefix(),
        new SystemEpochClock(),
        configuration.gapfillOnReplayMessageTypes(),
        configuration.replayHandler(),
        senderSequenceNumbers,
        new FixSessionCodecsFactory(epochFractionFormat),
        configuration.senderMaxBytesInBuffer(),
        replayerCommandQueue,
        epochFractionFormat,
        fixCounters.currentReplayCount(),
        configuration.maxConcurrentSessionReplays());
}
 
Example #6
Source File: EmbeddedBufferClaimIpcThroughput.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void run()
{
    final IdleStrategy idleStrategy = SampleConfiguration.newIdleStrategy();
    final AtomicBoolean running = this.running;
    final Publication publication = this.publication;
    final BufferClaim bufferClaim = new BufferClaim();
    long backPressureCount = 0;
    long totalMessageCount = 0;

    outputResults:
    while (running.get())
    {
        for (int i = 0; i < BURST_LENGTH; i++)
        {
            idleStrategy.reset();
            while (publication.tryClaim(MESSAGE_LENGTH, bufferClaim) <= 0)
            {
                ++backPressureCount;
                if (!running.get())
                {
                    break outputResults;
                }
                idleStrategy.idle();
            }

            final int offset = bufferClaim.offset();
            bufferClaim.buffer().putInt(offset, i); // Example field write
            // Real app would write whatever fields are required via a flyweight like SBE

            bufferClaim.commit();

            ++totalMessageCount;
        }
    }

    final double backPressureRatio = backPressureCount / (double)totalMessageCount;
    System.out.format("Publisher back pressure ratio: %f%n", backPressureRatio);
}
 
Example #7
Source File: ClaimablePublication.java    From artio with Apache License 2.0 5 votes vote down vote up
public long claim(final int framedLength, final BufferClaim bufferClaim)
{
    long position;
    long i = 0;
    do
    {
        position = dataPublication.tryClaim(framedLength, bufferClaim);

        if (position > 0L)
        {
            return position;
        }
        else
        {
            idleStrategy.idle();
        }

        fails.increment();
        i++;
    }
    while (i <= maxClaimAttempts);

    idleStrategy.reset();

    if (position == CLOSED || position == MAX_POSITION_EXCEEDED)
    {
        throw new NotConnectedException(position);
    }
    else
    {
        return position;
    }
}
 
Example #8
Source File: EmbeddedExclusiveBufferClaimIpcThroughput.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void run()
{
    final IdleStrategy idleStrategy = SampleConfiguration.newIdleStrategy();
    final AtomicBoolean running = this.running;
    final Publication publication = this.publication;
    final BufferClaim bufferClaim = new BufferClaim();
    long backPressureCount = 0;
    long totalMessageCount = 0;

    outputResults:
    while (running.get())
    {
        for (int i = 0; i < BURST_LENGTH; i++)
        {
            idleStrategy.reset();
            while (publication.tryClaim(MESSAGE_LENGTH, bufferClaim) <= 0)
            {
                ++backPressureCount;
                if (!running.get())
                {
                    break outputResults;
                }
                idleStrategy.idle();
            }

            final int offset = bufferClaim.offset();
            bufferClaim.buffer().putInt(offset, i); // Example field write
            // Real app would write whatever fields are required via a flyweight like SBE

            bufferClaim.commit();

            ++totalMessageCount;
        }
    }

    final double backPressureRatio = backPressureCount / (double)totalMessageCount;
    System.out.format("Publisher back pressure ratio: %f%n", backPressureRatio);
}
 
Example #9
Source File: FileSender.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static void sendChunk(
    final Publication publication,
    final BufferClaim bufferClaim,
    final long correlationId,
    final UnsafeBuffer fileBuffer,
    final int chunkOffset,
    final int chunkLength)
{
    long result;
    while ((result = publication.tryClaim(CHUNK_PAYLOAD_OFFSET + chunkLength, bufferClaim)) < 0)
    {
        checkResult(result);
        Thread.yield();
    }

    final MutableDirectBuffer buffer = bufferClaim.buffer();
    final int offset = bufferClaim.offset();

    buffer.putInt(offset + VERSION_OFFSET, VERSION, LITTLE_ENDIAN);
    buffer.putInt(offset + TYPE_OFFSET, FILE_CHUNK_TYPE, LITTLE_ENDIAN);
    buffer.putLong(offset + CORRELATION_ID_OFFSET, correlationId, LITTLE_ENDIAN);
    buffer.putLong(offset + CHUNK_OFFSET_OFFSET, chunkOffset, LITTLE_ENDIAN);
    buffer.putLong(offset + CHUNK_LENGTH_OFFSET, chunkLength, LITTLE_ENDIAN);
    buffer.putBytes(offset + CHUNK_PAYLOAD_OFFSET, fileBuffer, chunkOffset, chunkLength);

    bufferClaim.commit();
}
 
Example #10
Source File: FileSender.java    From aeron with Apache License 2.0 5 votes vote down vote up
private static void streamChunks(final Publication publication, final long correlationId, final UnsafeBuffer buffer)
{
    final BufferClaim bufferClaim = new BufferClaim();
    final int fileLength = buffer.capacity();
    final int maxChunkLength = publication.maxPayloadLength() - CHUNK_PAYLOAD_OFFSET;
    int chunkOffset = 0;

    while (chunkOffset < fileLength)
    {
        final int chunkLength = Math.min(maxChunkLength, fileLength - chunkOffset);
        sendChunk(publication, bufferClaim, correlationId, buffer, chunkOffset, chunkLength);
        chunkOffset += chunkLength;
    }
}
 
Example #11
Source File: PublicationTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldEnsureThePublicationIsOpenBeforeClaim()
{
    publication.close();
    final BufferClaim bufferClaim = new BufferClaim();
    assertEquals(Publication.CLOSED, publication.tryClaim(SEND_BUFFER_CAPACITY, bufferClaim));
}
 
Example #12
Source File: ClusterSession.java    From aeron with Apache License 2.0 5 votes vote down vote up
public long tryClaim(final int length, final BufferClaim bufferClaim)
{
    if (null == responsePublication)
    {
        return Publication.NOT_CONNECTED;
    }
    else
    {
        return responsePublication.tryClaim(length, bufferClaim);
    }
}
 
Example #13
Source File: ConsensusModuleProxy.java    From aeron with Apache License 2.0 5 votes vote down vote up
public long tryClaim(final int length, final BufferClaim bufferClaim, final DirectBuffer sessionHeader)
{
    final long result = publication.tryClaim(length, bufferClaim);
    if (result > 0)
    {
        bufferClaim.putBytes(sessionHeader, 0, AeronCluster.SESSION_HEADER_LENGTH);
    }

    return result;
}
 
Example #14
Source File: ClusteredServiceAgent.java    From aeron with Apache License 2.0 5 votes vote down vote up
long tryClaim(
    final long clusterSessionId,
    final Publication publication,
    final int length,
    final BufferClaim bufferClaim)
{
    if (role != Cluster.Role.LEADER)
    {
        final int maxPayloadLength = headerBuffer.capacity() - SESSION_HEADER_LENGTH;
        if (length > maxPayloadLength)
        {
            throw new IllegalArgumentException(
                "claim exceeds maxPayloadLength of " + maxPayloadLength + ", length=" + length);
        }

        bufferClaim.wrap(headerBuffer, 0, length + SESSION_HEADER_LENGTH);
        return ClientSession.MOCKED_OFFER;
    }

    if (null == publication)
    {
        return Publication.NOT_CONNECTED;
    }

    final long offset = publication.tryClaim(length + SESSION_HEADER_LENGTH, bufferClaim);
    if (offset > 0)
    {
        sessionMessageHeaderEncoder
            .clusterSessionId(clusterSessionId)
            .timestamp(clusterTime);

        bufferClaim.putBytes(headerBuffer, 0, SESSION_HEADER_LENGTH);
    }

    return offset;
}
 
Example #15
Source File: BufferClaimMessageTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@ParameterizedTest
@MethodSource("channels")
@Timeout(10)
public void shouldTransferReservedValue(final String channel)
{
    final BufferClaim bufferClaim = new BufferClaim();

    try (Subscription subscription = aeron.addSubscription(channel, STREAM_ID);
        Publication publication = aeron.addPublication(channel, STREAM_ID))
    {
        while (publication.tryClaim(MESSAGE_LENGTH, bufferClaim) < 0L)
        {
            Tests.yield();
        }

        final long reservedValue = System.currentTimeMillis();
        bufferClaim.reservedValue(reservedValue);
        bufferClaim.commit();

        final MutableBoolean done = new MutableBoolean();
        while (!done.get())
        {
            final int fragments = subscription.poll(
                (buffer, offset, length, header) ->
                {
                    assertEquals(MESSAGE_LENGTH, length);
                    assertEquals(reservedValue, header.reservedValue());

                    done.value = true;
                },
                FRAGMENT_COUNT_LIMIT);

            if (0 == fragments)
            {
                Tests.yield();
            }
        }
    }
}
 
Example #16
Source File: ReplaySessionTest.java    From aeron with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldThrowArchiveExceptionIfCrcFails()
{
    final long length = 4 * FRAME_LENGTH;
    final long correlationId = 1L;

    final Checksum checksum = crc32();
    try (ReplaySession replaySession = replaySession(
        RECORDING_POSITION + 2 * FRAME_LENGTH,
        length,
        correlationId,
        mockReplayPub,
        mockControlSession,
        null,
        checksum))
    {
        when(mockReplayPub.isClosed()).thenReturn(false);
        when(mockReplayPub.isConnected()).thenReturn(false);

        replaySession.doWork();
        assertEquals(ReplaySession.State.INIT, replaySession.state());

        when(mockReplayPub.isConnected()).thenReturn(true);

        final ArchiveException exception = assertThrows(ArchiveException.class, replaySession::doWork);
        assertEquals(ArchiveException.GENERIC, exception.errorCode());
        assertThat(exception.getMessage(), Matchers.startsWith("CRC checksum mismatch at offset=0"));
        verify(mockReplayPub, never()).tryClaim(anyInt(), any(BufferClaim.class));
    }
}
 
Example #17
Source File: AeronUtil.java    From benchmarks with Apache License 2.0 5 votes vote down vote up
static void pipeMessages(
    final Subscription subscription, final ExclusivePublication publication, final AtomicBoolean running)
{
    final IdleStrategy idleStrategy = idleStrategy();
    final BufferClaim bufferClaim = new BufferClaim();
    final FragmentHandler dataHandler =
        (buffer, offset, length, header) ->
        {
            long result;
            while ((result = publication.tryClaim(length, bufferClaim)) <= 0)
            {
                checkPublicationResult(result);
            }

            bufferClaim
                .flags(header.flags())
                .putBytes(buffer, offset, length)
                .commit();
        };

    final Image image = subscription.imageAtIndex(0);
    final int fragmentLimit = fragmentLimit();

    while (true)
    {
        final int fragmentsRead = image.poll(dataHandler, fragmentLimit);
        if (0 == fragmentsRead)
        {
            if (image.isClosed() || !running.get())
            {
                break;
            }
        }

        idleStrategy.idle(fragmentsRead);
    }
}
 
Example #18
Source File: ILink3Proxy.java    From artio with Apache License 2.0 5 votes vote down vote up
public long claimILinkMessage(
    final int messageLength,
    final MessageEncoderFlyweight message)
{
    final BufferClaim bufferClaim = this.bufferClaim;
    final long position = publication.tryClaim(ILINK_MESSAGE_HEADER + messageLength, bufferClaim);
    if (position < 0)
    {
        return position;
    }

    final MutableDirectBuffer buffer = bufferClaim.buffer();
    int offset = bufferClaim.offset();

    iLinkMessage
        .wrapAndApplyHeader(buffer, offset, messageHeader)
        .connection(connectionId);

    offset += ARTIO_HEADER_LENGTH;

    writeSofh(buffer, offset, ILINK_HEADER_LENGTH + messageLength);
    offset += SOFH_LENGTH;

    iLinkMessageHeader
        .wrap(buffer, offset)
        .blockLength(message.sbeBlockLength())
        .templateId(message.sbeTemplateId())
        .schemaId(message.sbeSchemaId())
        .version(message.sbeSchemaVersion());

    offset += iLinkMessageHeader.encodedLength();

    message.wrap(buffer, offset);

    return position;
}
 
Example #19
Source File: ClusteredServiceAgent.java    From aeron with Apache License 2.0 4 votes vote down vote up
public long tryClaim(final int length, final BufferClaim bufferClaim)
{
    sessionMessageHeaderEncoder.clusterSessionId(0);

    return consensusModuleProxy.tryClaim(length + SESSION_HEADER_LENGTH, bufferClaim, headerBuffer);
}
 
Example #20
Source File: BufferClaimMessageTest.java    From aeron with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("channels")
@Timeout(10)
public void shouldReceivePublishedMessageWithInterleavedAbort(final String channel)
{
    final MutableInteger fragmentCount = new MutableInteger();
    final FragmentHandler fragmentHandler = (buffer, offset, length, header) -> fragmentCount.value++;

    final BufferClaim bufferClaim = new BufferClaim();
    final UnsafeBuffer srcBuffer = new UnsafeBuffer(ByteBuffer.allocate(MESSAGE_LENGTH));

    try (Subscription subscription = aeron.addSubscription(channel, STREAM_ID);
        Publication publication = aeron.addPublication(channel, STREAM_ID))
    {
        publishMessage(srcBuffer, publication);

        while (publication.tryClaim(MESSAGE_LENGTH, bufferClaim) < 0L)
        {
            Tests.yield();
        }

        publishMessage(srcBuffer, publication);

        bufferClaim.abort();

        final int expectedNumberOfFragments = 2;
        int numFragments = 0;
        do
        {
            final int fragments = subscription.poll(fragmentHandler, FRAGMENT_COUNT_LIMIT);
            if (0 == fragments)
            {
                Tests.yield();
            }

            numFragments += fragments;
        }
        while (numFragments < expectedNumberOfFragments);

        assertEquals(expectedNumberOfFragments, fragmentCount.value);
    }
}
 
Example #21
Source File: ExclusivePublication.java    From aeron with Apache License 2.0 4 votes vote down vote up
/**
 * Try to claim a range in the publication log into which a message can be written with zero copy semantics.
 * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it
 * available.
 * <p>
 * <b>Note:</b> This method can only be used for message lengths less than MTU length minus header.
 * If the claim is held after the publication is closed, or the client dies, then it will be unblocked to reach
 * end-of-stream (EOS).
 * <pre>{@code
 *     final BufferClaim bufferClaim = new BufferClaim();
 *
 *     if (publication.tryClaim(messageLength, bufferClaim) > 0L)
 *     {
 *         try
 *         {
 *              final MutableDirectBuffer buffer = bufferClaim.buffer();
 *              final int offset = bufferClaim.offset();
 *
 *              // Work with buffer directly or wrap with a flyweight
 *         }
 *         finally
 *         {
 *             bufferClaim.commit();
 *         }
 *     }
 * }</pre>
 *
 * @param length      of the range to claim, in bytes..
 * @param bufferClaim to be populated if the claim succeeds.
 * @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
 * {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
 * @throws IllegalArgumentException if the length is greater than {@link #maxPayloadLength()} within an MTU.
 * @see BufferClaim#commit()
 * @see BufferClaim#abort()
 */
public long tryClaim(final int length, final BufferClaim bufferClaim)
{
    checkPayloadLength(length);
    long newPosition = CLOSED;

    if (!isClosed)
    {
        final long limit = positionLimit.getVolatile();
        final ExclusiveTermAppender termAppender = termAppenders[activePartitionIndex];
        final long position = termBeginPosition + termOffset;

        if (position < limit)
        {
            final int result = termAppender.claim(termId, termOffset, headerWriter, length, bufferClaim);
            newPosition = newPosition(result);
        }
        else
        {
            newPosition = backPressureStatus(position, length);
        }
    }

    return newPosition;
}
 
Example #22
Source File: Replayer.java    From artio with Apache License 2.0 4 votes vote down vote up
public Replayer(
    final ReplayQuery outboundReplayQuery,
    final ExclusivePublication publication,
    final BufferClaim bufferClaim,
    final IdleStrategy idleStrategy,
    final ErrorHandler errorHandler,
    final int maxClaimAttempts,
    final Subscription inboundSubscription,
    final String agentNamePrefix,
    final EpochClock clock,
    final Set<String> gapfillOnReplayMessageTypes,
    final ReplayHandler replayHandler,
    final SenderSequenceNumbers senderSequenceNumbers,
    final FixSessionCodecsFactory fixSessionCodecsFactory,
    final int maxBytesInBuffer,
    final ReplayerCommandQueue replayerCommandQueue,
    final EpochFractionFormat epochFractionFormat,
    final AtomicCounter currentReplayCount,
    final int maxConcurrentSessionReplays)
{
    this.outboundReplayQuery = outboundReplayQuery;
    this.publication = publication;
    this.bufferClaim = bufferClaim;
    this.idleStrategy = idleStrategy;
    this.errorHandler = errorHandler;
    this.maxClaimAttempts = maxClaimAttempts;
    this.inboundSubscription = inboundSubscription;
    this.agentNamePrefix = agentNamePrefix;
    this.clock = clock;
    this.replayHandler = replayHandler;
    this.senderSequenceNumbers = senderSequenceNumbers;
    this.fixSessionCodecsFactory = fixSessionCodecsFactory;
    this.maxBytesInBuffer = maxBytesInBuffer;
    this.replayerCommandQueue = replayerCommandQueue;
    this.currentReplayCount = currentReplayCount;
    this.maxConcurrentSessionReplays = maxConcurrentSessionReplays;

    gapFillMessageTypes = new LongHashSet();
    gapfillOnReplayMessageTypes.forEach(messageTypeAsString ->
        gapFillMessageTypes.add(GenerationUtil.packMessageType(messageTypeAsString)));
    utcTimestampEncoder = new UtcTimestampEncoder(epochFractionFormat);
}
 
Example #23
Source File: FixReplayerSession.java    From artio with Apache License 2.0 4 votes vote down vote up
FixReplayerSession(
    final BufferClaim bufferClaim,
    final IdleStrategy idleStrategy,
    final ReplayHandler replayHandler,
    final int maxClaimAttempts,
    final LongHashSet gapFillMessageTypes,
    final ExclusivePublication publication,
    final EpochClock clock,
    final int beginSeqNo,
    final int endSeqNo,
    final long connectionId,
    final long sessionId,
    final int sequenceIndex,
    final ReplayQuery replayQuery,
    final String message,
    final ErrorHandler errorHandler,
    final GapFillEncoder gapFillEncoder,
    final Formatters formatters,
    final AtomicCounter bytesInBuffer,
    final int maxBytesInBuffer,
    final UtcTimestampEncoder utcTimestampEncoder)
{
    super(connectionId, bufferClaim, idleStrategy, maxClaimAttempts, publication, replayQuery, beginSeqNo, endSeqNo,
        sessionId, sequenceIndex);
    this.replayHandler = replayHandler;
    this.gapFillMessageTypes = gapFillMessageTypes;
    this.message = message;
    this.errorHandler = errorHandler;
    this.gapFillEncoder = gapFillEncoder;
    this.formatters = formatters;
    this.maxBytesInBuffer = maxBytesInBuffer;
    this.bytesInBuffer = bytesInBuffer;

    sequenceNumberExtractor = new SequenceNumberExtractor(errorHandler);

    lastSeqNo = beginSeqNo - 1;

    possDupEnabler = new PossDupEnabler(
        utcTimestampEncoder,
        bufferClaim,
        this::claimMessageBuffer,
        this::onPreCommit,
        this::onIllegalState,
        this::onException,
        clock,
        publication.maxPayloadLength(),
        LogTag.FIX_MESSAGE);

    state = State.REPLAYING;
}
 
Example #24
Source File: AeronCluster.java    From aeron with Apache License 2.0 3 votes vote down vote up
/**
 * Try to claim a range in the publication log into which a message can be written with zero copy semantics.
 * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it available.
 * <p>
 * On successful claim, the Cluster ingress header will be written to the start of the claimed buffer section.
 * Clients <b>MUST</b> write into the claimed buffer region at offset + {@link AeronCluster#SESSION_HEADER_LENGTH}.
 * <pre>{@code
 *     final DirectBuffer srcBuffer = acquireMessage();
 *
 *     if (aeronCluster.tryClaim(length, bufferClaim) > 0L)
 *     {
 *         try
 *         {
 *              final MutableDirectBuffer buffer = bufferClaim.buffer();
 *              final int offset = bufferClaim.offset();
 *              // ensure that data is written at the correct offset
 *              buffer.putBytes(offset + AeronCluster.SESSION_HEADER_LENGTH, srcBuffer, 0, length);
 *         }
 *         finally
 *         {
 *             bufferClaim.commit();
 *         }
 *     }
 * }</pre>
 *
 * @param length      of the range to claim in bytes. The additional bytes for the session header will be added.
 * @param bufferClaim to be populated if the claim succeeds.
 * @return The new stream position, otherwise a negative error value as specified in
 * {@link io.aeron.Publication#tryClaim(int, BufferClaim)}.
 * @throws IllegalArgumentException if the length is greater than {@link io.aeron.Publication#maxPayloadLength()}.
 * @see Publication#tryClaim(int, BufferClaim)
 * @see BufferClaim#commit()
 * @see BufferClaim#abort()
 */
public long tryClaim(final int length, final BufferClaim bufferClaim)
{
    final long offset = publication.tryClaim(length + SESSION_HEADER_LENGTH, bufferClaim);
    if (offset > 0)
    {
        bufferClaim.putBytes(headerBuffer, 0, SESSION_HEADER_LENGTH);
    }

    return offset;
}
 
Example #25
Source File: ClientSession.java    From aeron with Apache License 2.0 2 votes vote down vote up
/**
 * Try to claim a range in the publication log into which a message can be written with zero copy semantics.
 * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it available.
 * <p>
 * On successful claim, the Cluster egress header will be written to the start of the claimed buffer section.
 * Clients <b>MUST</b> write into the claimed buffer region at offset + {@link AeronCluster#SESSION_HEADER_LENGTH}.
 * <pre>{@code
 *     final DirectBuffer srcBuffer = acquireMessage();
 *
 *     if (session.tryClaim(length, bufferClaim) > 0L)
 *     {
 *         try
 *         {
 *              final MutableDirectBuffer buffer = bufferClaim.buffer();
 *              final int offset = bufferClaim.offset();
 *              // ensure that data is written at the correct offset
 *              buffer.putBytes(offset + AeronCluster.SESSION_HEADER_LENGTH, srcBuffer, 0, length);
 *         }
 *         finally
 *         {
 *             bufferClaim.commit();
 *         }
 *     }
 * }</pre>
 *
 * @param length      of the range to claim in bytes. The additional bytes for the session header will be added.
 * @param bufferClaim to be populated if the claim succeeds.
 * @return The new stream position, otherwise a negative error value as specified in
 *         {@link io.aeron.Publication#tryClaim(int, BufferClaim)} when in {@link Cluster.Role#LEADER},
 *         otherwise {@link #MOCKED_OFFER} when a follower.
 * @throws IllegalArgumentException if the length is greater than {@link io.aeron.Publication#maxPayloadLength()}.
 * @see Publication#tryClaim(int, BufferClaim)
 * @see BufferClaim#commit()
 * @see BufferClaim#abort()
 */
public long tryClaim(final int length, final BufferClaim bufferClaim)
{
    return clusteredServiceAgent.tryClaim(id, responsePublication, length, bufferClaim);
}
 
Example #26
Source File: Cluster.java    From aeron with Apache License 2.0 2 votes vote down vote up
/**
 * Try to claim a range in the publication log into which a message can be written with zero copy semantics.
 * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it available.
 * <p>
 * On successful claim, the Cluster session header will be written to the start of the claimed buffer section.
 * Clients <b>MUST</b> write into the claimed buffer region at offset + {@link AeronCluster#SESSION_HEADER_LENGTH}.
 * <pre>{@code
 *     final DirectBuffer srcBuffer = acquireMessage();
 *
 *     if (cluster.tryClaim(length, bufferClaim))
 *     {
 *         try
 *         {
 *              final MutableDirectBuffer buffer = bufferClaim.buffer();
 *              final int offset = bufferClaim.offset();
 *              // ensure that data is written at the correct offset
 *              buffer.putBytes(offset + AeronCluster.SESSION_HEADER_LENGTH, srcBuffer, 0, length);
 *         }
 *         finally
 *         {
 *             bufferClaim.commit();
 *         }
 *     }
 * }</pre>
 *
 * @param length      of the range to claim, in bytes.
 * @param bufferClaim to be populated if the claim succeeds.
 * @return positive value if successful.
 * @throws IllegalArgumentException if the length is greater than {@link io.aeron.Publication#maxPayloadLength()}.
 * @see io.aeron.Publication#tryClaim(int, BufferClaim)
 * @see BufferClaim#commit()
 * @see BufferClaim#abort()
 */
long tryClaim(int length, BufferClaim bufferClaim);
 
Example #27
Source File: Publication.java    From aeron with Apache License 2.0 2 votes vote down vote up
/**
 * Try to claim a range in the publication log into which a message can be written with zero copy semantics.
 * Once the message has been written then {@link BufferClaim#commit()} should be called thus making it available.
 * A claim length cannot be greater than {@link #maxPayloadLength()}.
 * <p>
 * <b>Note:</b> This method can only be used for message lengths less than MTU length minus header.
 * If the claim is held for more than the aeron.publication.unblock.timeout system property then the driver will
 * assume the publication thread is dead and will unblock the claim thus allowing other threads to make progress
 * for {@link ConcurrentPublication} and other claims to be sent to reach end-of-stream (EOS).
 * <pre>{@code
 *     final BufferClaim bufferClaim = new BufferClaim(); // Can be stored and reused to avoid allocation
 *
 *     if (publication.tryClaim(messageLength, bufferClaim) > 0L)
 *     {
 *         try
 *         {
 *              final MutableDirectBuffer buffer = bufferClaim.buffer();
 *              final int offset = bufferClaim.offset();
 *
 *              // Work with buffer directly or wrap with a flyweight
 *         }
 *         finally
 *         {
 *             bufferClaim.commit();
 *         }
 *     }
 * }</pre>
 *
 * @param length      of the range to claim, in bytes..
 * @param bufferClaim to be populated if the claim succeeds.
 * @return The new stream position, otherwise a negative error value of {@link #NOT_CONNECTED},
 * {@link #BACK_PRESSURED}, {@link #ADMIN_ACTION}, {@link #CLOSED}, or {@link #MAX_POSITION_EXCEEDED}.
 * @throws IllegalArgumentException if the length is greater than {@link #maxPayloadLength()} within an MTU.
 * @see BufferClaim#commit()
 * @see BufferClaim#abort()
 */
public abstract long tryClaim(int length, BufferClaim bufferClaim);