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
025import org.eclipse.aether.named.NamedLockKey;
026
027/**
028 * Named lock support implementation that is using "adapted" semaphore (to be able to use semaphores not sharing common
029 * API).
030 */
031public class AdaptedSemaphoreNamedLock extends NamedLockSupport {
032    /**
033     * Wrapper for semaphore-like stuff, that do not share common ancestor. Semaphore must be created to support {@link
034     * Integer#MAX_VALUE} permissions.
035     */
036    public interface AdaptedSemaphore {
037        boolean tryAcquire(int perms, long time, TimeUnit unit) throws InterruptedException;
038
039        void release(int perms);
040    }
041
042    /**
043     * Count of permissions involved with "nop" locking. When required lock step is preceded with a step that already
044     * fulfills currently requested locking, no locking is needed. In other words, caller already possesses the access
045     * to lock protected resource. The "nop" locking is used to track proper "boxing" of lock/unlock calls.
046     */
047    private static final int NONE = 0;
048
049    /**
050     * Count of permissions involved with shared locking
051     */
052    private static final int SHARED = 1;
053
054    /**
055     * Count of permissions involved with exclusive locking
056     */
057    private static final int EXCLUSIVE = Integer.MAX_VALUE;
058
059    private final ThreadLocal<Deque<Integer>> threadPerms;
060
061    private final AdaptedSemaphore semaphore;
062
063    public AdaptedSemaphoreNamedLock(
064            final NamedLockKey key, final NamedLockFactorySupport factory, final AdaptedSemaphore semaphore) {
065        super(key, factory);
066        this.threadPerms = ThreadLocal.withInitial(ArrayDeque::new);
067        this.semaphore = semaphore;
068    }
069
070    @Override
071    protected boolean doLockShared(final long time, final TimeUnit unit) throws InterruptedException {
072        Deque<Integer> perms = threadPerms.get();
073        if (!perms.isEmpty()) { // we already own shared or exclusive lock
074            perms.push(NONE);
075            return true;
076        }
077        if (semaphore.tryAcquire(SHARED, time, unit)) {
078            perms.push(SHARED);
079            return true;
080        }
081        return false;
082    }
083
084    @Override
085    protected boolean doLockExclusively(final long time, final TimeUnit unit) throws InterruptedException {
086        Deque<Integer> perms = threadPerms.get();
087        if (!perms.isEmpty()) { // we already own shared or exclusive lock
088            if (perms.contains(EXCLUSIVE)) {
089                perms.push(NONE);
090                return true;
091            } else {
092                throw new LockUpgradeNotSupportedException(this); // Lock upgrade not supported
093            }
094        }
095        if (semaphore.tryAcquire(EXCLUSIVE, time, unit)) {
096            perms.push(EXCLUSIVE);
097            return true;
098        }
099        return false;
100    }
101
102    @Override
103    protected void doUnlock() {
104        Deque<Integer> steps = threadPerms.get();
105        if (steps.isEmpty()) {
106            throw new IllegalStateException("Wrong API usage: unlock without lock");
107        }
108        int step = steps.pop();
109        if (step > NONE) {
110            semaphore.release(step);
111        }
112    }
113}