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 static final Lock LOCKED = new Lock();
37 private final ReentrantLock _lock = new ReentrantLock();
38 private final Lock _unlock = new UnLock();
39
40 public Locker()
41 {
42 }
43
44 public Lock lock()
45 {
46 if (_lock.isHeldByCurrentThread())
47 throw new IllegalStateException("Locker is not reentrant");
48 _lock.lock();
49 return _unlock;
50 }
51
52 public Lock lockIfNotHeld ()
53 {
54 if (_lock.isHeldByCurrentThread())
55 return LOCKED;
56 _lock.lock();
57 return _unlock;
58 }
59
60 public boolean isLocked()
61 {
62 return _lock.isLocked();
63 }
64
65 public static class Lock implements AutoCloseable
66 {
67 @Override
68 public void close()
69 {
70 }
71 }
72
73 public class UnLock extends Lock
74 {
75 @Override
76 public void close()
77 {
78 _lock.unlock();
79 }
80 }
81
82 public Condition newCondition()
83 {
84 return _lock.newCondition();
85 }
86 }