EDAF85-labs/wash/src/actor/ActorThread.java

51 lines
1.6 KiB
Java
Raw Normal View History

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;
import java.util.Optional;
2024-06-10 10:53:11 +02:00
public abstract class ActorThread<M> extends Thread {
2024-10-09 20:50:40 +02:00
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-11-07 01:54:44 +01:00
System.out.println(" # Sending message: " + message);
2024-10-09 20:50:40 +02:00
q.offer(message);
2024-11-07 01:54:44 +01:00
System.out.println(" % Queue State: " + q);
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-11-07 01:54:44 +01:00
M mess = q.take();
System.out.println(" - Message taken: " + mess);
return mess;
2024-06-10 10:53:11 +02:00
}
2024-11-07 01:54:44 +01:00
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
}
protected Optional<M> poll(long timeOut) {
try {
2024-11-07 01:54:44 +01:00
Optional<M> m = Optional.ofNullable(q.poll(timeOut, TimeUnit.MILLISECONDS));
System.out.println("Stolen: " + m);
return m;
} 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();
}
}
2024-06-10 10:53:11 +02:00
}