aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/de/pixart/messenger/utils/SerialSingleThreadExecutor.java
blob: 500b03c5b0e93ebe4e998fa1fd53b03de5332d25 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package de.pixart.messenger.utils;

import android.os.Looper;
import android.util.Log;

import java.util.ArrayDeque;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import de.pixart.messenger.Config;

public class SerialSingleThreadExecutor implements Executor {

    final ArrayDeque<Runnable> tasks = new ArrayDeque<>();
    private final Executor executor = Executors.newSingleThreadExecutor();
    private final String name;
    protected Runnable active;

    public SerialSingleThreadExecutor(String name) {
        this(name, false);
    }

    SerialSingleThreadExecutor(String name, boolean prepareLooper) {
        if (prepareLooper) {
            execute(Looper::prepare);
        }
        this.name = name;
    }

    public synchronized void execute(final Runnable r) {
        tasks.offer(new Runner(r));
        if (active == null) {
            scheduleNext();
        }
    }

    private synchronized void scheduleNext() {
        if ((active = tasks.poll()) != null) {
            executor.execute(active);
            int remaining = tasks.size();
            if (remaining > 0) {
                Log.d(Config.LOGTAG, remaining + " remaining tasks on executor '" + name + "'");
            }
        }
    }

    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();
            }
        }
    }
}