100 lines
2.4 KiB
Java
100 lines
2.4 KiB
Java
package de.mrbesen.telegram;
|
|
|
|
import org.json.JSONObject;
|
|
|
|
import java.util.LinkedList;
|
|
import java.util.List;
|
|
|
|
public class AsyncHandler {
|
|
|
|
private List<Task> fasttasks = new LinkedList<>();
|
|
private List<Task> slowtasks = new LinkedList<>();
|
|
|
|
private AsyncHandlerThread[] asynchandlerthread;
|
|
private static final String THREADPREFIX = "AsyncTgHandler-";
|
|
|
|
// just use 2 async threads
|
|
public AsyncHandler(TelegramAPI api) {
|
|
this(api, 2);
|
|
}
|
|
|
|
// allow as many as threadCount threads to handle Async Tasks
|
|
public AsyncHandler(TelegramAPI api, int threadCount) {
|
|
if (threadCount < 2) {
|
|
threadCount = 2;
|
|
}
|
|
asynchandlerthread = new AsyncHandlerThread[threadCount];
|
|
|
|
asynchandlerthread[0] = new AsyncHandlerThread(fasttasks, THREADPREFIX + "Fast-0", api);
|
|
|
|
for (int i = 1; i < threadCount; ++i) {
|
|
asynchandlerthread[i] = new AsyncHandlerThread(slowtasks, THREADPREFIX + "Slow-" + i, api);
|
|
}
|
|
}
|
|
|
|
public void stop() {
|
|
for (AsyncHandlerThread t : asynchandlerthread) {
|
|
t.stop();
|
|
}
|
|
}
|
|
|
|
public void enque(Task t) {
|
|
enque(t, false, false);
|
|
}
|
|
|
|
public void enque(Task t, boolean isSlowMethod, boolean priority) {
|
|
List<Task> tasks = isSlowMethod ? slowtasks : fasttasks;
|
|
|
|
if (priority) {
|
|
synchronized (tasks) {
|
|
tasks.add(0, t);
|
|
tasks.notifyAll();
|
|
}
|
|
} else {
|
|
synchronized (tasks) {
|
|
tasks.add(t);
|
|
tasks.notifyAll();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void enque(String request, String parameters, long userid) {
|
|
enque(new Task(request, parameters, userid));
|
|
}
|
|
|
|
public static class Task {
|
|
String apimethod;
|
|
String parameters;
|
|
Callback<JSONObject, ?> callback = null;
|
|
Callback<Throwable, ?> exceptionhandl = null;
|
|
final long userid;
|
|
|
|
public Task(String apimethod, String parameters, long userid) {
|
|
this(apimethod, parameters, userid, null);
|
|
}
|
|
|
|
public Task(String apimethod, String parameters, long userid, Callback<JSONObject, ?> callback) {
|
|
this.apimethod = apimethod;
|
|
this.parameters = parameters;
|
|
this.userid = userid;
|
|
this.callback = callback;
|
|
}
|
|
|
|
public Task setExceptionhandl(Callback<Throwable, ?> exceptionhandl) {
|
|
this.exceptionhandl = exceptionhandl;
|
|
return this;
|
|
}
|
|
}
|
|
|
|
public static abstract class Callback<T extends Object, K extends Object> {
|
|
public Callback<K, ?> next = null;
|
|
|
|
public abstract K call(T j) throws Throwable;
|
|
|
|
@SuppressWarnings("unchecked")
|
|
public K callObj(Object j) throws Throwable {
|
|
return call((T) j);
|
|
}
|
|
}
|
|
}
|