2015-06-05 06:46:06 +00:00
|
|
|
package eu.siacs.conversations.utils;
|
|
|
|
|
2016-05-31 15:20:21 +00:00
|
|
|
import android.os.Looper;
|
2017-11-16 14:53:03 +00:00
|
|
|
import android.util.Log;
|
2016-05-31 15:20:21 +00:00
|
|
|
|
2015-06-05 06:46:06 +00:00
|
|
|
import java.util.ArrayDeque;
|
|
|
|
import java.util.Queue;
|
|
|
|
import java.util.concurrent.Executor;
|
|
|
|
import java.util.concurrent.Executors;
|
|
|
|
|
2017-11-16 14:53:03 +00:00
|
|
|
import eu.siacs.conversations.Config;
|
2017-09-18 15:56:25 +00:00
|
|
|
import eu.siacs.conversations.services.AttachFileToConversationRunnable;
|
|
|
|
|
2015-06-05 06:46:06 +00:00
|
|
|
public class SerialSingleThreadExecutor implements Executor {
|
|
|
|
|
2018-03-18 15:46:50 +00:00
|
|
|
private final Executor executor = Executors.newSingleThreadExecutor();
|
|
|
|
final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
|
2018-04-26 11:22:31 +00:00
|
|
|
protected Runnable active;
|
2017-11-16 14:53:03 +00:00
|
|
|
private final String name;
|
2015-06-05 06:46:06 +00:00
|
|
|
|
2017-11-16 14:53:03 +00:00
|
|
|
public SerialSingleThreadExecutor(String name) {
|
|
|
|
this(name, false);
|
2016-05-31 15:20:21 +00:00
|
|
|
}
|
|
|
|
|
2018-03-18 15:46:50 +00:00
|
|
|
SerialSingleThreadExecutor(String name, boolean prepareLooper) {
|
2016-05-31 15:20:21 +00:00
|
|
|
if (prepareLooper) {
|
2018-03-18 15:46:50 +00:00
|
|
|
execute(Looper::prepare);
|
2016-05-31 15:20:21 +00:00
|
|
|
}
|
2017-11-16 14:53:03 +00:00
|
|
|
this.name = name;
|
2016-05-31 15:20:21 +00:00
|
|
|
}
|
|
|
|
|
2015-06-05 06:46:06 +00:00
|
|
|
public synchronized void execute(final Runnable r) {
|
2018-04-26 15:02:31 +00:00
|
|
|
tasks.offer(new Runner(r));
|
2015-06-05 06:46:06 +00:00
|
|
|
if (active == null) {
|
|
|
|
scheduleNext();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-03-18 15:46:50 +00:00
|
|
|
private synchronized void scheduleNext() {
|
2018-04-26 11:22:31 +00:00
|
|
|
if ((active = tasks.poll()) != null) {
|
2015-06-05 06:46:06 +00:00
|
|
|
executor.execute(active);
|
2017-11-16 14:53:03 +00:00
|
|
|
int remaining = tasks.size();
|
|
|
|
if (remaining > 0) {
|
|
|
|
Log.d(Config.LOGTAG,remaining+" remaining tasks on executor '"+name+"'");
|
|
|
|
}
|
2015-06-05 06:46:06 +00:00
|
|
|
}
|
|
|
|
}
|
2018-04-26 15:02:31 +00:00
|
|
|
|
|
|
|
private class Runner implements Runnable, Cancellable {
|
|
|
|
|
|
|
|
private final Runnable runnable;
|
|
|
|
|
|
|
|
private Runner(Runnable runnable) {
|
|
|
|
this.runnable = runnable;
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void cancel() {
|
|
|
|
if (runnable instanceof Cancellable) {
|
|
|
|
((Cancellable) runnable).cancel();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
@Override
|
|
|
|
public void run() {
|
|
|
|
try {
|
|
|
|
runnable.run();
|
|
|
|
} finally {
|
|
|
|
scheduleNext();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2015-06-05 06:46:06 +00:00
|
|
|
}
|