1 package org.unicode.cldr.util; 2 3 import java.util.concurrent.ConcurrentHashMap; 4 import java.util.concurrent.ConcurrentMap; 5 6 /** 7 * Helper class: Provide a way to associate a String with an Object that can be used for locking. 8 * Different instances of the same String will return the same Object 9 * 10 * @author ribnitz 11 * 12 */ 13 public class LockSupportMap<E> { 14 /** 15 * Map to keep the track of the locks used for single entries; these are used for synchronization 16 */ 17 private final ConcurrentMap<E, Object> locks = new ConcurrentHashMap<>(); 18 LockSupportMap()19 public LockSupportMap() { 20 // do nothing 21 } 22 23 /** 24 * Retrieve the object that is used to lock the entry for this filename 25 * @param fileName 26 * @return 27 */ getItemLock(E item)28 public Object getItemLock(E item) { 29 /* 30 * The putIfAbsent needs an object to insert, if it none is there, 31 * the "cheapest" object that can be created is Object. 32 */ 33 Object oldLock = new Object(); 34 Object newLock = locks.putIfAbsent(item, oldLock); 35 /* 36 * PutIfAbsent has returned the previous value, if one was there 37 * So, the oldLock needs is the value to return if newLock is null. 38 */ 39 Object sync = newLock == null ? oldLock : newLock; 40 return sync; 41 } 42 43 /** 44 * Remove the the object associated with the name from the map, and return it 45 * @param nameToRemove 46 * @return 47 */ removeItemLock(E itemToRemove)48 public Object removeItemLock(E itemToRemove) { 49 synchronized (getItemLock(itemToRemove)) { 50 return locks.remove(itemToRemove); 51 } 52 } 53 }