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

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

mercurial