org.agrona.concurrent.AtomicBuffer Java Examples

The following examples show how to use org.agrona.concurrent.AtomicBuffer. 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: 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 #2
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 #3
Source File: OneToOneRingBufferConcurrentTest.java    From agrona with Apache License 2.0 6 votes vote down vote up
public void run()
{
    final int length = SIZE_OF_INT + SIZE_OF_LONG;
    for (int i = 0; i < REPETITIONS; i++)
    {

        int index = -1;
        try
        {
            while (INSUFFICIENT_CAPACITY == (index = ringBuffer.tryClaim(MSG_TYPE_ID, length)))
            {
                Thread.yield();
            }

            final AtomicBuffer buffer = ringBuffer.buffer();
            buffer.putInt(index, i);
            buffer.putLong(index + SIZE_OF_INT, i * 20L);
        }
        finally
        {
            ringBuffer.commit(index);
        }
    }
}
 
Example #4
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 #5
Source File: ManyToOneRingBuffer.java    From agrona with Apache License 2.0 6 votes vote down vote up
private static boolean scanBackToConfirmStillZeroed(final AtomicBuffer buffer, final int from, final int limit)
{
    int i = from - ALIGNMENT;
    boolean allZeros = true;
    while (i >= limit)
    {
        if (0 != buffer.getIntVolatile(i))
        {
            allZeros = false;
            break;
        }

        i -= ALIGNMENT;
    }

    return allZeros;
}
 
Example #6
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 #7
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 #8
Source File: ReadableCounter.java    From aeron with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a view of an existing counter.
 *
 * @param countersReader for getting access to the buffers.
 * @param registrationId assigned by the driver for the counter or {@link Aeron#NULL_VALUE} if not known.
 * @param counterId      for the counter to be viewed.
 * @throws IllegalStateException if the id has for the counter has not been allocated.
 */
public ReadableCounter(final CountersReader countersReader, final long registrationId, final int counterId)
{
    final int counterState = countersReader.getCounterState(counterId);
    if (counterState != CountersReader.RECORD_ALLOCATED)
    {
        throw new IllegalStateException("Counter not allocated: id=" + counterId + " state=" + counterState);
    }

    this.countersReader = countersReader;
    this.counterId = counterId;
    this.registrationId = registrationId;

    final AtomicBuffer valuesBuffer = countersReader.valuesBuffer();
    final int counterOffset = CountersReader.counterOffset(counterId);
    valuesBuffer.boundsCheck(counterOffset, SIZE_OF_LONG);

    this.buffer = valuesBuffer.byteArray();
    this.addressOffset = valuesBuffer.addressOffset() + counterOffset;
}
 
Example #9
Source File: LossStat.java    From aeron with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args)
{
    final String aeronDirectoryName = getProperty(AERON_DIR_PROP_NAME, AERON_DIR_PROP_DEFAULT);
    final File lossReportFile = LossReportUtil.file(aeronDirectoryName);

    if (!lossReportFile.exists())
    {
        System.err.print("Loss report does not exist: " + lossReportFile);
        System.exit(1);
    }

    final MappedByteBuffer mappedByteBuffer = SamplesUtil.mapExistingFileReadOnly(lossReportFile);
    final AtomicBuffer buffer = new UnsafeBuffer(mappedByteBuffer);

    System.out.println(LossReportReader.LOSS_REPORT_CSV_HEADER);
    final int entriesRead = LossReportReader.read(buffer, LossReportReader.defaultEntryConsumer(System.out));
    System.out.println(entriesRead + " loss entries");
}
 
Example #10
Source File: DistinctErrorLogTestWatcher.java    From aeron with Apache License 2.0 6 votes vote down vote up
public void captureErrors(final String aeronDirectoryName)
{
    final File cncFile = CommonContext.newCncFile(aeronDirectoryName);
    assertTrue(cncFile.exists());

    MappedByteBuffer cncByteBuffer = null;

    try (RandomAccessFile file = new RandomAccessFile(cncFile, "r");
        FileChannel channel = file.getChannel())
    {
        cncByteBuffer = channel.map(READ_ONLY, 0, channel.size());
        final AtomicBuffer errorLogBuffer = CommonContext.errorLogBuffer(cncByteBuffer);

        ErrorLogReader.read(errorLogBuffer, this::onObservation);
    }
    catch (final IOException ex)
    {
        ex.printStackTrace();
    }
    finally
    {
        IoUtil.unmap(cncByteBuffer);
    }
}
 
Example #11
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 #12
Source File: ManyToOneRingBuffer.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public boolean write(final int msgTypeId, final DirectBuffer srcBuffer, final int offset, 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 false;
    }

    buffer.putIntOrdered(lengthOffset(recordIndex), -recordLength);
    UnsafeAccess.UNSAFE.storeFence();

    buffer.putInt(typeOffset(recordIndex), msgTypeId);
    buffer.putBytes(encodedMsgOffset(recordIndex), srcBuffer, offset, length);
    buffer.putIntOrdered(lengthOffset(recordIndex), recordLength);

    return true;
}
 
Example #13
Source File: OneToOneRingBuffer.java    From agrona with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
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.putInt(typeOffset(recordIndex), msgTypeId);
    // Note: putInt is used to write negative length of the message since we are not yet publishing the message and
    // hence the order of writes of type field and negative length does not matter.
    // It is safe to do so, because the header was pre-zeroed during the capacity claim.
    buffer.putInt(lengthOffset(recordIndex), -recordLength);

    return encodedMsgOffset(recordIndex);
}
 
Example #14
Source File: ConcurrentCountersManager.java    From agrona with Apache License 2.0 5 votes vote down vote up
public ConcurrentCountersManager(
    final AtomicBuffer metaDataBuffer,
    final AtomicBuffer valuesBuffer,
    final Charset labelCharset,
    final EpochClock epochClock,
    final long freeToReuseTimeoutMs)
{
    super(metaDataBuffer, valuesBuffer, labelCharset, epochClock, freeToReuseTimeoutMs);
}
 
Example #15
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 #16
Source File: AtomicCounter.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Map a counter over a buffer. This version will free the counter on close.
 *
 * @param buffer          containing the counter.
 * @param counterId       identifier for the counter.
 * @param countersManager to be called to free the counter on close.
 */
public AtomicCounter(final AtomicBuffer buffer, final int counterId, final CountersManager countersManager)
{
    this.id = counterId;
    this.countersManager = countersManager;
    this.byteBuffer = buffer.byteBuffer();
    this.byteArray = buffer.byteArray();

    final int counterOffset = CountersManager.counterOffset(counterId);
    buffer.boundsCheck(counterOffset, SIZE_OF_LONG);
    this.addressOffset = buffer.addressOffset() + counterOffset;
}
 
Example #17
Source File: BufferAlignmentAgentTest.java    From agrona with Apache License 2.0 5 votes vote down vote up
private void testUnAlignedAtomicMethods(final AtomicBuffer buffer, final int offset)
{
    buffer.getLongVolatile(offset); // assert that buffer[offset] is 8-bytes
    // aligned

    assertUnaligned(offset + SIZE_OF_INT, buffer::getLongVolatile);
    assertUnaligned(offset + SIZE_OF_INT, (i) -> buffer.putLongVolatile(i, Long.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_INT, (i) -> buffer.compareAndSetLong(i, Long.MAX_VALUE, Long.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_INT, (i) -> buffer.getAndAddLong(i, Long.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_INT, (i) -> buffer.getAndSetLong(i, Long.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_INT, (i) -> buffer.putLongOrdered(i, Long.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_INT, (i) -> buffer.addLongOrdered(i, Long.MAX_VALUE));

    assertUnaligned(offset + SIZE_OF_SHORT, buffer::getIntVolatile);
    assertUnaligned(offset + SIZE_OF_SHORT, (i) -> buffer.putIntVolatile(i, Integer.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_SHORT,
        (i) -> buffer.compareAndSetInt(i, Integer.MAX_VALUE, Integer.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_SHORT, (i) -> buffer.getAndAddInt(i, Integer.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_SHORT, (i) -> buffer.getAndSetInt(i, Integer.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_SHORT, (i) -> buffer.putIntOrdered(i, Integer.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_SHORT, (i) -> buffer.addIntOrdered(i, Integer.MAX_VALUE));

    assertUnaligned(offset + SIZE_OF_BYTE, buffer::getShortVolatile);
    assertUnaligned(offset + SIZE_OF_BYTE, (i) -> buffer.putShortVolatile(i, Short.MAX_VALUE));
    assertUnaligned(offset + SIZE_OF_BYTE, buffer::getCharVolatile);
    assertUnaligned(offset + SIZE_OF_BYTE, (i) -> buffer.putCharVolatile(i, Character.MAX_VALUE));
}
 
Example #18
Source File: CountersReader.java    From agrona with Apache License 2.0 5 votes vote down vote up
private String labelValue(final AtomicBuffer metaDataBuffer, final int recordOffset)
{
    final int labelLength = metaDataBuffer.getIntVolatile(recordOffset + LABEL_OFFSET);
    final byte[] stringInBytes = new byte[labelLength];
    metaDataBuffer.getBytes(recordOffset + LABEL_OFFSET + SIZE_OF_INT, stringInBytes);

    return new String(stringInBytes, labelCharset);
}
 
Example #19
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 #20
Source File: BroadcastReceiver.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Non-blocking receive of next message from the transmission stream.
 * <p>
 * If loss has occurred then {@link #lappedCount()} will be incremented.
 *
 * @return true if transmission is available with {@link #offset()}, {@link #length()} and {@link #typeId()}
 * set for the next message to be consumed. If no transmission is available then false.
 */
public boolean receiveNext()
{
    boolean isAvailable = false;
    final AtomicBuffer buffer = this.buffer;
    final long tail = buffer.getLongVolatile(tailCounterIndex);
    long cursor = nextRecord;

    if (tail > cursor)
    {
        final int capacity = this.capacity;
        int recordOffset = (int)cursor & (capacity - 1);

        if (!validate(cursor, buffer, capacity))
        {
            lappedCount.lazySet(lappedCount.get() + 1);

            cursor = buffer.getLong(latestCounterIndex);
            recordOffset = (int)cursor & (capacity - 1);
        }

        this.cursor = cursor;
        nextRecord = cursor + align(buffer.getInt(lengthOffset(recordOffset)), RECORD_ALIGNMENT);

        if (PADDING_MSG_TYPE_ID == buffer.getInt(typeOffset(recordOffset)))
        {
            recordOffset = 0;
            this.cursor = nextRecord;
            nextRecord += align(buffer.getInt(lengthOffset(recordOffset)), RECORD_ALIGNMENT);
        }

        this.recordOffset = recordOffset;
        isAvailable = true;
    }

    return isAvailable;
}
 
Example #21
Source File: ErrorStat.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args)
{
    final File cncFile = CommonContext.newDefaultCncFile();
    System.out.println("Command `n Control file " + cncFile);

    final MappedByteBuffer cncByteBuffer = SamplesUtil.mapExistingFileReadOnly(cncFile);

    final AtomicBuffer buffer = CommonContext.errorLogBuffer(cncByteBuffer);
    final int distinctErrorCount = ErrorLogReader.read(buffer, ErrorStat::accept);

    System.out.format("%n%d distinct errors observed.%n", distinctErrorCount);
}
 
Example #22
Source File: SenderAndTargetSessionIdStrategyTest.java    From artio with Apache License 2.0 5 votes vote down vote up
@Test
public void savesAndLoadsACompositeKey()
{
    final AtomicBuffer buffer = new UnsafeBuffer(new byte[1024]);
    final CompositeKey key = strategy.onInitiateLogon("SIGMAX", null, null, "ABC_DEFG04", null, null);

    final int length = strategy.save(key, buffer, 1);

    assertThat(length, greaterThan(0));

    final Object loadedKey = strategy.load(buffer, 1, length);

    assertEquals(key, loadedKey);
}
 
Example #23
Source File: BroadcastTransmitter.java    From agrona with Apache License 2.0 5 votes vote down vote up
/**
 * Transmit a message to {@link BroadcastReceiver}s via the broadcast buffer.
 *
 * @param msgTypeId type of the message to be transmitted.
 * @param srcBuffer containing the encoded message to be transmitted.
 * @param srcIndex  srcIndex in the source buffer at which the encoded message begins.
 * @param length    in bytes of the encoded message.
 * @throws IllegalArgumentException of the msgTypeId is not valid,
 * or if the message length is greater than {@link #maxMsgLength()}.
 */
public void transmit(final int msgTypeId, final DirectBuffer srcBuffer, final int srcIndex, final int length)
{
    checkTypeId(msgTypeId);
    checkMessageLength(length);

    final AtomicBuffer buffer = this.buffer;
    long currentTail = buffer.getLong(tailCounterIndex);
    int recordOffset = (int)currentTail & (capacity - 1);
    final int recordLength = HEADER_LENGTH + length;
    final int recordLengthAligned = BitUtil.align(recordLength, RECORD_ALIGNMENT);
    final long newTail = currentTail + recordLengthAligned;

    final int toEndOfBuffer = capacity - recordOffset;
    if (toEndOfBuffer < recordLengthAligned)
    {
        signalTailIntent(buffer, newTail + toEndOfBuffer);
        insertPaddingRecord(buffer, recordOffset, toEndOfBuffer);

        currentTail += toEndOfBuffer;
        recordOffset = 0;
    }
    else
    {
        signalTailIntent(buffer, newTail);
    }

    buffer.putInt(lengthOffset(recordOffset), recordLength);
    buffer.putInt(typeOffset(recordOffset), msgTypeId);

    buffer.putBytes(msgOffset(recordOffset), srcBuffer, srcIndex, length);

    buffer.putLong(latestCounterIndex, currentTail);
    buffer.putLongOrdered(tailCounterIndex, currentTail + recordLengthAligned);
}
 
Example #24
Source File: Counter.java    From aeron with Apache License 2.0 5 votes vote down vote up
Counter(
    final long registrationId,
    final ClientConductor clientConductor,
    final AtomicBuffer buffer,
    final int counterId)
{
    super(buffer, counterId);

    this.registrationId = registrationId;
    this.clientConductor = clientConductor;
}
 
Example #25
Source File: LossReportTestUtil.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void verifyLossOccurredForStream(final String aeronDirectoryName, final int streamId)
    throws IOException
{
    final File lossReportFile = LossReportUtil.file(aeronDirectoryName);
    assertTrue(lossReportFile.exists());

    MappedByteBuffer mappedByteBuffer = null;

    try (RandomAccessFile file = new RandomAccessFile(lossReportFile, "r");
        FileChannel channel = file.getChannel())
    {
        mappedByteBuffer = channel.map(READ_ONLY, 0, channel.size());
        final AtomicBuffer buffer = new UnsafeBuffer(mappedByteBuffer);

        final LossReportReader.EntryConsumer lossEntryConsumer = mock(LossReportReader.EntryConsumer.class);
        LossReportReader.read(buffer, lossEntryConsumer);

        verify(lossEntryConsumer).accept(
            longThat((l) -> l > 0),
            longThat((l) -> l > 0),
            anyLong(),
            anyLong(),
            anyInt(),
            eq(streamId),
            any(),
            any());
    }
    finally
    {
        IoUtil.unmap(mappedByteBuffer);
    }
}
 
Example #26
Source File: SequenceNumberIndexTest.java    From artio with Apache License 2.0 5 votes vote down vote up
private SequenceNumberIndexWriter newWriter(final AtomicBuffer inMemoryBuffer)
{
    final MappedFile indexFile = newIndexFile();
    return new SequenceNumberIndexWriter(inMemoryBuffer, indexFile, errorHandler, STREAM_ID, recordingIdLookup,
        DEFAULT_INDEX_FILE_STATE_FLUSH_TIMEOUT_IN_MS, clock, null,
        new Long2LongHashMap(UNK_SESSION));
}
 
Example #27
Source File: SequenceNumberIndexTest.java    From artio with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldValidateBufferItReadsFrom()
{
    final AtomicBuffer tableBuffer = newBuffer();

    new SequenceNumberIndexReader(tableBuffer, errorHandler,
        recordingIdLookup,
        null);

    verify(errorHandler, times(1), IllegalStateException.class);
}
 
Example #28
Source File: ManyToOneRingBufferConcurrentTest.java    From agrona with Apache License 2.0 5 votes vote down vote up
public void run()
{
    try
    {
        barrier.await();
    }
    catch (final Exception ignore)
    {
    }

    final int length = SIZE_OF_INT * 2;
    for (int i = 0; i < reps; i++)
    {
        int index = -1;
        try
        {
            while (INSUFFICIENT_CAPACITY == (index = ringBuffer.tryClaim(MSG_TYPE_ID, length)))
            {
                Thread.yield();
            }

            final AtomicBuffer buffer = ringBuffer.buffer();
            buffer.putInt(index, producerId);
            buffer.putInt(index + SIZE_OF_INT, i);
        }
        finally
        {
            ringBuffer.commit(index);
        }
    }
}
 
Example #29
Source File: SenderAndTargetSessionIdStrategyTest.java    From artio with Apache License 2.0 5 votes vote down vote up
@Test
public void validatesSpaceInBufferOnSave()
{
    final AtomicBuffer buffer = new UnsafeBuffer(new byte[5]);
    final CompositeKey key = strategy.onInitiateLogon("SIGMAX", null, null, "ABC_DEFG04", null, null);

    final int length = strategy.save(key, buffer, 1);

    assertEquals(INSUFFICIENT_SPACE, length);
}
 
Example #30
Source File: ArchiveMarkFile.java    From aeron with Apache License 2.0 5 votes vote down vote up
public static void saveExistingErrors(final File markFile, final AtomicBuffer errorBuffer, final PrintStream logger)
{
    try
    {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final int observations = CommonContext.printErrorLog(errorBuffer, new PrintStream(baos, false, "US-ASCII"));
        if (observations > 0)
        {
            final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSSZ");
            final String errorLogFilename =
                markFile.getParent() + '-' + dateFormat.format(new Date()) + "-error.log";

            if (null != logger)
            {
                logger.println("WARNING: existing errors saved to: " + errorLogFilename);
            }

            try (FileOutputStream out = new FileOutputStream(errorLogFilename))
            {
                baos.writeTo(out);
            }
        }
    }
    catch (final Exception ex)
    {
        LangUtil.rethrowUnchecked(ex);
    }
}