ResettingDelayedExecutor.java revision 9c94ab32a69a1ad3642a0f1e38e68bcfd97d3511
1/*
2 * Copyright (C) 2014 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.camera.async;
18
19import java.util.concurrent.Executor;
20import java.util.concurrent.ScheduledExecutorService;
21import java.util.concurrent.ScheduledFuture;
22import java.util.concurrent.TimeUnit;
23
24/**
25 * An executor which executes with a delay, discarding pending executions such
26 * that at most one task is queued at any time.
27 */
28public class ResettingDelayedExecutor implements Executor, SafeCloseable {
29    private final ScheduledExecutorService mExecutor;
30    private final long mDelay;
31    private final TimeUnit mDelayUnit;
32    /**
33     * Lock for all mutable state: {@link #mLatestRunRequest} and
34     * {@link #mClosed}.
35     */
36    private final Object mLock;
37    private ScheduledFuture<?> mLatestRunRequest;
38    private boolean mClosed;
39
40    public ResettingDelayedExecutor(ScheduledExecutorService executor, long delay, TimeUnit
41            delayUnit) {
42        mExecutor = executor;
43        mDelay = delay;
44        mDelayUnit = delayUnit;
45        mLock = new Object();
46    }
47
48    @Override
49    public void execute(Runnable runnable) {
50        synchronized (mLock) {
51            if (mClosed) {
52                return;
53            }
54            // Cancel any existing, queued task before scheduling another.
55            if (mLatestRunRequest != null) {
56                boolean mayInterruptIfRunning = false;
57                mLatestRunRequest.cancel(mayInterruptIfRunning);
58            }
59            mLatestRunRequest = mExecutor.schedule(runnable, mDelay, mDelayUnit);
60        }
61    }
62
63    @Override
64    public void close() {
65        synchronized (mLock) {
66            if (mClosed) {
67                return;
68            }
69            mExecutor.shutdownNow();
70        }
71    }
72}
73