Skip to content

Commit

Permalink
Mailbox: untilHasMessage() performance improvement: Using java.util.T…
Browse files Browse the repository at this point in the history
…imerTask is quite costly, so we try Task.yield() a few times before resorting to starting one.
  • Loading branch information
Erik Søe Sørensen committed Feb 10, 2011
1 parent a2dd1c6 commit 9da3ab9
Showing 1 changed file with 33 additions and 21 deletions.
54 changes: 33 additions & 21 deletions src/kilim/Mailbox.java
Expand Up @@ -128,17 +128,17 @@ public boolean untilHasMessage(long timeoutMillis) throws Pausable {
final Task t = Task.getCurrentTask();
boolean has_msg = hasMessage(t);
long end = System.currentTimeMillis() + timeoutMillis;
int iteration = 0;
while (has_msg == false) {
TimerTask tt = new TimerTask() {
public void run() {
if (Mailbox.this.removeMessageConsumer(t)) {
t.consumeTimeout(Mailbox.this);
}
}
};
Task.timer.schedule(tt, timeoutMillis);
Task.pause(this);
tt.cancel();
if (++iteration <= 3) {
// Timer creation is costly, and frequently it has to
// be cancelled anyway. Try to avoid it:
Task.yield();
} else {
TimerTask tt = startConsumerTimeoutTimer(t, timeoutMillis);
Task.pause(this);
tt.cancel();
}
has_msg = hasMessage(t);
timeoutMillis = end - System.currentTimeMillis();
if (timeoutMillis <= 0) {
Expand All @@ -159,20 +159,20 @@ public boolean untilHasMessages(int num, long timeoutMillis)
final long end = System.currentTimeMillis() + timeoutMillis;

boolean has_msg = hasMessages(num, t);
int iteration = 0;
while (has_msg == false) {
TimerTask tt = new TimerTask() {
public void run() {
if (removeMessageConsumer(t)) {
t.consumeTimeout(Mailbox.this);
}
if (++iteration <= 3) {
// Timer creation is costly, and frequently it has to
// be cancelled anyway. Try to avoid it:
Task.yield();
} else {
TimerTask tt = startConsumerTimeoutTimer(t, timeoutMillis);
Task.pause(this);
if (!tt.cancel()) {
removeMessageConsumer(t);
}
};
Task.timer.schedule(tt, timeoutMillis);
Task.pause(this);
if (!tt.cancel()) {
removeMessageConsumer(t);
}

has_msg = hasMessages(num, t);
timeoutMillis = end - System.currentTimeMillis();
if (!has_msg && timeoutMillis <= 0) {
Expand All @@ -183,6 +183,18 @@ public void run() {
return has_msg;
}

private TimerTask startConsumerTimeoutTimer(final Task t, long timeoutMillis) {
TimerTask tt = new TimerTask() {
public void run() {
if (removeMessageConsumer(t)) {
t.consumeTimeout(Mailbox.this);
}
}
};
Task.timer.schedule(tt, timeoutMillis);
return tt;
}

/**
* Non-blocking, nonpausing "wait-until-message-available".
*
Expand Down

0 comments on commit 9da3ab9

Please sign in to comment.