Guest User

Untitled

a guest
May 22nd, 2018
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.81 KB | None | 0 0
  1. import java.util.HashMap;
  2. import java.util.Iterator;
  3. import java.util.concurrent.Semaphore;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. import org.apache.log4j.Logger;
  7.  
  8. public class LockManager {
  9. private static LockManager instance;
  10. private HashMap<String, Semaphore> map = new HashMap<String, Semaphore>();
  11. private static final String KEY_DELIMITER = "#";
  12. private static final Pattern PATTERN = Pattern.compile("(.+?)" + KEY_DELIMITER);
  13. private Logger logger = Logger.getLogger(LockManager.class);
  14.  
  15. private LockManager() {
  16. }
  17.  
  18. public static LockManager getInstance() {
  19. if (instance == null) {
  20. synchronized (LockManager.class) {
  21. // Método "double-check idiom" utilizado para sincronizar apenas
  22. // na primeira chamada do getInstance();
  23. if (instance == null) {
  24. instance = new LockManager();
  25. }
  26. }
  27. }
  28. return instance;
  29. }
  30.  
  31. public String generateKey(String key1, String key2) {
  32. return (key1 + KEY_DELIMITER + key2);
  33. }
  34.  
  35. public void acquire(String key1, String key2) throws InterruptedException {
  36. String key = generateKey(key1, key2);
  37. acquire(key);
  38. }
  39.  
  40. /*
  41. * Método responsável por instanciar e/ou adquirir o mutex/lock de acordo o
  42. * atributo key ps: Controle de concorrência por key, ou seja, cada key será
  43. * relacionada a apenas 1 mutex obrigatoriamente
  44. */
  45. public void acquire(String key) throws InterruptedException {
  46. Semaphore mutex = null;
  47. // Sincroniza o map de modo que threads relacionadas à mesma key não
  48. // insira dois registros no map
  49. synchronized (map) {
  50. mutex = map.get(key);
  51. if (mutex == null) {
  52. mutex = new Semaphore(1);
  53. map.put(key, mutex);
  54. }
  55. }
  56. // obtem o lock para o atributo key
  57. mutex.acquire();
  58. }
  59.  
  60. public void release(String key1, String key2) {
  61. String key = generateKey(key1, key2);
  62. release(key);
  63. }
  64.  
  65. /*
  66. * Método responsável por liberar o mutex de acordo com o atributo key
  67. * passado como parâmetro ps: O release deve ser sempre efetuado em algum
  68. * momento após a obtenção do lock. Caso contrário threads relacionadas à
  69. * mesma chave ficarão bloqueadas
  70. */
  71. public void release(String key) {
  72. Semaphore mutex = map.get(key);
  73. if (mutex != null) {
  74. mutex.release();
  75. }
  76. }
  77.  
  78. public void removeFinally(String pin) {
  79. if (map != null) {
  80. synchronized (map) {
  81. logger.info("Tamanho atual da estrutura de dados map: " + map.size());
  82. Iterator<String> keySet = map.keySet().iterator();
  83.  
  84. logger.info("Inicio da tentativa de limpeza do map para a ordem: " + pin);
  85. while (keySet.hasNext()) {
  86. String key = keySet.next();
  87. String mapPin = getPinFromKey(key);
  88. try {
  89. if (mapPin.equals(pin)) {
  90. // Obtém o mutex com base na key e o libera, caso o
  91. // mesmo esteja bloqueado.
  92. Semaphore mutex = map.get(key);
  93. mutex.release();
  94. // remove a key do map
  95. keySet.remove();
  96. }
  97. } catch (Exception e) {
  98. logger.error(e.getMessage(), e);
  99. }
  100. }
  101. }
  102. }
  103. }
  104.  
  105. public String getPinFromKey(String key) {
  106. String pin = "";
  107. Matcher matcher = PATTERN.matcher(key);
  108.  
  109. if (matcher.find()) {
  110. pin = matcher.group(1);
  111. }
  112.  
  113. return pin;
  114. }
  115.  
  116. /**
  117. * Faz a limpeza da variável de instância "map" declarada na classe
  118. * LockManager.
  119. */
  120. public class ClearMap implements Runnable {
  121. private boolean keepAlive = true;
  122. private long sleepTime = 1800000;
  123.  
  124. @Override
  125. public void run() {
  126. try {
  127. while (keepAlive) {
  128. Thread.sleep(sleepTime);
  129.  
  130. synchronized (map) {
  131. logger.info("Limpando o mapa de sincronização de sessões. Tamanho atual: " + map.size());
  132. map.clear();
  133. }
  134. }
  135. } catch (InterruptedException e) {
  136. logger.error(e.getMessage(), e);
  137. }
  138. }
  139.  
  140. public void setKeepAlive(boolean _keepAlive) {
  141. this.keepAlive = _keepAlive;
  142. }
  143.  
  144. public void setSleepTime(long _sleepTime) {
  145. this.sleepTime = _sleepTime;
  146. }
  147. }
  148. }
Add Comment
Please, Sign In to add comment