Java Code Examples for org.agrona.CloseHelper#close()

The following examples show how to use org.agrona.CloseHelper#close() . 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: ResetArchiveState.java    From artio with Apache License 2.0 6 votes vote down vote up
void resetState()
{
    if (configuration.logAnyMessages())
    {
        createArchiver();
        try
        {
            truncateArchive();
            backupState();
        }
        finally
        {
            CloseHelper.close(archive);
            CloseHelper.close(aeron);
        }
    }
}
 
Example 2
Source File: DynamicJoin.java    From aeron with Apache License 2.0 6 votes vote down vote up
private int snapshotLoad(final long nowNs)
{
    int workCount = 0;

    if (null == recoveryStateCounter)
    {
        recoveryStateCounter = consensusModuleAgent.loadSnapshotsForDynamicJoin();
        workCount++;
    }
    else if (consensusModuleAgent.pollForSnapshotLoadAck(recoveryStateCounter, nowNs))
    {
        CloseHelper.close(ctx.countedErrorHandler(), recoveryStateCounter);
        recoveryStateCounter = null;
        state(State.JOIN_CLUSTER);
        workCount++;
    }

    return workCount;
}
 
Example 3
Source File: HistogramLoggingTest.java    From artio with Apache License 2.0 5 votes vote down vote up
@After
public void tearDown()
{
    try
    {
        writer.onClose();
        CloseHelper.close(reader);
    }
    finally
    {
        file.delete();
    }
}
 
Example 4
Source File: DataTransportPoller.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void close()
{
    for (final ChannelAndTransport channelEndpoint : channelAndTransports)
    {
        final ReceiveChannelEndpoint receiveChannelEndpoint = channelEndpoint.channelEndpoint;
        receiveChannelEndpoint.closeMultiRcvDestination(this);
        CloseHelper.close(errorHandler, receiveChannelEndpoint);
    }

    super.close();
}
 
Example 5
Source File: RecordingWriter.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void close()
{
    if (!isClosed)
    {
        isClosed = true;
        CloseHelper.close(countedErrorHandler, recordingFileChannel);
    }
}
 
Example 6
Source File: ReplicationSession.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void close()
{
    final ArchiveConductor archiveConductor = controlSession.archiveConductor();
    final CountedErrorHandler countedErrorHandler = archiveConductor.context().countedErrorHandler();

    stopRecording(countedErrorHandler);
    stopReplaySession(countedErrorHandler);

    CloseHelper.close(countedErrorHandler, asyncConnect);
    CloseHelper.close(countedErrorHandler, srcArchive);
    archiveConductor.removeReplicationSession(this);
}
 
Example 7
Source File: RecordingSession.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void close()
{
    if (autoStop)
    {
        final Subscription subscription = image.subscription();
        CloseHelper.close(countedErrorHandler, subscription);
        controlSession.archiveConductor().removeRecordingSubscription(subscription.registrationId());
    }
    CloseHelper.close(countedErrorHandler, recordingWriter);
    CloseHelper.close(countedErrorHandler, position);
}
 
Example 8
Source File: DedicatedModeArchiveConductor.java    From aeron with Apache License 2.0 5 votes vote down vote up
protected void closeSessionWorkers()
{
    CloseHelper.close(errorHandler, recorderAgentRunner);
    CloseHelper.close(errorHandler, replayerAgentRunner);

    while (processCloseQueue() > 0 || !closeQueue.isEmpty())
    {
        Thread.yield();
        if (Thread.currentThread().isInterrupted())
        {
            break;
        }
    }
}
 
Example 9
Source File: EngineConfiguration.java    From artio with Apache License 2.0 5 votes vote down vote up
public void close()
{
    CloseHelper.close(sentSequenceNumberIndex);
    CloseHelper.close(receivedSequenceNumberIndex);
    CloseHelper.close(sessionIdBuffer);
    CloseHelper.close(iLink3IdBuffer);
}
 
Example 10
Source File: ArchiveMigration_1_2.java    From aeron with Apache License 2.0 5 votes vote down vote up
public void migrate(
    final PrintStream stream,
    final ArchiveMarkFile markFile,
    final Catalog catalog,
    final File archiveDir)
{
    final FileChannel migrationTimestampFile = MigrationUtils.createMigrationTimestampFile(
        archiveDir, markFile.decoder().version(), minimumVersion());

    catalog.forEach(
        (headerEncoder, headerDecoder, encoder, decoder) ->
        {
            final String version1Prefix = decoder.recordingId() + "-";
            final String version1Suffix = ".rec";
            String[] segmentFiles = archiveDir.list(
                (dir, filename) -> filename.startsWith(version1Prefix) && filename.endsWith(version1Suffix));

            if (null == segmentFiles)
            {
                segmentFiles = ArrayUtil.EMPTY_STRING_ARRAY;
            }

            migrateRecording(
                stream,
                archiveDir,
                segmentFiles,
                version1Prefix,
                version1Suffix,
                headerEncoder,
                headerDecoder,
                encoder,
                decoder);
        });

    markFile.encoder().version(minimumVersion());
    catalog.updateVersion(minimumVersion());

    CloseHelper.close(migrationTimestampFile);
}
 
Example 11
Source File: DefaultLibraryScheduler.java    From artio with Apache License 2.0 4 votes vote down vote up
public void close(final int libraryId)
{
    EngineScheduler.awaitRunnerStart(monitoringRunner);

    CloseHelper.close(monitoringRunner);
}
 
Example 12
Source File: ArchiveConductor.java    From aeron with Apache License 2.0 4 votes vote down vote up
private void extendRecordingSession(
    final ControlSession controlSession,
    final long correlationId,
    final long recordingId,
    final String strippedChannel,
    final String originalChannel,
    final Image image,
    final boolean autoStop)
{
    try
    {
        if (recordingSessionByIdMap.containsKey(recordingId))
        {
            final String msg = "cannot extend active recording for " + recordingId;
            controlSession.attemptErrorResponse(correlationId, ACTIVE_RECORDING, msg, controlResponseProxy);
            throw new ArchiveException(msg);
        }

        catalog.recordingSummary(recordingId, recordingSummary);
        validateImageForExtendRecording(correlationId, controlSession, image, recordingSummary);

        final Counter position = RecordingPos.allocate(
            aeron,
            counterMetadataBuffer,
            recordingId,
            image.sessionId(),
            image.subscription().streamId(),
            strippedChannel,
            image.sourceIdentity());

        position.setOrdered(image.joinPosition());

        final RecordingSession session = new RecordingSession(
            correlationId,
            recordingId,
            recordingSummary.startPosition,
            recordingSummary.segmentFileLength,
            originalChannel,
            recordingEventsProxy,
            image,
            position,
            archiveDirChannel,
            ctx,
            controlSession,
            ctx.recordChecksumBuffer(),
            ctx.recordChecksum(),
            autoStop);

        recordingSessionByIdMap.put(recordingId, session);
        catalog.extendRecording(recordingId, controlSession.sessionId(), correlationId, image.sessionId());
        recorder.addSession(session);

        controlSession.attemptSignal(
            correlationId,
            recordingId,
            image.subscription().registrationId(),
            image.joinPosition(),
            RecordingSignal.EXTEND);
    }
    catch (final Exception ex)
    {
        errorHandler.onError(ex);
        if (autoStop)
        {
            removeRecordingSubscription(image.subscription().registrationId());
            CloseHelper.close(errorHandler, image.subscription());
        }
    }
}
 
Example 13
Source File: SequenceNumberIndexWriter.java    From artio with Apache License 2.0 4 votes vote down vote up
public SequenceNumberIndexWriter(
    final AtomicBuffer inMemoryBuffer,
    final MappedFile indexFile,
    final ErrorHandler errorHandler,
    final int streamId,
    final RecordingIdLookup recordingIdLookup,
    final long indexFileStateFlushTimeoutInMs,
    final EpochClock clock,
    final String metaDataDir,
    final Long2LongHashMap connectionIdToILinkUuid)
{
    this.inMemoryBuffer = inMemoryBuffer;
    this.indexFile = indexFile;
    this.errorHandler = errorHandler;
    this.streamId = streamId;
    this.fileCapacity = indexFile.buffer().capacity();
    this.indexFileStateFlushTimeoutInMs = indexFileStateFlushTimeoutInMs;
    this.clock = clock;

    iLinkSequenceNumberExtractor = new ILinkSequenceNumberExtractor(
        connectionIdToILinkUuid, errorHandler,
        (seqNum, uuid, messageSize, endPosition, aeronSessionId) ->
        saveRecord(seqNum, uuid, endPosition, NO_REQUIRED_POSITION));

    final String indexFilePath = indexFile.file().getAbsolutePath();
    indexPath = indexFile.file().toPath();
    final File writeableFile = writableFile(indexFilePath);
    writablePath = writeableFile.toPath();
    passingPlacePath = passingFile(indexFilePath).toPath();
    writableFile = MappedFile.map(writeableFile, fileCapacity);
    sequenceNumberExtractor = new SequenceNumberExtractor(errorHandler);

    // TODO: Fsync parent directory
    indexedPositionsOffset = positionTableOffset(fileCapacity);
    checksumFramer = new ChecksumFramer(
        inMemoryBuffer, indexedPositionsOffset, errorHandler, 0, "SequenceNumberIndex");
    try
    {
        initialiseBuffer();
        positionWriter = new IndexedPositionWriter(
            positionsBuffer(inMemoryBuffer, indexedPositionsOffset),
            errorHandler,
            indexedPositionsOffset,
            "SequenceNumberIndex",
            recordingIdLookup);

        if (metaDataDir != null)
        {
            metaDataLocation = metaDataFile(metaDataDir);
            metaDataFile = openMetaDataFile(metaDataLocation);
        }
        else
        {
            metaDataLocation = null;
            metaDataFile = null;
        }
    }
    catch (final Exception e)
    {
        CloseHelper.close(writableFile);
        indexFile.close();
        throw e;
    }
}
 
Example 14
Source File: ClusterControlAdapter.java    From aeron with Apache License 2.0 4 votes vote down vote up
public void close()
{
    CloseHelper.close(subscription);
}
 
Example 15
Source File: ClusterMember.java    From aeron with Apache License 2.0 4 votes vote down vote up
/**
 * Close consensus publication and null out reference.
 *
 * @param errorHandler to capture errors during close.
 */
public void closePublication(final ErrorHandler errorHandler)
{
    CloseHelper.close(errorHandler, publication);
    publication = null;
}
 
Example 16
Source File: IndexedReplicatedRecording.java    From aeron with Apache License 2.0 4 votes vote down vote up
public void close()
{
    CloseHelper.close(publication);
}
 
Example 17
Source File: FixConnection.java    From artio with Apache License 2.0 4 votes vote down vote up
public void close()
{
    CloseHelper.close(socket);
}
 
Example 18
Source File: PersistentSequenceNumberResendRequestSystemTest.java    From artio with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldReplayMessageBeforeARestart()
{
    mediaDriver = TestFixtures.launchMediaDriver();

    // 1. setup a session
    launch(AUTOMATIC_INITIAL_SEQUENCE_NUMBER);

    // 2. exchange some messages
    sendOrder();

    final FixMessage executionReport =
        testSystem.awaitMessageOf(initiatingOtfAcceptor, EXECUTION_REPORT_MESSAGE_AS_STR);
    final int resendSeqNum = executionReport.messageSequenceNumber();

    assertInitiatingSequenceIndexIs(0);
    if (shutdownCleanly)
    {
        initiatingSession.startLogout();
        assertSessionsDisconnected();

        close();
    }
    else
    {
        CloseHelper.close(initiatingLibrary);
        CloseHelper.close(acceptingLibrary);
        CloseHelper.close(initiatingEngine);
        CloseHelper.close(acceptingEngine);
    }

    clearMessages();
    if (shutdownCleanly)
    {
        launchMediaDriverWithDirs();
    }

    // 4. login with low received sequence number in order to force a resend request from the server.
    launch(1);

    // 5. validate resent message
    final FixMessage resentExecutionReport =
        testSystem.awaitMessageOf(initiatingOtfAcceptor, EXECUTION_REPORT_MESSAGE_AS_STR);
    assertEquals(resendSeqNum, resentExecutionReport.messageSequenceNumber());
    assertEquals("Y", resentExecutionReport.possDup());

    sendResendRequest(1, 3, initiatingOtfAcceptor, initiatingSession);
    sendResendRequest(1, 3, initiatingOtfAcceptor, initiatingSession);

    assertEventuallyTrue(() -> "Failed to receive all the resends: " + initiatingOtfAcceptor.messages(),
        () ->
        {
            testSystem.poll();

            assertEquals(2, initiatingOtfAcceptor
                .receivedReplayGapFill(1, 2)
                .count());

            assertEquals(2, initiatingOtfAcceptor
                .receivedReplay(EXECUTION_REPORT_MESSAGE_AS_STR, resendSeqNum)
                .count());

            assertEquals(2, initiatingOtfAcceptor
                .receivedReplayGapFill(3, 4)
                .count());
        }, 5000);
}
 
Example 19
Source File: ReceiveDestinationTransport.java    From aeron with Apache License 2.0 4 votes vote down vote up
public void close()
{
    CloseHelper.close(localSocketAddressIndicator);
    super.close();
}
 
Example 20
Source File: AeronNDArrayResponder.java    From nd4j with Apache License 2.0 2 votes vote down vote up
/**
 * Closes this resource, relinquishing any underlying resources.
 * This method is invoked automatically on objects managed by the
 * {@code try}-with-resources statement.
 * <p>
 * <p>While this interface method is declared to throw {@code
 * Exception}, implementers are <em>strongly</em> encouraged to
 * declare concrete implementations of the {@code close} method to
 * throw more specific exceptions, or to throw no exception at all
 * if the close operation cannot fail.
 * <p>
 * <p> Cases where the close operation may fail require careful
 * attention by implementers. It is strongly advised to relinquish
 * the underlying resources and to internally <em>mark</em> the
 * resource as closed, prior to throwing the exception. The {@code
 * close} method is unlikely to be invoked more than once and so
 * this ensures that the resources are released in a timely manner.
 * Furthermore it reduces problems that could arise when the resource
 * wraps, or is wrapped, by another resource.
 * <p>
 * <p><em>Implementers of this interface are also strongly advised
 * to not have the {@code close} method throw {@link
 * InterruptedException}.</em>
 * <p>
 * This exception interacts with a thread's interrupted status,
 * and runtime misbehavior is likely to occur if an {@code
 * InterruptedException} is {@linkplain Throwable#addSuppressed
 * suppressed}.
 * <p>
 * More generally, if it would cause problems for an
 * exception to be suppressed, the {@code AutoCloseable.close}
 * method should not throw it.
 * <p>
 * <p>Note that unlike the {@link Closeable#close close}
 * method of {@link Closeable}, this {@code close} method
 * is <em>not</em> required to be idempotent.  In other words,
 * calling this {@code close} method more than once may have some
 * visible side effect, unlike {@code Closeable.close} which is
 * required to have no effect if called more than once.
 * <p>
 * However, implementers of this interface are strongly encouraged
 * to make their {@code close} methods idempotent.
 *
 * @throws Exception if this resource cannot be closed
 */
@Override
public void close() throws Exception {
    CloseHelper.close(aeron);
}