1/*
2 * Copyright (C) 2015 DroidDriver committers
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 io.appium.droiddriver.helpers;
18
19import java.util.concurrent.atomic.AtomicBoolean;
20
21/**
22 * Base class for an action that should run only once no matter how many times the method {@link
23 * #singleRun()} is called upon an instance. Typically it is used on a singleton to achieve once for
24 * a class effect.
25 */
26public abstract class SingleRun {
27  private AtomicBoolean hasRun = new AtomicBoolean();
28
29  /**
30   * Calls {@link #run()} if it is the first time this method is called upon this instance.
31   *
32   * @return true if this is the first time it is called, otherwise false
33   */
34  public final boolean singleRun() {
35    if (hasRun.compareAndSet(false, true)) {
36      run();
37      return true;
38    }
39    return false;
40  }
41
42  /**
43   * Takes the action that should run only once.
44   */
45  protected abstract void run();
46}
47