package com.ruoyi.mxjb.util;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;

public class DataLocker {
    private Map<Long, SemaphoreDataLocker> concurrentSemaphoreMap = Collections.synchronizedMap(new HashMap());


    /**
     * 获取临界区，并记录申请的个数
     *
     * @param id
     * @return
     */
    public SemaphoreDataLocker getSemaphore(Long id) {
        synchronized (concurrentSemaphoreMap) {
            SemaphoreDataLocker semaphoreWithCount = concurrentSemaphoreMap.get(id);
            if (semaphoreWithCount == null) {
                semaphoreWithCount = new SemaphoreDataLocker(id);
                concurrentSemaphoreMap.put(id, semaphoreWithCount);
            } else {
                semaphoreWithCount.count++;
            }
            return semaphoreWithCount;
        }
    }

    public void freeSemaphore(SemaphoreDataLocker semaphoreWithCount) {
        if (null == semaphoreWithCount) {
            return;
        }
        synchronized (concurrentSemaphoreMap) {
            semaphoreWithCount.count--;
            if (0 == semaphoreWithCount.count) {
                concurrentSemaphoreMap.remove(semaphoreWithCount.id);
            }
        }
    }

    public static class SemaphoreDataLocker extends Semaphore {
        Long id;
        Integer count;

        public SemaphoreDataLocker(Long id) {
            super(1);
            this.count = 1;
            this.id = id;
        }
    }
}
