1 //
2 // ========================================================================
3 // Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4 // ------------------------------------------------------------------------
5 // All rights reserved. This program and the accompanying materials
6 // are made available under the terms of the Eclipse Public License v1.0
7 // and Apache License v2.0 which accompanies this distribution.
8 //
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
11 //
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
14 //
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
17 //
18
19 package org.eclipse.jetty.util.thread;
20
21 import java.util.concurrent.locks.Condition;
22 import java.util.concurrent.locks.ReentrantLock;
23
24 /**
25 * Convenience Lock Wrapper.
26 *
27 * <pre>
28 * try(Locker.Lock lock = locker.lock())
29 * {
30 * // something
31 * }
32 * </pre>
33 */
34 public class Locker
35 {
36 private final ReentrantLock _lock = new ReentrantLock();
37 private final Lock _unlock = new Lock();
38
39 public Locker()
40 {
41 }
42
43 public Lock lock()
44 {
45 if (_lock.isHeldByCurrentThread())
46 throw new IllegalStateException("Locker is not reentrant");
47 _lock.lock();
48 return _unlock;
49 }
50
51 public boolean isLocked()
52 {
53 return _lock.isLocked();
54 }
55
56 public class Lock implements AutoCloseable
57 {
58 @Override
59 public void close()
60 {
61 _lock.unlock();
62 }
63 }
64
65 public Condition newCondition()
66 {
67 return _lock.newCondition();
68 }
69 }