Wed, 31 Dec 2014 07:22:50 +0100
Correct previous dual key logic pending first delivery installment.
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 | } |