mobile/android/base/util/GeckoBackgroundThread.java

Thu, 22 Jan 2015 13:21:57 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Thu, 22 Jan 2015 13:21:57 +0100
branch
TOR_BUG_9701
changeset 15
b8a032363ba2
permissions
-rw-r--r--

Incorporate requested changes from Mozilla in review:
https://bugzilla.mozilla.org/show_bug.cgi?id=1123480#c6

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
michael@0 3 * You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 package org.mozilla.gecko.util;
michael@0 6
michael@0 7 import android.os.Handler;
michael@0 8 import android.os.Looper;
michael@0 9
michael@0 10 import java.util.concurrent.SynchronousQueue;
michael@0 11
michael@0 12 final class GeckoBackgroundThread extends Thread {
michael@0 13 private static final String LOOPER_NAME = "GeckoBackgroundThread";
michael@0 14
michael@0 15 // Guarded by 'this'.
michael@0 16 private static Handler sHandler = null;
michael@0 17 private SynchronousQueue<Handler> mHandlerQueue = new SynchronousQueue<Handler>();
michael@0 18
michael@0 19 // Singleton, so private constructor.
michael@0 20 private GeckoBackgroundThread() {
michael@0 21 super();
michael@0 22 }
michael@0 23
michael@0 24 @Override
michael@0 25 public void run() {
michael@0 26 setName(LOOPER_NAME);
michael@0 27 Looper.prepare();
michael@0 28 try {
michael@0 29 mHandlerQueue.put(new Handler());
michael@0 30 } catch (InterruptedException ie) {}
michael@0 31
michael@0 32 Looper.loop();
michael@0 33 }
michael@0 34
michael@0 35 // Get a Handler for a looper thread, or create one if it doesn't yet exist.
michael@0 36 /*package*/ static synchronized Handler getHandler() {
michael@0 37 if (sHandler == null) {
michael@0 38 GeckoBackgroundThread lt = new GeckoBackgroundThread();
michael@0 39 ThreadUtils.setBackgroundThread(lt);
michael@0 40 lt.start();
michael@0 41 try {
michael@0 42 sHandler = lt.mHandlerQueue.take();
michael@0 43 } catch (InterruptedException ie) {}
michael@0 44 }
michael@0 45 return sHandler;
michael@0 46 }
michael@0 47
michael@0 48 /*package*/ static void post(Runnable runnable) {
michael@0 49 Handler handler = getHandler();
michael@0 50 if (handler == null) {
michael@0 51 throw new IllegalStateException("No handler! Must have been interrupted. Not posting.");
michael@0 52 }
michael@0 53 handler.post(runnable);
michael@0 54 }
michael@0 55 }

mercurial