Package org.apache.groovy.runtime.async
Class DefaultActor<T>
java.lang.Object
org.apache.groovy.runtime.async.DefaultActor<T>
- Type Parameters:
T- the message type
- All Implemented Interfaces:
Actor<T>,AutoCloseable
Default implementation of
Actor using a dedicated thread
and a LinkedBlockingQueue for message processing.
Each actor runs on its own thread (virtual on JDK 21+). Messages are processed one at a time, guaranteeing thread-safe state access without locks.
- Since:
- 6.0.0
- See Also:
-
Method Summary
Modifier and TypeMethodDescriptionbooleanisActive()Returnstrueif this actor is running and accepting messages.static <T,R> Actor<T> Creates a stateless reactor actor.voidSends a message to this actor.<R> Awaitable<R>sendAndGet(T message) Sends a message and returns anAwaitablethat completes with the reply.static <T,S> Actor<T> stateful(S initialState, BiFunction<S, T, S> handler) Creates a stateful actor.voidstop()Stops this actor gracefully.toString()
-
Method Details
-
reactor
Description copied from interface:ActorCreates a stateless reactor actor. Each message is passed to the handler function, and the return value becomes the reply forActor.sendAndGet(T)callers.var doubler = Actor.reactor(n -> (int) n * 2); System.out.println(AsyncSupport.await(doubler.sendAndGet(5))); // 10- Type Parameters:
T- the message typeR- the reply type- Parameters:
handler- the message processing function- Returns:
- a started actor
-
stateful
Description copied from interface:ActorCreates a stateful actor. The handler receives the current state and the message, and returns the new state. ForActor.sendAndGet(T)callers, the new state is the reply.var counter = Actor.stateful(0, (state, msg) -> { if ("increment".equals(msg)) return (int) state + 1; return state; }); counter.send("increment"); System.out.println(AsyncSupport.await(counter.sendAndGet("increment"))); // 2- Type Parameters:
T- the message typeS- the state type- Parameters:
initialState- the initial statehandler- receives (state, message), returns new state- Returns:
- a started actor
-
send
Description copied from interface:ActorSends a message to this actor. The message is queued and processed asynchronously. Fire-and-forget — no reply is expected. -
sendAndGet
Description copied from interface:ActorSends a message and returns anAwaitablethat completes with the reply. For reactors, the reply is the handler's return value. For stateful actors, the reply is the new state.- Specified by:
sendAndGetin interfaceActor<T>- Type Parameters:
R- the reply type- Parameters:
message- the message to send- Returns:
- an awaitable reply
-
isActive
public boolean isActive()Description copied from interface:ActorReturnstrueif this actor is running and accepting messages. -
stop
public void stop()Description copied from interface:ActorStops this actor gracefully. Messages already in the queue are processed before the actor shuts down. New sends after stop throwIllegalStateException. -
toString
-