DataLocker.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. package com.ruoyi.mxjb.util;
  2. import java.util.Collections;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. import java.util.concurrent.Semaphore;
  6. public class DataLocker {
  7. private Map<Long, SemaphoreDataLocker> concurrentSemaphoreMap = Collections.synchronizedMap(new HashMap());
  8. /**
  9. * 获取临界区,并记录申请的个数
  10. *
  11. * @param id
  12. * @return
  13. */
  14. public SemaphoreDataLocker getSemaphore(Long id) {
  15. synchronized (concurrentSemaphoreMap) {
  16. SemaphoreDataLocker semaphoreWithCount = concurrentSemaphoreMap.get(id);
  17. if (semaphoreWithCount == null) {
  18. semaphoreWithCount = new SemaphoreDataLocker(id);
  19. concurrentSemaphoreMap.put(id, semaphoreWithCount);
  20. } else {
  21. semaphoreWithCount.count++;
  22. }
  23. return semaphoreWithCount;
  24. }
  25. }
  26. public void freeSemaphore(SemaphoreDataLocker semaphoreWithCount) {
  27. if (null == semaphoreWithCount) {
  28. return;
  29. }
  30. synchronized (concurrentSemaphoreMap) {
  31. semaphoreWithCount.count--;
  32. if (0 == semaphoreWithCount.count) {
  33. concurrentSemaphoreMap.remove(semaphoreWithCount.id);
  34. }
  35. }
  36. }
  37. public static class SemaphoreDataLocker extends Semaphore {
  38. Long id;
  39. Integer count;
  40. public SemaphoreDataLocker(Long id) {
  41. super(1);
  42. this.count = 1;
  43. this.id = id;
  44. }
  45. }
  46. }