Package org.nustaq.kontraktor
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 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:
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionintintlongbooleanprotected TicketMachinestatic ThreadLocal<ConnectionRegistry>contains remote connection if current message came from remotestatic ThreadLocal<Actor>contains sender of a message if one actor messages to another actorfree for outer mechanics to use.booleanFields inherited from class org.nustaq.kontraktor.Actors
CONT, DEFAULT_TIMOUT, defaultScheduler, delayedCalls, exec, instance, MAX_EXTERNAL_THREADS_POOL_SIZE, version -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionvoid__addDeadLetter(Actor receiver, String methodName) voidvoid__addStopHandler(Callback<SELF> cb) 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__enqueueCall(Actor receiver, String methodName, Object[] args, boolean isCB) __getCachedMethod(String methodName, Actor actor, BiFunction<Actor, String, Boolean> callInterceptor) voidvoid__stop()protected voidvoidgeneric method for untyped remoting.generic method for untyped messages.voidprotected final voidDebug method.voidclose()closes associated remote connection(s) if present.protected voidcloses the connection to the remote client which has sent currently executing message.static Actorcurrent()voidvoidvoidschedule an action or call delayed.<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).voidjust enqueue given runable to this actors mailbox and execute on the actor's thread WARNING: the similar named method execInThreadPool() works different (bad naming)getActor()intWARNING: call rarely, this method might have O(n) runtime with default unbounded queues.protected ConcurrentLinkedQueue<ConnectionRegistry>intWARNING: call rarely, this method might have O(n) runtime with default unbounded queues.intWARNING: call rarely, this method might have O(n) runtime with default unbounded queues.protected voidoverride to clean up / stop dependend actorsstatic booleaninside()protected <T> Twraps an interface into a proxy of that interface.booleanWARNING: call rarely, this method might have O(n) runtime with default unbounded queues.booleanisEmpty()booleanWARNING: call rarely, this method might have O(n) runtime with default unbounded queues.booleanisProxy()booleanbooleanisRemote()booleansynchronous method returning true in case this actor is stoppedping()can be used to wait for all messages having been processed and get a signal from the returned future once this is completerouter$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 voidenforce serial execution of asynchronous tasks.voidcb 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.voidavoids exception when closing an actor after stop has been called.voidgeneric method for untyped remoting.voidgeneric method for untyped messages.voidvoidvoidzzRoutingRefGC(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
free for outer mechanics to use. -
__mailbox
-
__mbCapacity
public int __mbCapacity -
__cbQueue
-
__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
-
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
generic method for untyped messages.- Parameters:
messageId-
-
ask
generic method for untyped remoting.- Parameters:
messageId-- Returns:
-
tell
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
-
debounce
-
delayed
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
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
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) -
getCurrentDispatcher
-
getConnections
-
getUntypedRef
-
__addStopHandler
-
__addRemoteConnection
-
__removeRemoteConnection
-
__stop
public void __stop() -
__stopImpl
protected void __stopImpl() -
__enqueueCall
-
__addDeadLetter
-
__getCachedMethod
-
__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
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
-