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.
9 // The Eclipse Public License is available at
10 // http://www.eclipse.org/legal/epl-v10.html
12 // The Apache License v2.0 is available at
13 // http://www.opensource.org/licenses/apache2.0.php
15 // You may elect to redistribute this code under either of these licenses.
16 // ========================================================================
19 package org.eclipse.jetty.util.thread;
21 import java.util.concurrent.atomic.AtomicReference;
24 * <p>This spin lock is a lock designed to protect VERY short sections
25 * of critical code. Threads attempting to take the lock will spin
26 * forever until the lock is available, thus it is important that
27 * the code protected by this lock is extremely simple and non
28 * blocking. The reason for this lock is that it prevents a thread
29 * from giving up a CPU core when contending for the lock.</p>
31 * try(SpinLock.Lock lock = spinlock.lock())
33 * // something very quick and non blocking
36 * <p>Further analysis however, shows that spin locks behave really
37 * bad under heavy contention and where the number of threads
38 * exceeds the number of cores, which are common scenarios for a
39 * server, so this class was removed from usage, preferring
40 * standard locks instead.</p>
41 * @deprecated Do not use it anymore, prefer normal locks
46 private final AtomicReference<Thread> _lock = new AtomicReference<>(null);
47 private final Lock _unlock = new Lock();
51 Thread thread = Thread.currentThread();
54 if (!_lock.compareAndSet(null,thread))
56 if (_lock.get()==thread)
57 throw new IllegalStateException("SpinLock is not reentrant");
64 public boolean isLocked()
66 return _lock.get()!=null;
69 public boolean isLockedThread()
71 return _lock.get()==Thread.currentThread();
74 public class Lock implements AutoCloseable