2024-06-10 10:53:11 +02:00
|
|
|
package actor;
|
|
|
|
|
2024-10-09 20:50:40 +02:00
|
|
|
import java.util.concurrent.LinkedBlockingQueue;
|
|
|
|
import java.util.concurrent.TimeUnit;
|
2024-10-17 01:50:25 +02:00
|
|
|
import java.util.Optional;
|
2024-06-10 10:53:11 +02:00
|
|
|
|
2024-10-09 20:50:40 +02:00
|
|
|
public class ActorThread<M> extends Thread {
|
|
|
|
|
|
|
|
private final LinkedBlockingQueue<M> q = new LinkedBlockingQueue<>();
|
2024-06-10 10:53:11 +02:00
|
|
|
|
|
|
|
/** Called by another thread, to send a message to this thread. */
|
|
|
|
public void send(M message) {
|
2024-10-09 20:50:40 +02:00
|
|
|
q.offer(message);
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Returns the first message in the queue, or blocks if none available. */
|
|
|
|
protected M receive() throws InterruptedException {
|
2024-10-09 20:50:40 +02:00
|
|
|
return q.take();
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/** Returns the first message in the queue, or blocks up to 'timeout'
|
|
|
|
milliseconds if none available. Returns null if no message is obtained
|
|
|
|
within 'timeout' milliseconds. */
|
|
|
|
protected M receiveWithTimeout(long timeout) throws InterruptedException {
|
2024-10-09 20:50:40 +02:00
|
|
|
return q.poll(timeout, TimeUnit.MILLISECONDS);
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|
2024-10-17 01:50:25 +02:00
|
|
|
|
|
|
|
protected Optional<M> poll(long timeOut) throws InterruptedException {
|
|
|
|
return Optional.ofNullable(q.poll(timeOut, TimeUnit.MILLISECONDS));
|
|
|
|
}
|
2024-06-10 10:53:11 +02:00
|
|
|
}
|