001package org.eclipse.aether.named.redisson;
002
003/*
004 * Licensed to the Apache Software Foundation (ASF) under one
005 * or more contributor license agreements.  See the NOTICE file
006 * distributed with this work for additional information
007 * regarding copyright ownership.  The ASF licenses this file
008 * to you under the Apache License, Version 2.0 (the
009 * "License"); you may not use this file except in compliance
010 * with the License.  You may obtain a copy of the License at
011 *
012 *  http://www.apache.org/licenses/LICENSE-2.0
013 *
014 * Unless required by applicable law or agreed to in writing,
015 * software distributed under the License is distributed on an
016 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
017 * KIND, either express or implied.  See the License for the
018 * specific language governing permissions and limitations
019 * under the License.
020 */
021
022import org.eclipse.aether.named.support.AdaptedSemaphoreNamedLock;
023import org.eclipse.aether.named.support.NamedLockSupport;
024import org.redisson.api.RSemaphore;
025
026import javax.inject.Named;
027import javax.inject.Singleton;
028import java.util.concurrent.TimeUnit;
029
030/**
031 * Provider of {@link RedissonSemaphoreNamedLockFactory} using Redisson and {@link org.redisson.api.RSemaphore}.
032 */
033@Singleton
034@Named( RedissonSemaphoreNamedLockFactory.NAME )
035public class RedissonSemaphoreNamedLockFactory
036    extends RedissonNamedLockFactorySupport
037{
038    public static final String NAME = "semaphore-redisson";
039
040    @Override
041    protected NamedLockSupport createLock( final String name )
042    {
043        return new AdaptedSemaphoreNamedLock(
044                   name, this, new RedissonSemaphore( redissonClient.getSemaphore( NAME_PREFIX + name ) )
045    );
046    }
047
048    private static final class RedissonSemaphore implements AdaptedSemaphoreNamedLock.AdaptedSemaphore
049    {
050        private final RSemaphore semaphore;
051
052        private RedissonSemaphore( final RSemaphore semaphore )
053        {
054            semaphore.trySetPermits( Integer.MAX_VALUE );
055            this.semaphore = semaphore;
056        }
057
058        @Override
059        public boolean tryAcquire( final int perms, final long time, final TimeUnit unit )
060            throws InterruptedException
061        {
062            return semaphore.tryAcquire( perms, time, unit );
063        }
064
065        @Override
066        public void release( final int perms )
067        {
068            semaphore.release( perms );
069        }
070    }
071}