Package org.nustaq.kontraktor
Class Actor<SELF extends Actor>
java.lang.Object
org.nustaq.kontraktor.Actors
org.nustaq.kontraktor.Actor<SELF>
- All Implemented Interfaces:
java.io.Serializable,java.util.concurrent.Executor,Monitorable
- Direct Known Subclasses:
_AsyncClientSocket.CLSActor,AbstractKrouter,Log,TCPClientConnector.RemotingHelper
public class Actor<SELF extends Actor> extends Actors implements java.io.Serializable, Monitorable, java.util.concurrent.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 ActorNote 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.{ // 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();
- See Also:
- Serialized Form
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classActor.ActorReport -
Field Summary
Fields Modifier and Type Field Description java.util.Queue__cbQueueConnectionRegistry__clientConnectionjava.util.concurrent.ConcurrentLinkedQueue<ConnectionRegistry>__connectionsjava.lang.Thread__currentDispatcherjava.util.Queue__mailboxint__mailboxCapacityint__mbCapacityActor__publishTargetlong__remoteIdScheduler__schedulerActor__selfboolean__stoppedprotected TicketMachine__ticketMachinestatic java.lang.ThreadLocal<ConnectionRegistry>connectioncontains remote connection if current message came from remotestatic java.lang.ThreadLocal<Actor>sendercontains sender of a message if one actor messages to another actorjava.lang.ObjectuserDatafree for outer mechanics to use.booleanzzRoutingGCEnabledCallback<RemoteCallEntry>zzServerMsgCallbackFields inherited from class org.nustaq.kontraktor.Actors
CONT, DEFAULT_TIMOUT, defaultScheduler, delayedCalls, exec, instance, MAX_EXTERNAL_THREADS_POOL_SIZE, version -
Constructor Summary
Constructors Constructor Description Actor()required by bytecode magic. -
Method Summary
Modifier and Type Method Description void__addDeadLetter(Actor receiver, java.lang.String methodName)void__addRemoteConnection(ConnectionRegistry con)void__addStopHandler(Callback<SELF> cb)boolean__dispatchRemoteCall(ObjectSocket objSocket, RemoteCallEntry rce, ConnectionRegistry registry, java.util.List<IPromise> createdFutures, java.lang.Object authContext, java.util.function.BiFunction<Actor,java.lang.String,java.lang.Boolean> callInterceptor, long delayCode)called if a message invokation from remote is receivedjava.lang.Object__enqueueCall(Actor receiver, java.lang.String methodName, java.lang.Object[] args, boolean isCB)java.lang.reflect.Method__getCachedMethod(java.lang.String methodName, Actor actor, java.util.function.BiFunction<Actor,java.lang.String,java.lang.Boolean> callInterceptor)void__removeRemoteConnection(ConnectionRegistry con)void__stop()protected void__stopImpl()void__submit(java.lang.Runnable toRun)IPromiseask(java.lang.String messageId, java.lang.Object... args)generic method for untyped remoting.IPromiseaskMsg(java.lang.String messageId, java.lang.Object... args)generic method for untyped messages.voidasyncstop()protected voidcheckThread()Debug method.voidclose()closes associated remote connection(s) if present.protected voidcloseCurrentClient()closes the connection to the remote client which has sent currently executing message.static Actorcurrent()voidcyclic(long interval, java.util.concurrent.Callable<java.lang.Boolean> toRun)voiddebounce(long timeout, java.lang.String tag, java.lang.Runnable toRun)voiddelayed(long millis, java.lang.Runnable toRun)schedule an action or call delayed.<T> IPromise<T>execInThreadPool(java.util.concurrent.Callable<T> callable)execute a callable asynchronously (in a different thread) and return a future of the result (delivered in caller thread).voidexecute(java.lang.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)SELFgetActor()ActorgetActorRef()intgetCallbackSize()WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.protected java.util.concurrent.ConcurrentLinkedQueue<ConnectionRegistry>getConnections()DispatcherThreadgetCurrentDispatcher()ActorProxyFactorygetFactory()intgetMailboxSize()WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.intgetQSizes()WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.IPromisegetReport()SchedulergetScheduler()IPromise<Monitorable[]>getSubMonitorables()ActorgetUntypedRef()protected voidhasStopped()override to clean up / stop dependend actorsstatic booleaninside()protected <T> TinThread(Actor proxy, T cbInterface)wraps an interface into a proxy of that interface.booleanisCallbackQPressured()WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.booleanisEmpty()booleanisMailboxPressured()WARNING: call rarely, this method might have O(n) runtime with default unbounded queues.booleanisProxy()booleanisPublished()booleanisRemote()booleanisStopped()synchronous method returning true in case this actor is stoppedIPromiseping()can be used to wait for all messages having been processed and get a signal from the returned future once this is completeIPromise<java.lang.Long>router$clientPing(long tim, long[] publishedActorIds)a krouter client should ping using this method.protected SELFself()use this to call public methods using actor-dispatch instead of direct in-thread call.protected voidserialOn(java.lang.Object transactionKey, java.util.function.Consumer<IPromise> toRun)enforce serial execution of asynchronous tasks.voidsetServerMsgCallback(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 codevoidstop()stop receiving events.voidstopSafeClose()avoids exception when closing an actor after stop has been called.voidtell(java.lang.String messageId, java.lang.Object... args)generic method for untyped remoting.voidtellMsg(java.lang.String messageId, java.lang.Object... args)generic method for untyped messages.voidunpublish()voidzzkrouterLostClient()voidzzRoutingRefGC(long[] ids)Methods inherited from class org.nustaq.kontraktor.Actors
AddDeadLetter, all, all, all, allMapped, AsActor, AsActor, AsActor, AsActor, AsUntypedActor, awaitAll, awaitAll, awaitAll, awaitAll, complete, complete, DeadLetters, flow, InThread, isComplete, isCont, isError, isErrorOrComplete, isResult, isTimeout, kYield, kYield, promise, race, race, reject, resolve, resolve, stream, SubmitDelayed, yieldCallbacks
-
Field Details
-
sender
contains sender of a message if one actor messages to another actor -
connection
contains remote connection if current message came from remote -
userData
public java.lang.Object userDatafree for outer mechanics to use. -
__mailbox
public java.util.Queue __mailbox -
__mbCapacity
public int __mbCapacity -
__cbQueue
public java.util.Queue __cbQueue -
__currentDispatcher
public java.lang.Thread __currentDispatcher -
__scheduler
-
__stopped
public volatile boolean __stopped -
__self
-
__remoteId
public long __remoteId -
__connections
-
__clientConnection
-
zzRoutingGCEnabled
public boolean zzRoutingGCEnabled -
__mailboxCapacity
public int __mailboxCapacity -
__ticketMachine
-
zzServerMsgCallback
-
__publishTarget
-
-
Constructor Details
-
Actor
public Actor()required by bytecode magic. Use Actors.AsActor(..) to construct actor instances
-
-
Method Details
-
current
- Returns:
- current actor or throw an exception if not running inside an actor thread.
-
inside
public static boolean inside() -
__submit
public void __submit(java.lang.Runnable toRun) -
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
-
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
generic method for untyped messages.- Parameters:
messageId-- Returns:
-
tellMsg
public void tellMsg(java.lang.String messageId, java.lang.Object... args)generic method for untyped messages.- Parameters:
messageId-
-
ask
generic method for untyped remoting.- Parameters:
messageId-- Returns:
-
tell
public void tell(java.lang.String messageId, java.lang.Object... args)generic method for untyped remoting.- Parameters:
messageId-
-
execInThreadPool
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, java.util.concurrent.Callable<java.lang.Boolean> toRun) -
debounce
public void debounce(long timeout, java.lang.String tag, java.lang.Runnable toRun) -
delayed
public void delayed(long millis, java.lang.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
- 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
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
- 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
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(java.lang.Object transactionKey, java.util.function.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(java.lang.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:
executein interfacejava.util.concurrent.Executor- Parameters:
command-
-
getCurrentDispatcher
-
getConnections
-
getUntypedRef
-
__addStopHandler
-
__addRemoteConnection
-
__removeRemoteConnection
-
__stop
public void __stop() -
__stopImpl
protected void __stopImpl() -
__enqueueCall
public java.lang.Object __enqueueCall(Actor receiver, java.lang.String methodName, java.lang.Object[] args, boolean isCB) -
__addDeadLetter
-
__getCachedMethod
-
__dispatchRemoteCall
public boolean __dispatchRemoteCall(ObjectSocket objSocket, RemoteCallEntry rce, ConnectionRegistry registry, java.util.List<IPromise> createdFutures, java.lang.Object authContext, java.util.function.BiFunction<Actor,java.lang.String,java.lang.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
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
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
- Specified by:
getReportin interfaceMonitorable
-
getSubMonitorables
- Specified by:
getSubMonitorablesin interfaceMonitorable
-