SingleThreadNamedTaskExecutor.java revision a48af083ff81555261f334a1e050eae3b02a746c
1/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.quicksearchbox.util;
18
19import android.util.Log;
20
21import java.util.concurrent.LinkedBlockingQueue;
22import java.util.concurrent.ThreadFactory;
23
24/**
25 * Executor that uses a single thread and an unbounded work queue.
26 */
27public class SingleThreadNamedTaskExecutor implements NamedTaskExecutor {
28
29    private static final String TAG = "QSB.SingleThreadNamedTaskExecutor";
30
31    private final LinkedBlockingQueue<NamedTask> mQueue;
32    private final Thread mWorker;
33    private volatile boolean mClosed = false;
34
35    public SingleThreadNamedTaskExecutor(ThreadFactory threadFactory) {
36        mQueue = new LinkedBlockingQueue<NamedTask>();
37        mWorker = threadFactory.newThread(new Worker());
38        mWorker.start();
39    }
40
41    public void cancelPendingTasks() {
42        if (mClosed) {
43            throw new IllegalStateException("cancelPendingTasks() after close()");
44        }
45        mQueue.clear();
46    }
47
48    public void close() {
49        mClosed = true;
50        mWorker.interrupt();
51        mQueue.clear();
52    }
53
54    public void execute(NamedTask task) {
55        if (mClosed) {
56            throw new IllegalStateException("execute() after close()");
57        }
58        mQueue.add(task);
59    }
60
61    private class Worker implements Runnable {
62        public void run() {
63            while (!mClosed) {
64                NamedTask task;
65                try {
66                    task = mQueue.take();
67                } catch (InterruptedException ex) {
68                    break;
69                }
70                try {
71                    task.run();
72                } catch (RuntimeException ex) {
73                    Log.e(TAG, "Task " + task.getName() + " failed", ex);
74                }
75            }
76        }
77    }
78
79    public static Factory<NamedTaskExecutor> factory(final ThreadFactory threadFactory) {
80        return new Factory<NamedTaskExecutor>() {
81            public NamedTaskExecutor create() {
82                return new SingleThreadNamedTaskExecutor(threadFactory);
83            }
84        };
85    }
86
87}
88