ActorThread extended with timeout poll with Optional<T> return type

This commit is contained in:
Imbus 2024-11-03 16:18:59 +01:00
parent af173df69d
commit 1f859d1a28

View file

@ -4,7 +4,7 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.Optional; import java.util.Optional;
public class ActorThread<M> extends Thread { public abstract class ActorThread<M> extends Thread {
private final LinkedBlockingQueue<M> q = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<M> q = new LinkedBlockingQueue<>();
@ -25,7 +25,21 @@ public class ActorThread<M> extends Thread {
return q.poll(timeout, TimeUnit.MILLISECONDS); return q.poll(timeout, TimeUnit.MILLISECONDS);
} }
protected Optional<M> poll(long timeOut) throws InterruptedException { protected Optional<M> poll(long timeOut) {
return Optional.ofNullable(q.poll(timeOut, TimeUnit.MILLISECONDS)); try {
return Optional.ofNullable(q.poll(timeOut, TimeUnit.MILLISECONDS));
} catch (InterruptedException e) {
return Optional.empty();
} catch (Exception e) {
return Optional.empty(); // Or exit the program
}
}
protected void usleep(long time) {
try {
Thread.sleep(time);
} catch (InterruptedException e) {
e.printStackTrace();
}
} }
} }