Java Code Examples for org.agrona.concurrent.AtomicBuffer#capacity()

The following examples show how to use org.agrona.concurrent.AtomicBuffer#capacity() . 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: ManyToOneRingBuffer.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new {@link RingBuffer} based on an underlying {@link AtomicBuffer}.
 * The underlying buffer must a power of 2 in size plus sufficient space
 * for the {@link RingBufferDescriptor#TRAILER_LENGTH}.
 *
 * @param buffer via which events will be exchanged.
 * @throws IllegalStateException if the buffer capacity is not a power of 2
 *                               plus {@link RingBufferDescriptor#TRAILER_LENGTH} in capacity.
 */
public ManyToOneRingBuffer(final AtomicBuffer buffer)
{
    this.buffer = buffer;
    checkCapacity(buffer.capacity());
    capacity = buffer.capacity() - TRAILER_LENGTH;

    buffer.verifyAlignment();

    maxMsgLength = capacity >> 3;
    tailPositionIndex = capacity + TAIL_POSITION_OFFSET;
    headCachePositionIndex = capacity + HEAD_CACHE_POSITION_OFFSET;
    headPositionIndex = capacity + HEAD_POSITION_OFFSET;
    correlationIdCounterIndex = capacity + CORRELATION_COUNTER_OFFSET;
    consumerHeartbeatIndex = capacity + CONSUMER_HEARTBEAT_OFFSET;
}
 
Example 2
Source File: OneToOneRingBuffer.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new {@link RingBuffer} based on an underlying {@link AtomicBuffer}.
 * The underlying buffer must a power of 2 in size plus sufficient space
 * for the {@link RingBufferDescriptor#TRAILER_LENGTH}.
 *
 * @param buffer via which events will be exchanged.
 * @throws IllegalStateException if the buffer capacity is not a power of 2 plus
 *                               {@link RingBufferDescriptor#TRAILER_LENGTH} in capacity.
 */
public OneToOneRingBuffer(final AtomicBuffer buffer)
{
    this.buffer = buffer;
    checkCapacity(buffer.capacity());
    capacity = buffer.capacity() - TRAILER_LENGTH;

    buffer.verifyAlignment();

    maxMsgLength = capacity >> 3;
    tailPositionIndex = capacity + TAIL_POSITION_OFFSET;
    headCachePositionIndex = capacity + HEAD_CACHE_POSITION_OFFSET;
    headPositionIndex = capacity + HEAD_POSITION_OFFSET;
    correlationIdCounterIndex = capacity + CORRELATION_COUNTER_OFFSET;
    consumerHeartbeatIndex = capacity + CONSUMER_HEARTBEAT_OFFSET;
}
 
Example 3
Source File: CommonContext.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Print the contents of an error log to a {@link PrintStream} in human readable format.
 *
 * @param errorBuffer to read errors from.
 * @param out         print the errors to.
 * @return number of distinct errors observed.
 */
public static int printErrorLog(final AtomicBuffer errorBuffer, final PrintStream out)
{
    int distinctErrorCount = 0;

    if (errorBuffer.capacity() > 0 && ErrorLogReader.hasErrors(errorBuffer))
    {
        final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSZ");
        final ErrorConsumer errorConsumer = (count, firstTimestamp, lastTimestamp, ex) ->
            out.format(
            "***%n%d observations from %s to %s for:%n %s%n",
            count,
            dateFormat.format(new Date(firstTimestamp)),
            dateFormat.format(new Date(lastTimestamp)),
            ex);

        distinctErrorCount = ErrorLogReader.read(errorBuffer, errorConsumer);
        out.format("%n%d distinct errors observed.%n", distinctErrorCount);
    }

    return distinctErrorCount;
}
 
Example 4
Source File: CountersManager.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Create a new counter buffer manager over two buffers.
 *
 * @param metaDataBuffer       containing the types, keys, and labels for the counters.
 * @param valuesBuffer         containing the values of the counters themselves.
 * @param labelCharset         for the label encoding.
 * @param epochClock           to use for determining time for keep counter from being reused after being freed.
 * @param freeToReuseTimeoutMs timeout (in milliseconds) to keep counter from being reused after being freed.
 */
public CountersManager(
    final AtomicBuffer metaDataBuffer,
    final AtomicBuffer valuesBuffer,
    final Charset labelCharset,
    final EpochClock epochClock,
    final long freeToReuseTimeoutMs)
{
    super(metaDataBuffer, valuesBuffer, labelCharset);

    valuesBuffer.verifyAlignment();
    this.epochClock = epochClock;
    this.freeToReuseTimeoutMs = freeToReuseTimeoutMs;

    if (metaDataBuffer.capacity() < (valuesBuffer.capacity() * 2))
    {
        throw new IllegalArgumentException("metadata buffer not sufficiently large");
    }
}
 
Example 5
Source File: BroadcastReceiver.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new broadcast receiver based on an underlying {@link AtomicBuffer}.
 * The underlying buffer must a power of 2 in size plus sufficient space
 * for the {@link BroadcastBufferDescriptor#TRAILER_LENGTH}.
 *
 * @param buffer via which messages will be exchanged.
 * @throws IllegalStateException if the buffer capacity is not a power of 2
 * plus {@link BroadcastBufferDescriptor#TRAILER_LENGTH} in capacity.
 */
public BroadcastReceiver(final AtomicBuffer buffer)
{
    this.buffer = buffer;
    this.capacity = buffer.capacity() - TRAILER_LENGTH;

    checkCapacity(capacity);
    buffer.verifyAlignment();

    tailIntentCounterIndex = capacity + TAIL_INTENT_COUNTER_OFFSET;
    tailCounterIndex = capacity + TAIL_COUNTER_OFFSET;
    latestCounterIndex = capacity + LATEST_COUNTER_OFFSET;

    cursor = nextRecord = buffer.getLongVolatile(latestCounterIndex);
    recordOffset = (int)cursor & (capacity - 1);
}
 
Example 6
Source File: CountersReader.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Iterate over all the metadata in the buffer.
 *
 * @param metaData function to be called for each metadata record.
 */
public void forEach(final MetaData metaData)
{
    int counterId = 0;

    final AtomicBuffer metaDataBuffer = this.metaDataBuffer;

    for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH)
    {
        final int recordStatus = metaDataBuffer.getIntVolatile(i);
        if (RECORD_ALLOCATED == recordStatus)
        {
            final int typeId = metaDataBuffer.getInt(i + TYPE_ID_OFFSET);
            final String label = labelValue(metaDataBuffer, i);
            final DirectBuffer keyBuffer = new UnsafeBuffer(metaDataBuffer, i + KEY_OFFSET, MAX_KEY_LENGTH);

            metaData.accept(counterId, typeId, keyBuffer, label);
        }
        else if (RECORD_UNUSED == recordStatus)
        {
            break;
        }

        counterId++;
    }
}
 
Example 7
Source File: CountersReader.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Iterate over the counters and provide the value and basic metadata.
 *
 * @param consumer for each allocated counter.
 */
public void forEach(final CounterConsumer consumer)
{
    int counterId = 0;

    final AtomicBuffer metaDataBuffer = this.metaDataBuffer;
    final AtomicBuffer valuesBuffer = this.valuesBuffer;

    for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH)
    {
        final int recordStatus = metaDataBuffer.getIntVolatile(i);

        if (RECORD_ALLOCATED == recordStatus)
        {
            consumer.accept(
                valuesBuffer.getLongVolatile(counterOffset(counterId)), counterId, labelValue(metaDataBuffer, i));
        }
        else if (RECORD_UNUSED == recordStatus)
        {
            break;
        }

        counterId++;
    }
}
 
Example 8
Source File: CountersReader.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * Iterate over all labels in the label buffer.
 *
 * @param consumer function to be called for each label.
 */
public void forEach(final IntObjConsumer<String> consumer)
{
    int counterId = 0;

    final AtomicBuffer metaDataBuffer = this.metaDataBuffer;
    for (int i = 0, capacity = metaDataBuffer.capacity(); i < capacity; i += METADATA_LENGTH)
    {
        final int recordStatus = metaDataBuffer.getIntVolatile(i);

        if (RECORD_ALLOCATED == recordStatus)
        {
            consumer.accept(counterId, labelValue(metaDataBuffer, i));
        }
        else if (RECORD_UNUSED == recordStatus)
        {
            break;
        }

        counterId++;
    }
}
 
Example 9
Source File: ErrorLogReader.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Read all the errors in a log since a given timestamp.
 *
 * @param buffer         containing the {@link DistinctErrorLog}.
 * @param consumer       to be called for each exception encountered.
 * @param sinceTimestamp for filtering errors that have been recorded since this time.
 * @return the number of entries that has been read.
 */
public static int read(final AtomicBuffer buffer, final ErrorConsumer consumer, final long sinceTimestamp)
{
    int entries = 0;
    int offset = 0;
    final int capacity = buffer.capacity();

    while (offset < capacity)
    {
        final int length = buffer.getIntVolatile(offset + LENGTH_OFFSET);
        if (0 == length)
        {
            break;
        }

        final long lastObservationTimestamp = buffer.getLongVolatile(offset + LAST_OBSERVATION_TIMESTAMP_OFFSET);
        if (lastObservationTimestamp >= sinceTimestamp)
        {
            ++entries;

            consumer.accept(
                buffer.getInt(offset + OBSERVATION_COUNT_OFFSET),
                buffer.getLong(offset + FIRST_OBSERVATION_TIMESTAMP_OFFSET),
                lastObservationTimestamp,
                buffer.getStringWithoutLengthUtf8(offset + ENCODED_ERROR_OFFSET, length - ENCODED_ERROR_OFFSET));
        }

        offset += align(length, RECORD_ALIGNMENT);
    }

    return entries;
}
 
Example 10
Source File: CountersManager.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Create a new counter buffer manager over two buffers.
 *
 * @param metaDataBuffer containing the types, keys, and labels for the counters.
 * @param valuesBuffer   containing the values of the counters themselves.
 */
public CountersManager(final AtomicBuffer metaDataBuffer, final AtomicBuffer valuesBuffer)
{
    super(metaDataBuffer, valuesBuffer);

    valuesBuffer.verifyAlignment();
    this.epochClock = () -> 0;
    this.freeToReuseTimeoutMs = 0;

    if (metaDataBuffer.capacity() < (valuesBuffer.capacity() * 2))
    {
        throw new IllegalArgumentException("metadata buffer not sufficiently large");
    }
}
 
Example 11
Source File: CountersReader.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a reader over buffers containing the values and associated metadata.
 *
 * @param metaDataBuffer containing the counter metadata.
 * @param valuesBuffer   containing the counter values.
 * @param labelCharset   for the label encoding.
 */
public CountersReader(
    final AtomicBuffer metaDataBuffer, final AtomicBuffer valuesBuffer, final Charset labelCharset)
{
    this.maxCounterId = valuesBuffer.capacity() / COUNTER_LENGTH;
    this.valuesBuffer = valuesBuffer;
    this.metaDataBuffer = metaDataBuffer;
    this.labelCharset = labelCharset;
}
 
Example 12
Source File: BroadcastTransmitter.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new broadcast transmitter based on an underlying {@link org.agrona.concurrent.AtomicBuffer}.
 * The underlying buffer must a power of 2 in size plus sufficient space
 * for the {@link BroadcastBufferDescriptor#TRAILER_LENGTH}.
 *
 * @param buffer via which messages will be exchanged.
 * @throws IllegalStateException if the buffer capacity is not a power of 2
 * plus {@link BroadcastBufferDescriptor#TRAILER_LENGTH} in capacity.
 */
public BroadcastTransmitter(final AtomicBuffer buffer)
{
    this.buffer = buffer;
    this.capacity = buffer.capacity() - TRAILER_LENGTH;

    checkCapacity(capacity);
    buffer.verifyAlignment();

    this.maxMsgLength = calculateMaxMessageLength(capacity);
    this.tailIntentCountIndex = capacity + TAIL_INTENT_COUNTER_OFFSET;
    this.tailCounterIndex = capacity + TAIL_COUNTER_OFFSET;
    this.latestCounterIndex = capacity + LATEST_COUNTER_OFFSET;
}
 
Example 13
Source File: IndexedPositionReader.java    From artio with Apache License 2.0 5 votes vote down vote up
IndexedPositionReader(final AtomicBuffer buffer)
{
    this.buffer = buffer;
    final MessageHeaderDecoder messageHeader = new MessageHeaderDecoder();
    messageHeader.wrap(buffer, 0);
    actingBlockLength = messageHeader.blockLength();
    actingVersion = messageHeader.version();
    sectorFramer = new SectorFramer(buffer.capacity());
}
 
Example 14
Source File: LoggerUtil.java    From artio with Apache License 2.0 5 votes vote down vote up
public static boolean initialiseBuffer(
    final AtomicBuffer buffer,
    final MessageHeaderEncoder headerEncoder,
    final MessageHeaderDecoder headerDecoder,
    final int sbeSchemaId,
    final int sbeTemplateId,
    final int actingVersion,
    final int actingBlockLength,
    final ErrorHandler errorHandler)
{
    headerDecoder.wrap(buffer, 0);
    if (headerDecoder.blockLength() == 0)
    {
        writeHeader(buffer, headerEncoder, sbeSchemaId, sbeTemplateId, actingVersion, actingBlockLength);

        return true;
    }
    else
    {
        if (!validateBuffer(
            buffer,
            headerDecoder,
            sbeSchemaId,
            errorHandler))
        {
            writeHeader(
                buffer, headerEncoder, sbeSchemaId, sbeTemplateId, actingVersion, actingBlockLength);

            final int offset = headerEncoder.encodedLength();
            final int length = buffer.capacity() - offset;
            buffer.setMemory(
                offset,
                length,
                (byte)0);
        }

        return false;
    }
}
 
Example 15
Source File: IndexedPositionWriter.java    From artio with Apache License 2.0 5 votes vote down vote up
IndexedPositionWriter(
    final AtomicBuffer buffer,
    final ErrorHandler errorHandler,
    final int errorReportingOffset,
    final String fileName,
    final RecordingIdLookup recordingIdLookup)
{
    this.buffer = buffer;
    this.errorHandler = errorHandler;
    this.recordingIdLookup = recordingIdLookup;
    checksumFramer = new ChecksumFramer(
        buffer, buffer.capacity(), errorHandler, errorReportingOffset, fileName);
    setupHeader();
    initialiseOffsets();
}
 
Example 16
Source File: LossReportReader.java    From aeron with Apache License 2.0 4 votes vote down vote up
/**
 * Read a {@link LossReport} contained in the buffer. This can be done concurrently.
 *
 * @param buffer        containing the loss report.
 * @param entryConsumer to be called to accept each entry in the report.
 * @return the number of entries read.
 */
public static int read(final AtomicBuffer buffer, final EntryConsumer entryConsumer)
{
    final int capacity = buffer.capacity();

    int recordsRead = 0;
    int offset = 0;

    while (offset < capacity)
    {
        final long observationCount = buffer.getLongVolatile(offset + OBSERVATION_COUNT_OFFSET);
        if (observationCount <= 0)
        {
            break;
        }

        ++recordsRead;

        final String channel = buffer.getStringAscii(offset + CHANNEL_OFFSET);
        final String source = buffer.getStringAscii(
            offset + CHANNEL_OFFSET + BitUtil.align(SIZE_OF_INT + channel.length(), SIZE_OF_INT));

        entryConsumer.accept(
            observationCount,
            buffer.getLong(offset + TOTAL_BYTES_LOST_OFFSET),
            buffer.getLong(offset + FIRST_OBSERVATION_OFFSET),
            buffer.getLong(offset + LAST_OBSERVATION_OFFSET),
            buffer.getInt(offset + SESSION_ID_OFFSET),
            buffer.getInt(offset + STREAM_ID_OFFSET),
            channel,
            source);

        final int recordLength =
            CHANNEL_OFFSET +
            BitUtil.align(SIZE_OF_INT + channel.length(), SIZE_OF_INT) +
            SIZE_OF_INT + source.length();
        offset += BitUtil.align(recordLength, ENTRY_ALIGNMENT);
    }

    return recordsRead;
}
 
Example 17
Source File: SequenceNumberIndexDescriptor.java    From artio with Apache License 2.0 4 votes vote down vote up
static AtomicBuffer positionsBuffer(final AtomicBuffer buffer, final int positionsOffset)
{
    return new UnsafeBuffer(buffer, positionsOffset, buffer.capacity() - positionsOffset);
}
 
Example 18
Source File: ErrorLogReader.java    From agrona with Apache License 2.0 2 votes vote down vote up
/**
 * Has the error buffer any recorded errors?
 *
 * @param buffer containing the {@link DistinctErrorLog}.
 * @return true if there is at least one error.
 */
public static boolean hasErrors(final AtomicBuffer buffer)
{
    return buffer.capacity() > 0 && 0 != buffer.getIntVolatile(LENGTH_OFFSET);
}