Home | History | Annotate | Download | only in email
      1 /*
      2  * Copyright (C) 2011 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.email;
     18 
     19 import com.android.emailcommon.Logging;
     20 
     21 import android.util.Log;
     22 
     23 import java.util.concurrent.atomic.AtomicBoolean;
     24 
     25 /**
     26  * Base class for a task that runs at most one instance at any given moment.
     27  *
     28  * Call {@link #run} to start the task.  If the task is already running on another thread, it'll do
     29  * nothing.
     30  */
     31 public abstract class SingleRunningTask<Param> {
     32     private final AtomicBoolean mIsRunning = new AtomicBoolean(false);
     33     private final String mLogTaskName;
     34 
     35     public SingleRunningTask(String logTaskName) {
     36         mLogTaskName = logTaskName;
     37     }
     38 
     39     /**
     40      * Calls {@link #runInternal} if it's not running already.
     41      */
     42     public final void run(Param param) {
     43         if (mIsRunning.compareAndSet(false, true)) {
     44             Log.i(Logging.LOG_TAG,  mLogTaskName + ": start");
     45             try {
     46                 runInternal(param);
     47             } finally {
     48                 Log.i(Logging.LOG_TAG, mLogTaskName + ": done");
     49                 mIsRunning.set(false);
     50             }
     51         } else {
     52             // Already running -- do nothing.
     53             Log.i(Logging.LOG_TAG, mLogTaskName + ": already running");
     54         }
     55     }
     56 
     57     /**
     58      * The actual task must be implemented by subclasses.
     59      */
     60     protected abstract void runInternal(Param param);
     61 
     62     /* package */ boolean isRunningForTest() {
     63         return mIsRunning.get();
     64     }
     65 }
     66