public int tryClaim(final int msgTypeId, final int length)
    {
        checkTypeId(msgTypeId);
        checkMsgLength(length);

        final AtomicBuffer buffer = this.buffer;
        final int recordLength = length + HEADER_LENGTH;
        final int recordIndex = claimCapacity(buffer, recordLength);

        if (INSUFFICIENT_CAPACITY == recordIndex)
        {
            return recordIndex;
        }

        buffer.putIntOrdered(lengthOffset(recordIndex), -recordLength);
        MemoryAccess.releaseFence();
        buffer.putInt(typeOffset(recordIndex), msgTypeId);

        return encodedMsgOffset(recordIndex);
    }
@Test
    void tryClaimReturnsIndexAtWhichEncodedMessageStarts()
    {
        final int length = 10;
        final int recordLength = length + HEADER_LENGTH;
        final int alignedRecordLength = align(recordLength, ALIGNMENT);
        final long headPosition = 248L;
        final long tailPosition = 320L;
        final int recordIndex = (int)tailPosition;
        when(buffer.getLongVolatile(HEAD_COUNTER_CACHE_INDEX)).thenReturn(headPosition);
        when(buffer.getLongVolatile(TAIL_COUNTER_INDEX)).thenReturn(tailPosition);
        when(buffer.compareAndSetLong(TAIL_COUNTER_INDEX, tailPosition, tailPosition + alignedRecordLength))
            .thenReturn(TRUE);

        final int index = ringBuffer.tryClaim(MSG_TYPE_ID, length);

        assertEquals(recordIndex + HEADER_LENGTH, index);

        final InOrder inOrder = inOrder(buffer);
        inOrder.verify(buffer).getLongVolatile(HEAD_COUNTER_CACHE_INDEX);
        inOrder.verify(buffer).getLongVolatile(TAIL_COUNTER_INDEX);
        inOrder.verify(buffer).compareAndSetLong(TAIL_COUNTER_INDEX, tailPosition, tailPosition + alignedRecordLength);
        inOrder.verify(buffer).putIntOrdered(lengthOffset(recordIndex), -recordLength);
        inOrder.verify(buffer).putInt(typeOffset(recordIndex), MSG_TYPE_ID);
        inOrder.verifyNoMoreInteractions();
    }