summaryrefslogtreecommitdiffstats
path: root/core/java/android/hardware/camera2/utils/CloseableLock.java
blob: 9ac89c8254304947787024b5dc84b29119092a56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.hardware.camera2.utils;

import android.util.Log;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Implement a shared/exclusive lock that can be closed.
 *
 * <p>A shared lock can be acquired if any other shared locks are also acquired. An
 * exclusive lock acquire will block until all shared locks have been released.</p>
 *
 * <p>Locks are re-entrant; trying to acquire another lock (of the same type)
 * while a lock is already held will immediately succeed.</p>
 *
 * <p>Acquiring to acquire a shared lock while holding an exclusive lock or vice versa is not
 * supported; attempting it will throw an {@link IllegalStateException}.</p>
 *
 * <p>If the lock is closed, all future and current acquires will immediately return {@code null}.
 * </p>
 */
public class CloseableLock implements AutoCloseable {

    private static final boolean VERBOSE = false;

    private final String TAG = "CloseableLock";
    private final String mName;

    private volatile boolean mClosed = false;

    /** If an exclusive lock is acquired by some thread. */
    private boolean mExclusive = false;
    /**
     * How many shared locks are acquired by any thread:
     *
     * <p>Reentrant locking increments this. If an exclusive lock is held,
     * this value will stay at 0.</p>
     */
    private int mSharedLocks = 0;

    private final ReentrantLock mLock = new ReentrantLock();
    /** This condition automatically releases mLock when waiting; re-acquiring it after notify */
    private final Condition mCondition = mLock.newCondition();

    /** How many times the current thread is holding the lock */
    private final ThreadLocal<Integer> mLockCount =
        new ThreadLocal<Integer>() {
            @Override protected Integer initialValue() {
                return 0;
            }
        };

    /**
     * Helper class to release a lock at the end of a try-with-resources statement.
     */
    public class ScopedLock implements AutoCloseable {
        private ScopedLock() {}

        /** Release the lock with {@link CloseableLock#releaseLock}. */
        @Override
        public void close() {
            releaseLock();
        }
    }

    /**
     * Create a new instance; starts out with 0 locks acquired.
     */
    public CloseableLock() {
        mName = "";
    }

    /**
     * Create a new instance; starts out with 0 locks acquired.
     *
     * @param name set an optional name for logging functionality
     */
    public CloseableLock(String name) {
        mName = name;
    }

    /**
     * Acquires the lock exclusively (blocking), marks it as closed, then releases the lock.
     *
     * <p>Marking a lock as closed will fail all further acquisition attempts;
     * it will also immediately unblock all other threads currently trying to acquire a lock.</p>
     *
     * <p>This operation is idempotent; calling it more than once has no effect.</p>
     *
     * @throws IllegalStateException
     *          if an attempt is made to {@code close} while this thread has a lock acquired
     */
    @Override
    public void close() {
        if (mClosed) {
            if (VERBOSE) {
                log("close - already closed; ignoring");
            }
            return;
        }

        ScopedLock scoper = acquireExclusiveLock();
        // Already closed by another thread?
        if (scoper == null) {
            return;
        } else if (mLockCount.get() != 1) {
            // Future: may want to add a #releaseAndClose to allow this.
            throw new IllegalStateException(
                    "Cannot close while one or more acquired locks are being held by this " +
                     "thread; release all other locks first");
        }

        try {
            mLock.lock();

            mClosed = true;
            mExclusive = false;
            mSharedLocks = 0;
            mLockCount.remove();

            // Notify all threads that are waiting to unblock and return immediately
            mCondition.signalAll();
        } finally {
            mLock.unlock();
        }

        if (VERBOSE) {
            log("close - completed");
        }
    }

    /**
     * Try to acquire the lock non-exclusively, blocking until the operation completes.
     *
     * <p>If the lock has already been closed, or being closed before this operation returns,
     * the call will immediately return {@code false}.</p>
     *
     * <p>If other threads hold a non-exclusive lock (and the lock is not yet closed),
     * this operation will return immediately. If another thread holds an exclusive lock,
     * this thread will block until the exclusive lock has been released.</p>
     *
     * <p>This lock is re-entrant; acquiring more than one non-exclusive lock per thread is
     * supported, and must be matched by an equal number of {@link #releaseLock} calls.</p>
     *
     * @return {@code ScopedLock} instance if the lock was acquired, or {@code null} if the lock
     *         was already closed.
     *
     * @throws IllegalStateException if this thread is already holding an exclusive lock
     */
    public ScopedLock acquireLock() {

        int ownedLocks;

        try {
            mLock.lock();

            // Lock is already closed, all further acquisitions will fail
            if (mClosed) {
                if (VERBOSE) {
                    log("acquire lock early aborted (already closed)");
                }
                return null;
            }

            ownedLocks = mLockCount.get();

            // This thread is already holding an exclusive lock
            if (mExclusive && ownedLocks > 0) {
                throw new IllegalStateException(
                        "Cannot acquire shared lock while holding exclusive lock");
            }

            // Is another thread holding the exclusive lock? Block until we can get in.
            while (mExclusive) {
                mCondition.awaitUninterruptibly();

                // Did another thread #close while we were waiting? Unblock immediately.
                if (mClosed) {
                    if (VERBOSE) {
                        log("acquire lock unblocked aborted (already closed)");
                    }
                    return null;
                }
            }

            mSharedLocks++;

            ownedLocks = mLockCount.get() + 1;
            mLockCount.set(ownedLocks);
        } finally {
            mLock.unlock();
        }

        if (VERBOSE) {
            log("acquired lock (local own count = " + ownedLocks + ")");
        }
        return new ScopedLock();
    }

    /**
     * Try to acquire the lock exclusively, blocking until all other threads release their locks.
     *
     * <p>If the lock has already been closed, or being closed before this operation returns,
     * the call will immediately return {@code false}.</p>
     *
     * <p>If any other threads are holding a lock, this thread will block until all
     * other locks are released.</p>
     *
     * <p>This lock is re-entrant; acquiring more than one exclusive lock per thread is supported,
     * and must be matched by an equal number of {@link #releaseLock} calls.</p>
     *
     * @return {@code ScopedLock} instance if the lock was acquired, or {@code null} if the lock
     *         was already closed.
     *
     * @throws IllegalStateException
     *          if an attempt is made to acquire an exclusive lock while already holding a lock
     */
    public ScopedLock acquireExclusiveLock() {

        int ownedLocks;

        try {
            mLock.lock();

            // Lock is already closed, all further acquisitions will fail
            if (mClosed) {
                if (VERBOSE) {
                    log("acquire exclusive lock early aborted (already closed)");
                }
                return null;
            }

            ownedLocks = mLockCount.get();

            // This thread is already holding a shared lock
            if (!mExclusive && ownedLocks > 0) {
                throw new IllegalStateException(
                        "Cannot acquire exclusive lock while holding shared lock");
            }

            /*
             * Is another thread holding the lock? Block until we can get in.
             *
             * If we are already holding the lock, always let it through since
             * we are just reentering the exclusive lock.
             */
            while (ownedLocks == 0 && (mExclusive || mSharedLocks > 0)) {
                mCondition.awaitUninterruptibly();

             // Did another thread #close while we were waiting? Unblock immediately.
                if (mClosed) {
                    if (VERBOSE) {
                        log("acquire exclusive lock unblocked aborted (already closed)");
                    }
                    return null;
                }
            }

            mExclusive = true;

            ownedLocks = mLockCount.get() + 1;
            mLockCount.set(ownedLocks);
        } finally {
            mLock.unlock();
        }

        if (VERBOSE) {
            log("acquired exclusive lock (local own count = " + ownedLocks + ")");
        }
        return new ScopedLock();
    }

    /**
     * Release a single lock that was acquired.
     *
     * <p>Any other other that is blocked and trying to acquire a lock will get a chance
     * to acquire the lock.</p>
     *
     * @throws IllegalStateException if no locks were acquired, or if the lock was already closed
     */
    public void releaseLock() {
        if (mLockCount.get() <= 0) {
            throw new IllegalStateException(
                    "Cannot release lock that was not acquired by this thread");
        }

        int ownedLocks;

        try {
            mLock.lock();

            // Lock is already closed, it couldn't have been acquired in the first place
            if (mClosed) {
                throw new IllegalStateException("Do not release after the lock has been closed");
            }

            if (!mExclusive) {
                mSharedLocks--;
            } else {
                if (mSharedLocks != 0) {
                    throw new AssertionError("Too many shared locks " + mSharedLocks);
                }
            }

            ownedLocks = mLockCount.get() - 1;
            mLockCount.set(ownedLocks);

            if (ownedLocks == 0 && mExclusive) {
                // Wake up any threads that might be waiting for the exclusive lock to be released
                mExclusive = false;
                mCondition.signalAll();
            } else if (ownedLocks == 0 && mSharedLocks == 0) {
                // Wake up any threads that might be trying to get the exclusive lock
                mCondition.signalAll();
            }
        } finally {
            mLock.unlock();
        }

        if (VERBOSE) {
             log("released lock (local lock count " + ownedLocks + ")");
        }
    }

    private void log(String what) {
        Log.v(TAG + "[" + mName + "]", what);
    }

}