Newer
Older
gitbucket_jkp / src / main / scala / util / LockUtil.scala
@takezoe takezoe on 21 Sep 2013 760 bytes Use ControlUtil.
  1. package util
  2.  
  3. import java.util.concurrent.ConcurrentHashMap
  4. import java.util.concurrent.locks.{ReentrantLock, Lock}
  5. import util.ControlUtil._
  6.  
  7. object LockUtil {
  8.  
  9. /**
  10. * lock objects
  11. */
  12. private val locks = new ConcurrentHashMap[String, Lock]()
  13.  
  14. /**
  15. * Returns the lock object for the specified repository.
  16. */
  17. private def getLockObject(key: String): Lock = synchronized {
  18. if(!locks.containsKey(key)){
  19. locks.put(key, new ReentrantLock())
  20. }
  21. locks.get(key)
  22. }
  23.  
  24. /**
  25. * Synchronizes a given function which modifies the working copy of the wiki repository.
  26. */
  27. def lock[T](key: String)(f: => T): T = defining(getLockObject(key)){ lock =>
  28. try {
  29. lock.lock()
  30. f
  31. } finally {
  32. lock.unlock()
  33. }
  34. }
  35.  
  36. }