Class Actor<SELF extends Actor>

java.lang.Object
org.nustaq.kontraktor.Actors
org.nustaq.kontraktor.Actor<SELF>
All Implemented Interfaces:
Serializable, Executor, Monitorable
Direct Known Subclasses:
_AsyncClientSocket.CLSActor, AbstractKrouter, Log, TCPClientConnector.RemotingHelper

public class Actor<SELF extends Actor> extends Actors implements Serializable, Monitorable, Executor
Baseclass for actor/eventloop implementations. Note that actors are not created using constructors. Use Actors.AsActor(..) to instantiate an actor instance. Example (public methods are automatically transformed to be async):
 public class MyActor extends Actor {

     // public async API
     public IPromise init() {..}
     public void asyncMessage(String arg) { .. }
     public IPromise asyncMessage(String arg) { .. }
     public void asyncMessage(int arg, Callback aCallback) { .. }

     // synchronous methods (safe as cannot be called by foreign threads)
     protected String syncMethod() { .. }
 }

 MyActor act = Actors.AsActor(MyActor.class);
 act.init().then( () -> { System.out.println("done"); }
 Object res = act.asyncMessage("Hello").await();

 
Note that unlike in other actor libraries, processing of Callback and Promise is transfered to the current actor thread, so its safe to close over actor state.
See Also:
  • Field Details

    • sender

      public static ThreadLocal<Actor> sender
      contains sender of a message if one actor messages to another actor
    • connection

      public static ThreadLocal<ConnectionRegistry> connection
      contains remote connection if current message came from remote
    • userData

      public Object userData
      free for outer mechanics to use.
    • __mailbox

      public Queue __mailbox
    • __mbCapacity

      public int __mbCapacity
    • __cbQueue

      public Queue __cbQueue
    • __currentDispatcher

      public Thread __currentDispatcher
    • __scheduler

      public Scheduler __scheduler
    • __stopped

      public volatile boolean __stopped
    • __self

      public Actor __self
    • __remoteId

      public long __remoteId
    • __connections

      public volatile ConcurrentLinkedQueue<ConnectionRegistry> __connections
    • __clientConnection

      public ConnectionRegistry __clientConnection
    • zzRoutingGCEnabled

      public boolean zzRoutingGCEnabled
    • __mailboxCapacity

      public int __mailboxCapacity
    • __ticketMachine

      protected TicketMachine __ticketMachine
    • zzServerMsgCallback

      public Callback<RemoteCallEntry> zzServerMsgCallback
    • __publishTarget

      public Actor __publishTarget
  • Constructor Details

    • Actor

      public Actor()
      required by bytecode magic. Use Actors.AsActor(..) to construct actor instances
  • Method Details

    • current

      public static Actor current()
      Returns:
      current actor or throw an exception if not running inside an actor thread.
    • inside

      public static boolean inside()
    • __submit

      public void __submit(Runnable toRun)
    • self

      protected SELF self()
      use this to call public methods using actor-dispatch instead of direct in-thread call. Important: When passing references out of your actor, always pass 'self()' instead of this !
      Returns:
    • getFactory

      public ActorProxyFactory getFactory()
    • getActor

      public SELF getActor()
      Returns:
      if this is an actorproxy, return the underlying actor instance, else return this Note: gets patched during proxy generation to guarantee correctness.
    • stop

      public void stop()
      stop receiving events. If there are no actors left on the underlying dispatcher, the dispatching thread will be terminated.
    • isStopped

      public boolean isStopped()
      synchronous method returning true in case this actor is stopped
    • isProxy

      public boolean isProxy()
      Returns:
      wether this is the "real" implementation or the proxy object
    • askMsg

      public IPromise askMsg(String messageId, Object... args)
      generic method for untyped messages.
      Parameters:
      messageId -
      Returns:
    • tellMsg

      public void tellMsg(String messageId, Object... args)
      generic method for untyped messages.
      Parameters:
      messageId -
    • ask

      public IPromise ask(String messageId, Object... args)
      generic method for untyped remoting.
      Parameters:
      messageId -
      Returns:
    • tell

      public void tell(String messageId, Object... args)
      generic method for untyped remoting.
      Parameters:
      messageId -
    • execInThreadPool

      public <T> IPromise<T> execInThreadPool(Callable<T> callable)
      execute a callable asynchronously (in a different thread) and return a future of the result (delivered in caller thread). Can be used to isolate blocking operations WARNING: do not access local actor state (instance fields) from within the callable (=hidden parallelism). WARNING: a similar named method execute() works different (bad naming)
      Type Parameters:
      T -
      Parameters:
      callable -
      Returns:
    • cyclic

      public void cyclic(long interval, Callable<Boolean> toRun)
    • debounce

      public void debounce(long timeout, String tag, Runnable toRun)
    • delayed

      public void delayed(long millis, Runnable toRun)
      schedule an action or call delayed. typical use case: delayed( 100, () -> { self().doAction( x, y, ); } );
    • isMailboxPressured

      public boolean isMailboxPressured()
      WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.
      Returns:
      true if mailbox fill size is ~half capacity
    • isEmpty

      public boolean isEmpty()
    • getScheduler

      public Scheduler getScheduler()
      Returns:
      the scheduler associated with this actor (determines scheduling of processing of actors to threads)
    • isCallbackQPressured

      public boolean isCallbackQPressured()
      WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.
      Returns:
      wether the callback queue is mor than half full (can indicate overload)
    • getMailboxSize

      public int getMailboxSize()
      WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.
      Returns:
      an estimation on the queued up entries in the mailbox. Can be used for bogus flow control
    • getQSizes

      public int getQSizes()
      WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.
      Returns:
      summed queue size of mailbox+callback queue
    • getCallbackSize

      public int getCallbackSize()
      WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.
      Returns:
      an estimation on the queued up callback entries. Can be used for bogus flow control.
    • inThread

      protected <T> T inThread(Actor proxy, T cbInterface)
      wraps an interface into a proxy of that interface. The proxy object automatically enqueues all calls made on the interface onto the callback queue. Can be used incase one needs to pass other callback interfaces then built in Callback object. Stick to using 'Callback' class if possible.
      Type Parameters:
      T -
      Parameters:
      proxy -
      cbInterface -
      Returns:
    • checkThread

      protected final void checkThread()
      Debug method. can be called to check actor code is actually single threaded. By using custom callbacks/other threading bugs accidental multi threading can be detected that way.
    • getActorRef

      public Actor getActorRef()
      Returns:
      the proxy of this actor
    • isRemote

      public boolean isRemote()
      Returns:
      wether this is a proxy to a remotely running actor
    • close

      public void close()
      closes associated remote connection(s) if present. NOP otherwise. Close refers to "unmapping" the serving actor, underlying network connections will be closed. All clients get disconnected
    • closeCurrentClient

      protected void closeCurrentClient()
      closes the connection to the remote client which has sent currently executing message. If current message was not sent by a client, NOP.
    • asyncstop

      public void asyncstop()
    • hasStopped

      protected void hasStopped()
      override to clean up / stop dependend actors
    • stopSafeClose

      public void stopSafeClose()
      avoids exception when closing an actor after stop has been called.
    • ping

      public IPromise ping()
      can be used to wait for all messages having been processed and get a signal from the returned future once this is complete
      Returns:
    • serialOn

      protected void serialOn(Object transactionKey, Consumer<IPromise> toRun)
      enforce serial execution of asynchronous tasks. The 'toRun' closure must call '.complete()' (=empty result) on the given future to signal his processing has finished and the next item locked on 'transactionKey' can be processed.
      Parameters:
      transactionKey -
      toRun -
    • isPublished

      public boolean isPublished()
      Returns:
      true wether this actor is published to network
    • execute

      public void execute(Runnable command)
      just enqueue given runable to this actors mailbox and execute on the actor's thread WARNING: the similar named method execInThreadPool() works different (bad naming)
      Specified by:
      execute in interface Executor
      Parameters:
      command -
    • getCurrentDispatcher

      public DispatcherThread getCurrentDispatcher()
    • getConnections

      protected ConcurrentLinkedQueue<ConnectionRegistry> getConnections()
    • getUntypedRef

      public Actor getUntypedRef()
    • __addStopHandler

      public void __addStopHandler(Callback<SELF> cb)
    • __addRemoteConnection

      public void __addRemoteConnection(ConnectionRegistry con)
    • __removeRemoteConnection

      public void __removeRemoteConnection(ConnectionRegistry con)
    • __stop

      public void __stop()
    • __stopImpl

      protected void __stopImpl()
    • __enqueueCall

      public Object __enqueueCall(Actor receiver, String methodName, Object[] args, boolean isCB)
    • __addDeadLetter

      public void __addDeadLetter(Actor receiver, String methodName)
    • __getCachedMethod

      public Method __getCachedMethod(String methodName, Actor actor, BiFunction<Actor,String,Boolean> callInterceptor)
    • __dispatchRemoteCall

      public boolean __dispatchRemoteCall(ObjectSocket objSocket, RemoteCallEntry rce, ConnectionRegistry registry, List<IPromise> createdFutures, Object authContext, BiFunction<Actor,String,Boolean> callInterceptor, long delayCode)
      called if a message invokation from remote is received
      Returns:
      true if a new promise has been created
    • unpublish

      public void unpublish()
    • setServerMsgCallback

      public void setServerMsgCallback(Callback<RemoteCallEntry> cb)
      cb is invoked once the server sends back messages to a client, the client does not necessary have an actor running but might simply connect using ordinary mt code
      Parameters:
      cb -
    • router$clientPing

      public IPromise<Long> router$clientPing(long tim, long[] publishedActorIds)
      a krouter client should ping using this method.
      Parameters:
      tim -
      publishedActorIds - - published actors of sender
      Returns:
    • zzRoutingRefGC

      public void zzRoutingRefGC(long[] ids)
    • zzkrouterLostClient

      public void zzkrouterLostClient()
    • getReport

      public IPromise getReport()
      Specified by:
      getReport in interface Monitorable
    • getSubMonitorables

      public IPromise<Monitorable[]> getSubMonitorables()
      Specified by:
      getSubMonitorables in interface Monitorable