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 * @param <T> The input type that we lock on.
28 * @param <D> The stripe type that we stripe locks on.
29 *
30 * @since 0.0.7
31 */
32 public interface ManagedLock {
33 /**
34 * Execute the supplied {@link Callable} under a lock determined by the
35 * descriptor.
36 *
37 * @param <R> the result type
38 * @param descriptor to look up the lock
39 * @param callable the operation to perform under lock
40 * @return whatever the supplied {@link Callable} returns
41 * @throws Exception if the supplied {@link Callable} throws an exception
42 */
43 <R> R withLock(final @NotNull Callable<R> callable) throws Exception;
44
45 /**
46 * Execute the supplied {@link Supplier} under a lock determined by the
47 * descriptor.
48 * <p>
49 * Unlike {@link #withLock(Object, Callable)} this version returns a result
50 * and does not declare a checked exception.
51 *
52 * @param <R> the result type
53 * @param descriptor to look up the lock
54 * @param callable the operation to perform under lock
55 * @return whatever the supplied {@link Callable} returns
56 */
57 <R> R withLock(final @NotNull Supplier<R> supplier);
58
59 /**
60 * Execute the supplied {@link Runnable} under a lock determined by the
61 * descriptor.
62 *
63 * @param descriptor to look up the lock
64 * @param runnable the operation to perform under lock
65 */
66 void withLock(final @NotNull Runnable runnable);
67
68 /**
69 * Maintains two managed locks that internally use the same
70 * {@link ReadWriteLock read/write locks}
71 */
72 interface ReadWrite {
73 /**
74 * For performing operations that require read locks
75 *
76 * @return a lock manager that uses read locks
77 */
78 ManagedLock read();
79
80 /**
81 * For performing operations that require write locks
82 *
83 * @return a lock manager that uses write locks
84 */
85 ManagedLock write();
86 }
87 }