Re: [Simpleweb-Support] aren't "Dispacher-n" threads already asynchronous?
Brought to you by:
niallg
|
From: -=}\\*/{=- <rui...@gm...> - 2012-07-07 04:47:47
|
hi again,
i just finished this code and is working fine... but is this the "best"
approach?
bellow is the inner code of my container class...
i'm creating 2 threads, one (Timed) that times the runner (Runner), but if
the "Dispatcher-n" thread is already asynchronous maybe makes more sense to
use it directly and move Timed.run() code to the handle method...
[]r.
private class Runner implements Runnable {
final InnerQuest quest;
final Sponse sponse;
boolean handled = false;
Runner(InnerQuest iq, Sponse s) {
this.quest = iq;
this.sponse = s;
}
@Override
public void run() {
try {
// cascade through contexts
for (Context c: contexts)
if (c.accepts(quest))
if (c.handle(quest, sponse)) {
handled = true;
return;
}
else
quest.resetCascade();
} catch (Exception e) {
quest.logT(e, EM_UNHANDLE);
}
}
void afterRun() {
// if not handled...
if (!handled) // ... send 404 http error
sponse.sendHTTPError(Sponse.SC_404, Sponse.SCD_404, quest);
}
void finish() {
sponse.finish(quest);
// log time
quest.logI("! %1$sms: %2$s%3$s",
System.currentTimeMillis() - quest.creationTime,
quest.getHeader(Quest.H_Host), quest.getUrlPath());
// merge quest logger if exists
if (quest.hasOwnLogger())
logI(quest.logger.toString());
}
}
private class Timed implements Runnable {
private Runner runner;
private String namePostfix;
public Timed(Runner r) {
this.runner = r;
}
void start() {
namePostfix = String.valueOf(timedCount++);
new Thread(this, "TimedRunner-".concat(namePostfix)).start();
}
@Override
public void run() {
Thread thread = new Thread(runner, "Runner-".concat(namePostfix));
Quest quest = runner.quest;
thread.start();
try {
thread.join(questTimeout);
} catch (InterruptedException ex) {
quest.logT(ex, EM_INTERRUPTED);
} finally {
if (thread.isAlive()) {
thread.interrupt();
quest.logE(EM_TIMEOUT);
runner.sponse.sendHTTPInternalError(
"request handling timed out", quest);
} else if (!thread.isInterrupted()) // runner not interrupted...
runner.afterRun();
runner.finish();
runner = null;
timedCount--;
}
}
}
protected void handle(InnerQuest quest, Sponse sponse) {
Runner runner = new Runner(quest, sponse);
if (questTimeout > 0)
new Timed(runner).start();
else {
timedCount++;
runner.run();
runner.afterRun();
runner.finish();
timedCount--;
}
}
|