TelegramAPI/src/main/java/de/mrbesen/telegram/AsyncHandlerThread.java

100 lines
2.1 KiB
Java

package de.mrbesen.telegram;
import java.net.UnknownHostException;
import java.util.List;
import de.mrbesen.telegram.AsyncHandler.Callback;
import de.mrbesen.telegram.AsyncHandler.Task;
public class AsyncHandlerThread implements Runnable {
private boolean shouldrun = false;
private TelegramAPI api;
private int failed = 0;
private Thread thread;
private List<Task> tasks;
AsyncHandlerThread(List<Task> tasks, String name, TelegramAPI api) {
this.tasks = tasks;
this.api = api;
shouldrun = true;
thread = new Thread(this, name);
thread.start();
}
public void stop() {
shouldrun = false;
thread.interrupt();
try {
thread.join();
} catch (InterruptedException e) {
}
}
@Override
public void run() {
while (shouldrun) {
Task t;
synchronized (tasks) {
while (tasks.isEmpty()) {
try {
tasks.wait();
} catch (InterruptedException e) {
}
}
t = tasks.remove(0);
tasks.notifyAll();
}
if (t == null)
continue;
// run task
try {
processTask(t);
} catch (Throwable thro) {
api.log.log("Error executing Task: ");
thro.printStackTrace();
}
}
}
private void processTask(Task t) throws Throwable {
try {
Object obj = api.request(t.apimethod, t.parameters, t.userid);
Callback<?, ?> callb = t.callback;
while (callb != null) {
obj = (Object) callb.callObj(obj);
callb = callb.next;
// throw new Exception("Callbacktype missmatch! Got " +
// obj.getClass().getSimpleName() + " Wanted: " + wanted.getSimpleName() );
}
failed = 0;
} catch (UnknownHostException ex) { // host(api.telegram.org) is good -> bad inet
failed++;
if (failed > 10)
try {
Thread.sleep(1000); // wait 1 second
} catch (InterruptedException ignored) {
}
// reenque
synchronized (tasks) {
tasks.add(0, t);
}
} catch (Throwable thro) {
if (t.exceptionhandl == null)
throw thro;
api.log.log("Exception " + thro.getClass().getSimpleName() + " handled by "
+ t.exceptionhandl.getClass().getSimpleName());
t.exceptionhandl.call(thro);
}
}
}