Class Receiver<T>


  • public class Receiver<T>
    extends java.lang.Object
    A class for sending single messages between threads with timeout. Typical use would be
     Receiver<SomeMessage> receiver = new Receiver<SomeMessage>();
     SomeRunnable runnable = new SomeRunnable(receiver);
     Thread worker = new Thread(runnable);
     worker.start();
     Pair<Receiver.MessageState, SomeMessage> answer = receiver.get(500L);
     
    ... and in the worker thread simply
     receiver.put(new SomeMessage(...))
     

    Any number of threads may wait for the same message. Sending null references is supported. The object is intended for delivering only single message, there is no support for recycling it.

    Author:
    Steinar Knutsen
    • Nested Class Summary

      Nested Classes 
      Modifier and Type Class Description
      static class  Receiver.MessageState
      MessageState is the reason for returning from get().
    • Constructor Summary

      Constructors 
      Constructor Description
      Receiver()  
    • Method Summary

      All Methods Instance Methods Concrete Methods 
      Modifier and Type Method Description
      Tuple2<Receiver.MessageState,​T> get​(long timeout)
      Wait for up to "timeout" milliseconds for an incoming message.
      void put​(T message)
      Make a message available for consumers.
      • Methods inherited from class java.lang.Object

        clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
    • Constructor Detail

      • Receiver

        public Receiver()
    • Method Detail

      • put

        public void put​(T message)
        Make a message available for consumers.
        Parameters:
        message - the message to send
        Throws:
        java.lang.IllegalStateException - if a message has already been received here
      • get

        public Tuple2<Receiver.MessageState,​T> get​(long timeout)
                                                  throws java.lang.InterruptedException
        Wait for up to "timeout" milliseconds for an incoming message. This hides spurious wakeup, but InterruptedException will be propagated.
        Parameters:
        timeout - maximum time to wait for message in milliseconds
        Returns:
        a Pair instance containing the reason for returning and the message possible received
        Throws:
        java.lang.InterruptedException - if the waiting thread is interrupted