Package io.aeron

Class Publication

java.lang.Object
io.aeron.Publication
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
ConcurrentPublication, ExclusivePublication

public abstract class Publication extends Object implements AutoCloseable
Aeron publisher API for sending messages to subscribers of a given channel and streamId pair. Publications are created via the Aeron.addPublication(String, int) Aeron.addExclusivePublication(String, int) methods, and messages are sent via one of the offer(DirectBuffer) methods.

The APIs used for tryClaim and offer are non-blocking.

Note: All methods are threadsafe except offer and tryClaim for the subclass ExclusivePublication. In the case of ConcurrentPublication all methods are threadsafe.

See Also:
  • Field Summary

    Fields
    Modifier and Type
    Field
    Description
    static final long
    The offer failed due to an administration action and should be retried.
    static final long
    The offer failed due to back pressure from the subscribers preventing further transmission.
    static final long
    The Publication has been closed and should no longer be used.
    static final long
    The offer failed due to reaching the maximum position of the stream given term buffer length times the total possible number of terms.
    static final long
    The publication is not connected to a subscriber, this can be an intermittent state as subscribers come and go.
  • Method Summary

    Modifier and Type
    Method
    Description
    void
    addDestination(String endpointChannel)
    Add a destination manually to a multi-destination-cast Publication.
    long
    asyncAddDestination(String endpointChannel)
    Asynchronously add a destination manually to a multi-destination-cast Publication.
    long
    asyncRemoveDestination(long destinationRegistrationId)
    Asynchronously remove a previously added destination from a multi-destination-cast Publication by registrationId.
    long
    asyncRemoveDestination(String endpointChannel)
    Asynchronously remove a previously added destination from a multi-destination-cast Publication.
    abstract long
    Available window for offering into a publication before the positionLimit() is reached.
    Media address for delivery to the channel.
    long
    Get the status of the media channel for this Publication.
    int
    Get the counter used to represent the channel status for this publication.
    void
    Remove resources used by this Publication when there are no more references.
    static String
    errorString(long position)
    Returns a string representation of a position.
    int
    The initial term id assigned when this Publication was created.
    boolean
    Has this object been closed and should no longer be used?
    boolean
    Has the Publication seen an active Subscriber recently?
    boolean
    Is this Publication the original instance added to the driver? If not then it was added after another client has already added the publication.
    Fetches the local socket address for this publication.
    int
    Maximum message length supported in bytes.
    int
    Maximum length of a message payload that fits within a message fragment.
    long
    The maximum possible position this stream can reach due to its term buffer length.
    final long
    Non-blocking publish by gathering buffer vectors into a message.
    abstract long
    offer(DirectBufferVector[] vectors, ReservedValueSupplier reservedValueSupplier)
    Non-blocking publish by gathering buffer vectors into a message.
    final long
    Non-blocking publish of a buffer containing a message.
    final long
    offer(DirectBuffer buffer, int offset, int length)
    Non-blocking publish of a partial buffer containing a message.
    abstract long
    offer(DirectBuffer buffer, int offset, int length, ReservedValueSupplier reservedValueSupplier)
    Non-blocking publish of a partial buffer containing a message.
    final long
    offer(DirectBuffer bufferOne, int offsetOne, int lengthOne, DirectBuffer bufferTwo, int offsetTwo, int lengthTwo)
    Non-blocking publish of a message composed of two parts, e.g.
    abstract long
    offer(DirectBuffer bufferOne, int offsetOne, int lengthOne, DirectBuffer bufferTwo, int offsetTwo, int lengthTwo, ReservedValueSupplier reservedValueSupplier)
    Non-blocking publish of a message composed of two parts, e.g.
    long
    Get the registration used to register this Publication with the media driver by the first publisher.
    long
    Get the current position to which the publication has advanced for this stream.
    int
    Number of bits to right shift a position to get a term count for how far the stream has progressed.
    long
    Get the position limit beyond which this Publication will be back pressured.
    int
    Get the counter id for the position limit after which the publication will be back pressured.
    long
    Get the registration id used to register this Publication with the media driver.
    void
    removeDestination(long registrationId)
    Remove a previously added destination manually from a multi-destination-cast Publication.
    void
    removeDestination(String endpointChannel)
    Remove a previously added destination manually from a multi-destination-cast Publication.
    int
    Session under which messages are published.
    int
    Stream identity for scoping within the channel media address.
    int
    Get the length in bytes for each term partition in the log buffer.
    abstract long
    tryClaim(int length, BufferClaim bufferClaim)
    Try to claim a range in the publication log into which a message can be written with zero copy semantics.

    Methods inherited from class java.lang.Object

    clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
  • Field Details

    • NOT_CONNECTED

      public static final long NOT_CONNECTED
      The publication is not connected to a subscriber, this can be an intermittent state as subscribers come and go.
      See Also:
    • BACK_PRESSURED

      public static final long BACK_PRESSURED
      The offer failed due to back pressure from the subscribers preventing further transmission.
      See Also:
    • ADMIN_ACTION

      public static final long ADMIN_ACTION
      The offer failed due to an administration action and should be retried. The action is an operation such as log rotation which is likely to have succeeded by the next retry attempt.
      See Also:
    • CLOSED

      public static final long CLOSED
      The Publication has been closed and should no longer be used.
      See Also:
    • MAX_POSITION_EXCEEDED

      public static final long MAX_POSITION_EXCEEDED
      The offer failed due to reaching the maximum position of the stream given term buffer length times the total possible number of terms.

      If this happens then the publication should be closed and a new one added. To make it less likely to happen then increase the term buffer length.

      See Also:
  • Method Details

    • positionBitsToShift

      public int positionBitsToShift()
      Number of bits to right shift a position to get a term count for how far the stream has progressed.
      Returns:
      of bits to right shift a position to get a term count for how far the stream has progressed.
    • termBufferLength

      public int termBufferLength()
      Get the length in bytes for each term partition in the log buffer.
      Returns:
      the length in bytes for each term partition in the log buffer.
    • maxPossiblePosition

      public long maxPossiblePosition()
      The maximum possible position this stream can reach due to its term buffer length.

      Maximum possible position is term-length times 2^31 in bytes.

      Returns:
      the maximum possible position this stream can reach due to it term buffer length.
    • channel

      public String channel()
      Media address for delivery to the channel.
      Returns:
      Media address for delivery to the channel.
    • streamId

      public int streamId()
      Stream identity for scoping within the channel media address.
      Returns:
      Stream identity for scoping within the channel media address.
    • sessionId

      public int sessionId()
      Session under which messages are published. Identifies this Publication instance. Sessions are unique across all active publications on a driver instance.
      Returns:
      the session id for this publication.
    • initialTermId

      public int initialTermId()
      The initial term id assigned when this Publication was created. This can be used to determine how many terms have passed since creation.
      Returns:
      the initial term id.
    • maxMessageLength

      public int maxMessageLength()
      Maximum message length supported in bytes. Messages may be made of multiple fragments if greater than MTU length.
      Returns:
      maximum message length supported in bytes.
    • maxPayloadLength

      public int maxPayloadLength()
      Maximum length of a message payload that fits within a message fragment.

      This is the MTU length minus the message fragment header length.

      Returns:
      maximum message fragment payload length.
    • originalRegistrationId

      public long originalRegistrationId()
      Get the registration used to register this Publication with the media driver by the first publisher.
      Returns:
      original registration id
    • isOriginal

      public boolean isOriginal()
      Is this Publication the original instance added to the driver? If not then it was added after another client has already added the publication.
      Returns:
      true if this instance is the first added otherwise false.
    • registrationId

      public long registrationId()
      Get the registration id used to register this Publication with the media driver.

      If this value is different from the originalRegistrationId() then a previous active registration exists.

      Returns:
      registration id
    • isConnected

      public boolean isConnected()
      Has the Publication seen an active Subscriber recently?
      Returns:
      true if this Publication has recently seen an active subscriber otherwise false.
    • close

      public void close()
      Remove resources used by this Publication when there are no more references.

      Publications are reference counted and are only truly closed when the ref count reaches zero.

      Specified by:
      close in interface AutoCloseable
    • isClosed

      public boolean isClosed()
      Has this object been closed and should no longer be used?
      Returns:
      true if it has been closed otherwise false.
    • channelStatus

      public long channelStatus()
      Get the status of the media channel for this Publication.

      The status will be ChannelEndpointStatus.ERRORED if a socket exception occurs on setup and ChannelEndpointStatus.ACTIVE if all is well.

      Returns:
      status for the channel as one of the constants from ChannelEndpointStatus with it being ChannelEndpointStatus.NO_ID_ALLOCATED if the publication is closed.
      See Also:
    • channelStatusId

      public int channelStatusId()
      Get the counter used to represent the channel status for this publication.
      Returns:
      the counter used to represent the channel status for this publication.
    • localSocketAddresses

      public List<String> localSocketAddresses()
      Fetches the local socket address for this publication. If the channel is not ChannelEndpointStatus.ACTIVE, then this will return an empty list.

      The format is as follows:

      IPv4: ip address:port
      IPv6: [ip6 address]:port

      This is to match the formatting used in the Aeron URI. For publications this will be the control address and is likely to only contain a single entry.

      Returns:
      local socket addresses for this publication.
      See Also:
    • position

      public long position()
      Get the current position to which the publication has advanced for this stream.
      Returns:
      the current position to which the publication has advanced for this stream or CLOSED.
    • positionLimit

      public long positionLimit()
      Get the position limit beyond which this Publication will be back pressured.

      This should only be used as a guide to determine when back pressure is likely to be applied.

      Returns:
      the position limit beyond which this Publication will be back pressured.
    • positionLimitId

      public int positionLimitId()
      Get the counter id for the position limit after which the publication will be back pressured.
      Returns:
      the counter id for the position limit after which the publication will be back pressured.
    • availableWindow

      public abstract long availableWindow()
      Available window for offering into a publication before the positionLimit() is reached.
      Returns:
      window for offering into a publication before the positionLimit() is reached. If the publication is closed then CLOSED will be returned.
    • offer

      public final long offer(DirectBuffer buffer)
      Non-blocking publish of a buffer containing a message.
      Parameters:
      buffer - containing message.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • offer

      public final long offer(DirectBuffer buffer, int offset, int length)
      Non-blocking publish of a partial buffer containing a message.
      Parameters:
      buffer - containing message.
      offset - offset in the buffer at which the encoded message begins.
      length - in bytes of the encoded message.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • offer

      public abstract long offer(DirectBuffer buffer, int offset, int length, ReservedValueSupplier reservedValueSupplier)
      Non-blocking publish of a partial buffer containing a message.
      Parameters:
      buffer - containing message.
      offset - offset in the buffer at which the encoded message begins.
      length - in bytes of the encoded message.
      reservedValueSupplier - ReservedValueSupplier for the frame.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • offer

      public final long offer(DirectBuffer bufferOne, int offsetOne, int lengthOne, DirectBuffer bufferTwo, int offsetTwo, int lengthTwo)
      Non-blocking publish of a message composed of two parts, e.g. a header and encapsulated payload.
      Parameters:
      bufferOne - containing the first part of the message.
      offsetOne - at which the first part of the message begins.
      lengthOne - of the first part of the message.
      bufferTwo - containing the second part of the message.
      offsetTwo - at which the second part of the message begins.
      lengthTwo - of the second part of the message.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • offer

      public abstract long offer(DirectBuffer bufferOne, int offsetOne, int lengthOne, DirectBuffer bufferTwo, int offsetTwo, int lengthTwo, ReservedValueSupplier reservedValueSupplier)
      Non-blocking publish of a message composed of two parts, e.g. a header and encapsulated payload.
      Parameters:
      bufferOne - containing the first part of the message.
      offsetOne - at which the first part of the message begins.
      lengthOne - of the first part of the message.
      bufferTwo - containing the second part of the message.
      offsetTwo - at which the second part of the message begins.
      lengthTwo - of the second part of the message.
      reservedValueSupplier - ReservedValueSupplier for the frame.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • offer

      public final long offer(DirectBufferVector[] vectors)
      Non-blocking publish by gathering buffer vectors into a message.
      Parameters:
      vectors - which make up the message.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • offer

      public abstract long offer(DirectBufferVector[] vectors, ReservedValueSupplier reservedValueSupplier)
      Non-blocking publish by gathering buffer vectors into a message.
      Parameters:
      vectors - which make up the message.
      reservedValueSupplier - ReservedValueSupplier for the frame.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
    • tryClaim

      public abstract long tryClaim(int length, BufferClaim bufferClaim)
      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 BufferClaim.commit() should be called thus making it available. A claim length cannot be greater than maxPayloadLength().

      Note: 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 ConcurrentPublication and other claims to be sent to reach end-of-stream (EOS).

      
           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();
               }
           }
       
      Parameters:
      length - of the range to claim, in bytes.
      bufferClaim - to be populated if the claim succeeds.
      Returns:
      The new stream position, otherwise a negative error value of NOT_CONNECTED, BACK_PRESSURED, ADMIN_ACTION, CLOSED, or MAX_POSITION_EXCEEDED.
      Throws:
      IllegalArgumentException - if the length is greater than maxPayloadLength() within an MTU.
      See Also:
    • addDestination

      public void addDestination(String endpointChannel)
      Add a destination manually to a multi-destination-cast Publication.
      Parameters:
      endpointChannel - for the destination to add.
    • removeDestination

      public void removeDestination(String endpointChannel)
      Remove a previously added destination manually from a multi-destination-cast Publication.
      Parameters:
      endpointChannel - for the destination to remove.
    • removeDestination

      public void removeDestination(long registrationId)
      Remove a previously added destination manually from a multi-destination-cast Publication.
      Parameters:
      registrationId - for the destination to remove.
    • asyncAddDestination

      public long asyncAddDestination(String endpointChannel)
      Asynchronously add a destination manually to a multi-destination-cast Publication.

      Errors will be delivered asynchronously to the Aeron.Context.errorHandler(). Completion can be tracked by passing the returned correlation id to Aeron.isCommandActive(long).

      Parameters:
      endpointChannel - for the destination to add.
      Returns:
      the correlationId for the command.
    • asyncRemoveDestination

      public long asyncRemoveDestination(String endpointChannel)
      Asynchronously remove a previously added destination from a multi-destination-cast Publication.

      Errors will be delivered asynchronously to the Aeron.Context.errorHandler(). Completion can be tracked by passing the returned correlation id to Aeron.isCommandActive(long).

      Parameters:
      endpointChannel - for the destination to remove.
      Returns:
      the correlationId for the command.
    • asyncRemoveDestination

      public long asyncRemoveDestination(long destinationRegistrationId)
      Asynchronously remove a previously added destination from a multi-destination-cast Publication by registrationId.

      Errors will be delivered asynchronously to the Aeron.Context.errorHandler(). Completion can be tracked by passing the returned correlation id to Aeron.isCommandActive(long).

      Parameters:
      destinationRegistrationId - for the destination to remove.
      Returns:
      the correlationId for the command.
    • errorString

      public static String errorString(long position)
      Returns a string representation of a position. Generally used for errors. If the position is a valid error then String name of the error will be returned. If the value is 0 or greater the text will be "NONE". If the position is negative, but not a known error code then "UNKNOWN" will be returned.
      Parameters:
      position - position value returned from a call to offer.
      Returns:
      String representation of the error.
    • toString

      public String toString()
      Overrides:
      toString in class Object