001/**
002 * Copyright (c) 2015-2022, Michael Yang 杨福海 (fuhai999@gmail.com).
003 * <p>
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 * <p>
008 * http://www.apache.org/licenses/LICENSE-2.0
009 * <p>
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package io.jboot.objects.lock.impl;
017
018import io.jboot.objects.lock.JbootLock;
019
020import java.util.HashMap;
021import java.util.Map;
022import java.util.concurrent.TimeUnit;
023import java.util.concurrent.locks.Condition;
024import java.util.concurrent.locks.ReentrantLock;
025
026/**
027 * @author michael yang (fuhai999@gmail.com)
028 * @Date: 2020/3/7
029 */
030public class JbootLocalLock implements JbootLock {
031
032    private static Map<String, ReentrantLock> LOCKS = new HashMap<>();
033
034    private ReentrantLock lock;
035
036    public JbootLocalLock(String name) {
037        lock = LOCKS.get(name);
038        if (lock == null) {
039            synchronized (JbootLocalLock.class) {
040                lock = LOCKS.get(name);
041                if (lock == null) {
042                    lock = new ReentrantLock();
043                    LOCKS.put(name, lock);
044                }
045            }
046        }
047    }
048
049    @Override
050    public void lock() {
051        lock.lock();
052    }
053
054    @Override
055    public void lockInterruptibly() throws InterruptedException {
056        lock.lockInterruptibly();
057    }
058
059    @Override
060    public boolean tryLock() {
061        return lock.tryLock();
062    }
063
064    @Override
065    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
066        return lock.tryLock(time, unit);
067    }
068
069    @Override
070    public void unlock() {
071        lock.unlock();
072    }
073
074    @Override
075    public Condition newCondition() {
076        return lock.newCondition();
077    }
078}