1 /*
2  * Copyright (C) 2015 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 
17 package com.android.camera.one.v2.commands;
18 
19 import com.google.common.util.concurrent.Futures;
20 
21 import java.util.concurrent.Future;
22 
23 import javax.annotation.Nonnull;
24 import javax.annotation.ParametersAreNonnullByDefault;
25 import javax.annotation.concurrent.ThreadSafe;
26 
27 /**
28  * Converts a {@link CameraCommand} into a {@link Runnable} which interrupts and
29  * restarts the command if it was already running.
30  */
31 @ThreadSafe
32 @ParametersAreNonnullByDefault
33 public final class ResettingRunnableCameraCommand implements Runnable {
34     private final CameraCommandExecutor mExecutor;
35     private final CameraCommand mCommand;
36     private final Object mLock;
37 
38     /**
39      * The future corresponding to any currently-executing command.
40      */
41     @Nonnull
42     private Future<?> mInProgressCommand;
43 
ResettingRunnableCameraCommand(CameraCommandExecutor executor, CameraCommand command)44     public ResettingRunnableCameraCommand(CameraCommandExecutor executor, CameraCommand command) {
45         mExecutor = executor;
46         mCommand = command;
47         mLock = new Object();
48         mInProgressCommand = Futures.immediateFuture(new Object());
49     }
50 
51     @Override
run()52     public void run() {
53         synchronized (mLock) {
54             // Cancel, via interruption, the already-running command, one has
55             // been started and has not yet completed.
56             mInProgressCommand.cancel(true /* mayInterruptIfRunning */);
57             mInProgressCommand = mExecutor.execute(mCommand);
58         }
59     }
60 }
61