View Javadoc

1   /**
2    * Copyright 2008 Atlassian Pty Ltd 
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.atlassian.util.concurrent;
18  
19  import java.util.concurrent.Callable;
20  import java.util.concurrent.locks.ReadWriteLock;
21  
22  /**
23   * {@link ManagedLock} allows {@link Callable callables}, {@link Runnable
24   * runnables} and {@link Supplier suppliers} to be run under a lock that is
25   * resolved against an input object.
26   * 
27   * @since 0.0.7
28   */
29  public interface ManagedLock {
30      /**
31       * Execute the supplied {@link Callable} under a lock determined by the
32       * descriptor.
33       * 
34       * @param <R> the result type
35       * @param callable the operation to perform under lock
36       * @return whatever the supplied {@link Callable} returns
37       * @throws Exception if the supplied {@link Callable} throws an exception
38       */
39      <R> R withLock(final @NotNull Callable<R> callable) throws Exception;
40  
41      /**
42       * Execute the supplied {@link Supplier} under a lock determined by the
43       * descriptor.
44       * <p>
45       * Unlike {@link #withLock(Callable)} this version returns a result and does
46       * not declare a checked exception.
47       * 
48       * @param <R> the result type
49       * @param supplier the operation to perform under lock
50       * @return whatever the supplied {@link Callable} returns
51       */
52      <R> R withLock(final @NotNull Supplier<R> supplier);
53  
54      /**
55       * Execute the supplied {@link Runnable} under a lock determined by the
56       * descriptor.
57       * 
58       * @param runnable the operation to perform under lock
59       */
60      void withLock(final @NotNull Runnable runnable);
61  
62      /**
63       * Maintains two managed locks that internally use the same
64       * {@link ReadWriteLock read/write locks}
65       */
66      interface ReadWrite {
67          /**
68           * For performing operations that require read locks
69           * 
70           * @return a lock manager that uses read locks
71           */
72          ManagedLock read();
73  
74          /**
75           * For performing operations that require write locks
76           * 
77           * @return a lock manager that uses write locks
78           */
79          ManagedLock write();
80      }
81  }