summaryrefslogtreecommitdiffstats
path: root/mobile/android/geckoview/src/main/java/org/mozilla/gecko/util/GeckoBackgroundThread.java
blob: 442f782e2f522fce729b825f9dd1a638eb69296c (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
72
73
74
75
76
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

package org.mozilla.gecko.util;

import android.os.Handler;
import android.os.Looper;

import java.util.concurrent.SynchronousQueue;

final class GeckoBackgroundThread extends Thread {
    private static final String LOOPER_NAME = "GeckoBackgroundThread";

    // Guarded by 'GeckoBackgroundThread.class'.
    private static Handler handler;
    private static Thread thread;

    // The initial Runnable to run on the new thread. Its purpose
    // is to avoid us having to wait for the new thread to start.
    private Runnable initialRunnable;

    // Singleton, so private constructor.
    private GeckoBackgroundThread(final Runnable initialRunnable) {
        this.initialRunnable = initialRunnable;
    }

    @Override
    public void run() {
        setName(LOOPER_NAME);
        Looper.prepare();

        synchronized (GeckoBackgroundThread.class) {
            handler = new Handler();
            GeckoBackgroundThread.class.notify();
        }

        if (initialRunnable != null) {
            initialRunnable.run();
            initialRunnable = null;
        }

        Looper.loop();
    }

    private static void startThread(final Runnable initialRunnable) {
        thread = new GeckoBackgroundThread(initialRunnable);
        ThreadUtils.setBackgroundThread(thread);

        thread.setDaemon(true);
        thread.start();
    }

    // Get a Handler for a looper thread, or create one if it doesn't yet exist.
    /*package*/ static synchronized Handler getHandler() {
        if (thread == null) {
            startThread(null);
        }

        while (handler == null) {
            try {
                GeckoBackgroundThread.class.wait();
            } catch (final InterruptedException e) {
            }
        }
        return handler;
    }

    /*package*/ static synchronized void post(final Runnable runnable) {
        if (thread == null) {
            startThread(runnable);
            return;
        }
        getHandler().post(runnable);
    }
}