com.droidkit.actors.mailbox.Mailbox Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of actors Show documentation
Show all versions of actors Show documentation
DroidKit Actors is simple actor model implementation for java and Android
package com.droidkit.actors.mailbox;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* Actor mailbox, queue of envelopes.
*
* @author Stepan Ex3NDR Korshakov ([email protected])
*/
public class Mailbox {
private final TreeMap envelopes = new TreeMap();
private MailboxesQueue queue;
/**
* Creating mailbox
*
* @param queue MailboxesQueue
*/
public Mailbox(MailboxesQueue queue) {
this.queue = queue;
}
/**
* Send envelope at time
*
* @param envelope envelope
* @param time time
*/
public synchronized void schedule(Envelope envelope, long time) {
if (envelope.getMailbox() != this) {
throw new RuntimeException("envelope.mailbox != this mailbox");
}
time = queue.sendEnvelope(envelope, time);
envelopes.put(time, envelope);
}
/**
* Send envelope once at time
*
* @param envelope envelope
* @param time time
*/
public synchronized void scheduleOnce(Envelope envelope, long time) {
if (envelope.getMailbox() != this) {
throw new RuntimeException("envelope.mailbox != this mailbox");
}
Iterator> iterator = envelopes.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry entry = iterator.next();
if (isEqualEnvelope(entry.getValue(), envelope)) {
queue.removeEnvelope(entry.getKey());
iterator.remove();
}
}
schedule(envelope, time);
}
/**
* Override this if you need to change filtering for scheduleOnce behaviour.
* By default it check equality only of class names.
*
* @param a
* @param b
* @return is equal
*/
protected boolean isEqualEnvelope(Envelope a, Envelope b) {
return a.getMessage().getClass() == b.getMessage().getClass();
}
public synchronized Envelope[] allEnvelopes() {
return envelopes.values().toArray(new Envelope[0]);
}
public synchronized int getMailboxSize() {
return envelopes.size();
}
}