001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.named.support;
020
021import java.util.ArrayDeque;
022import java.util.Deque;
023import java.util.concurrent.TimeUnit;
024
025/**
026 * Named lock support implementation that is using "adapted" semaphore (to be able to use semaphores not sharing common
027 * API).
028 */
029public class AdaptedSemaphoreNamedLock extends NamedLockSupport {
030    /**
031     * Wrapper for semaphore-like stuff, that do not share common ancestor. Semaphore must be created to support {@link
032     * Integer#MAX_VALUE} permissions.
033     */
034    public interface AdaptedSemaphore {
035        boolean tryAcquire(int perms, long time, TimeUnit unit) throws InterruptedException;
036
037        void release(int perms);
038    }
039
040    /**
041     * Count of permissions involved with "nop" locking. When required lock step is preceded with a step that already
042     * fulfills currently requested locking, no locking is needed. In other words, caller already possesses the access
043     * to lock protected resource. The "nop" locking is used to track proper "boxing" of lock/unlock calls.
044     */
045    private static final int NONE = 0;
046
047    /**
048     * Count of permissions involved with shared locking
049     */
050    private static final int SHARED = 1;
051
052    /**
053     * Count of permissions involved with exclusive locking
054     */
055    private static final int EXCLUSIVE = Integer.MAX_VALUE;
056
057    private final ThreadLocal<Deque<Integer>> threadPerms;
058
059    private final AdaptedSemaphore semaphore;
060
061    public AdaptedSemaphoreNamedLock(
062            final String name, final NamedLockFactorySupport factory, final AdaptedSemaphore semaphore) {
063        super(name, factory);
064        this.threadPerms = ThreadLocal.withInitial(ArrayDeque::new);
065        this.semaphore = semaphore;
066    }
067
068    @Override
069    protected boolean doLockShared(final long time, final TimeUnit unit) throws InterruptedException {
070        Deque<Integer> perms = threadPerms.get();
071        if (!perms.isEmpty()) { // we already own shared or exclusive lock
072            perms.push(NONE);
073            return true;
074        }
075        if (semaphore.tryAcquire(SHARED, time, unit)) {
076            perms.push(SHARED);
077            return true;
078        }
079        return false;
080    }
081
082    @Override
083    protected boolean doLockExclusively(final long time, final TimeUnit unit) throws InterruptedException {
084        Deque<Integer> perms = threadPerms.get();
085        if (!perms.isEmpty()) { // we already own shared or exclusive lock
086            if (perms.contains(EXCLUSIVE)) {
087                perms.push(NONE);
088                return true;
089            } else {
090                throw new LockUpgradeNotSupportedException(this); // Lock upgrade not supported
091            }
092        }
093        if (semaphore.tryAcquire(EXCLUSIVE, time, unit)) {
094            perms.push(EXCLUSIVE);
095            return true;
096        }
097        return false;
098    }
099
100    @Override
101    protected void doUnlock() {
102        Deque<Integer> steps = threadPerms.get();
103        if (steps.isEmpty()) {
104            throw new IllegalStateException("Wrong API usage: unlock without lock");
105        }
106        int step = steps.pop();
107        if (step > NONE) {
108            semaphore.release(step);
109        }
110    }
111}