Java Code Examples for java.util.concurrent.locks.ReentrantReadWriteLock

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project org.openscada.atlantis, under directory /org.openscada.da.server.common/src/org/openscada/da/server/common/impl/.

Source file: HiveCommon.java

  32 
vote

public HiveCommon(){
  final ReentrantReadWriteLock itemMapLock=new ReentrantReadWriteLock(Boolean.getBoolean("org.openscada.da.server.common.fairItemMapLock"));
  this.itemMapReadLock=itemMapLock.readLock();
  this.itemMapWriteLock=itemMapLock.writeLock();
  this.itemSubscriptionManager.setValidator(new SubscriptionValidator(){
    @Override public boolean validate(    final SubscriptionListener listener,    final Object topic){
      return validateItem(topic.toString());
    }
  }
);
}
 

Example 2

From project airlift, under directory /stats/src/main/java/io/airlift/stats/.

Source file: ExponentiallyDecayingSample.java

  31 
vote

/** 
 * Creates a new  {@link ExponentiallyDecayingSample}.
 * @param reservoirSize the number of samples to keep in the samplingreservoir
 * @param alpha the exponential decay factor; the higher this is, the morebiased the sample will be towards newer values
 */
public ExponentiallyDecayingSample(int reservoirSize,double alpha){
  this.values=new ConcurrentSkipListMap<Double,Long>();
  this.lock=new ReentrantReadWriteLock();
  this.alpha=alpha;
  this.reservoirSize=reservoirSize;
  clear();
}
 

Example 3

From project azkaban, under directory /azkaban/src/java/azkaban/jobcontrol/impl/jobs/locks/.

Source file: ReadWriteLockManager.java

  31 
vote

public ReadWriteResourceLock getReadLock(Object resource){
  ReadWriteLock rwl=_readWriteLockMap.get(resource);
  if (rwl == null) {
    rwl=new ReentrantReadWriteLock(_isFair);
    _readWriteLockMap.put(resource,rwl);
  }
  return new ReadWriteResourceLock(resource,rwl,false);
}
 

Example 4

From project bonecp, under directory /bonecp/src/test/java/com/jolbox/bonecp/.

Source file: TestConnectionPartition.java

  31 
vote

/** 
 * Test method for created connections.
 * @throws NoSuchFieldException 
 * @throws SecurityException 
 * @throws IllegalAccessException 
 * @throws IllegalArgumentException 
 */
@Test public void testUpdateCreatedConnectionsWithException() throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
  ReentrantReadWriteLock mockLock=createNiceMock(ReentrantReadWriteLock.class);
  WriteLock mockWriteLock=createNiceMock(WriteLock.class);
  Field field=testClass.getClass().getDeclaredField("statsLock");
  field.setAccessible(true);
  ReentrantReadWriteLock oldLock=(ReentrantReadWriteLock)field.get(testClass);
  field.set(testClass,mockLock);
  expect(mockLock.writeLock()).andThrow(new RuntimeException()).once().andReturn(mockWriteLock).once();
  mockWriteLock.lock();
  expectLastCall().once();
  replay(mockLock,mockWriteLock);
  try {
    testClass.updateCreatedConnections(5);
    fail("Should have thrown an exception");
  }
 catch (  Throwable t) {
  }
  verify(mockLock);
  field.set(testClass,oldLock);
}
 

Example 5

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: MultiFn.java

  31 
vote

public MultiFn(String name,IFn dispatchFn,Object defaultDispatchVal,IRef hierarchy){
  this.rw=new ReentrantReadWriteLock();
  this.name=name;
  this.dispatchFn=dispatchFn;
  this.defaultDispatchVal=defaultDispatchVal;
  this.methodTable=PersistentHashMap.EMPTY;
  this.methodCache=getMethodTable();
  this.preferTable=PersistentHashMap.EMPTY;
  this.hierarchy=hierarchy;
  cachedHierarchy=null;
}
 

Example 6

From project Diver, under directory /ca.uvic.chisel.javasketch/src/ca/uvic/chisel/javasketch/internal/interest/.

Source file: ReconnaissanceFiltering.java

  31 
vote

/** 
 */
public ReconnaissanceFiltering(){
  lock=new ReentrantReadWriteLock();
  active=null;
  hidden=Collections.synchronizedSet(new HashSet<DBProgramSketch>());
  trees=Collections.synchronizedMap(new HashMap<IThread,DatabaseThreadTree>());
}
 

Example 7

From project efflux, under directory /src/main/java/com/biasedbit/efflux/participant/.

Source file: DefaultParticipantDatabase.java

  31 
vote

public DefaultParticipantDatabase(String id,ParticipantEventListener eventListener){
  this.id=id;
  this.listener=eventListener;
  this.receivers=new ArrayList<RtpParticipant>();
  this.members=new HashMap<Long,RtpParticipant>();
  this.lock=new ReentrantReadWriteLock();
  this.timeoutAfterNoPacketsReceived=TIMEOUT_AFTER_NO_PACKETS_RECEIVED;
  this.timeoutAfterByeAndNoPacketsReceived=TIMEOUT_AFTER_BYE_AND_NO_PACKETS_RECEIVED;
}
 

Example 8

From project hotpotato, under directory /src/main/java/com/biasedbit/hotpotato/session/.

Source file: DefaultHttpSession.java

  31 
vote

public DefaultHttpSession(HttpClient client,HttpClient httpsClient){
  if (client.isHttps()) {
    throw new IllegalArgumentException("HTTP client must not have SSL (HTTPS) support active");
  }
  if ((httpsClient != null) && !httpsClient.isHttps()) {
    throw new IllegalArgumentException("HTTPS client must have SSL (HTTPS) support active");
  }
  this.maxRedirects=MAX_REDIRECTS;
  this.client=client;
  this.httpsClient=httpsClient;
  ReentrantReadWriteLock rwLock=new ReentrantReadWriteLock();
  this.headerReadLock=rwLock.readLock();
  this.headerWriteLock=rwLock.writeLock();
  this.headers=new ArrayList<Map.Entry<String,String>>();
  this.handlers=new ConcurrentHashMap<Integer,ResponseCodeHandler>();
  this.addHandler(new AuthenticationResponseHandler());
  this.addHandler(new RedirectResponseHandler());
}
 

Example 9

From project james-mailbox, under directory /store/src/main/java/org/apache/james/mailbox/store/.

Source file: JVMMailboxPathLocker.java

  31 
vote

/** 
 * @see org.apache.james.mailbox.store.AbstractMailboxPathLocker#lock(org.apache.james.mailbox.MailboxSession,org.apache.james.mailbox.model.MailboxPath,boolean)
 */
protected void lock(MailboxSession session,MailboxPath path,boolean writeLock) throws MailboxException {
  ReadWriteLock lock=paths.get(path);
  if (lock == null) {
    lock=new ReentrantReadWriteLock();
    ReadWriteLock storedLock=paths.putIfAbsent(path,lock);
    if (storedLock != null) {
      lock=storedLock;
    }
  }
  getLock(lock,writeLock).lock();
}
 

Example 10

From project jboss-jsf-api_spec, under directory /src/main/java/javax/faces/.

Source file: FactoryFinder.java

  31 
vote

public FactoryManager(){
  lock=new ReentrantReadWriteLock(true);
  factories=new HashMap<String,Object>();
  savedFactoryNames=new HashMap<String,List<String>>();
  for (  String name : FACTORY_NAMES) {
    factories.put(name,new ArrayList(4));
  }
}
 

Example 11

From project moji, under directory /src/main/java/fm/last/moji/impl/.

Source file: MojiFileImpl.java

  31 
vote

MojiFileImpl(String key,String domain,String storageClass,TrackerFactory trackerFactory,HttpConnectionFactory httpFactory){
  this.key=key;
  this.domain=domain;
  this.storageClass=storageClass;
  this.trackerFactory=trackerFactory;
  this.httpFactory=httpFactory;
  executor=new Executor(trackerFactory);
  lock=new ReentrantReadWriteLock();
}
 

Example 12

From project nuxeo-tycho-osgi, under directory /nuxeo-runtime/nuxeo-runtime/src/main/java/org/nuxeo/runtime/model/impl/.

Source file: ComponentPersistence.java

  31 
vote

public ComponentPersistence(OSGiRuntimeService runtime){
  this.runtime=runtime;
  root=new File(Environment.getDefault().getData(),"components");
  fileLock=new ReentrantReadWriteLock();
  sysrc=runtime.getContext();
  persistedComponents=Collections.synchronizedSet(new HashSet<RegistrationInfo>());
}
 

Example 13

From project org.openscada.aurora, under directory /org.openscada.hsdb.testing/src/org/openscada/hsdb/testing/backend/.

Source file: FileBackEndTest.java

  31 
vote

/** 
 * This method creates, initializes and returns the backend that has to be tested. If a backend with the same meta data already exists, the old back end will be deleted.
 * @param metaData metadata that should be used when creating a back end
 * @return backend that has to be tested
 * @throws Exception in case of problems
 */
@Override protected BackEnd createBackEnd(final StorageChannelMetaData metaData) throws Exception {
  final FileBackEnd backEnd=new FileBackEnd(URLEncoder.encode(metaData.getConfigurationId(),"utf-8") + ".va",false);
  new File(backEnd.getFileName()).delete();
  backEnd.setLock(new ReentrantReadWriteLock());
  backEnd.create(metaData);
  backEnd.initialize(metaData);
  return backEnd;
}
 

Example 14

From project org.ops4j.pax.logging, under directory /pax-logging-service/src/main/java/org/ops4j/pax/logging/service/internal/.

Source file: PaxLoggingServiceImpl.java

  31 
vote

public PaxLoggingServiceImpl(BundleContext context,LogReaderServiceImpl logReader,EventAdminPoster eventAdmin){
  m_bundleContext=context;
  m_logReader=logReader;
  m_eventAdmin=eventAdmin;
  m_context=new PaxContext();
  m_configLock=new ReentrantReadWriteLock();
  m_julLoggers=new LinkedList();
  configureDefaults();
}
 

Example 15

From project org.ops4j.pax.web, under directory /pax-web-spi/src/main/java/org/ops4j/pax/web/service/spi/model/.

Source file: ServerModel.java

  31 
vote

/** 
 * Constructor.
 */
public ServerModel(){
  m_aliasMapping=new HashMap<String,ServletModel>();
  m_servlets=new HashSet<Servlet>();
  m_servletUrlPatterns=new HashMap<String,UrlPattern>();
  m_filterUrlPatterns=new ConcurrentHashMap<String,UrlPattern>();
  m_httpContexts=new ConcurrentHashMap<HttpContext,Bundle>();
  containerInitializers=new ConcurrentHashMap<ServletContainerInitializer,ContainerInitializerModel>();
  m_servletLock=new ReentrantReadWriteLock(true);
}
 

Example 16

From project p2-bridge, under directory /eclipse-bridge/src/main/java/org/sonatype/eclipse/bridge/internal/.

Source file: DefaultEclipseInstance.java

  31 
vote

public Started(){
  activeServices=new HashMap<WeakReference<?>,ServiceReference>();
  staleReferences=new ReferenceQueue<Object>();
  lock=new ReentrantReadWriteLock();
  cleanupThread=new Thread(new Cleanup(),"Stale Eclipse services cleanup");
  cleanupThread.start();
}
 

Example 17

From project platform_3, under directory /stats/src/main/java/com/proofpoint/stats/.

Source file: ExponentiallyDecayingSample.java

  31 
vote

/** 
 * Creates a new  {@link ExponentiallyDecayingSample}.
 * @param reservoirSize the number of samples to keep in the samplingreservoir
 * @param alpha the exponential decay factor; the higher this is, the morebiased the sample will be towards newer values
 */
public ExponentiallyDecayingSample(int reservoirSize,double alpha){
  this.values=new ConcurrentSkipListMap<Double,Long>();
  this.lock=new ReentrantReadWriteLock();
  this.alpha=alpha;
  this.reservoirSize=reservoirSize;
  clear();
}
 

Example 18

From project rate-limit, under directory /src/main/java/com/eternus/ratelimit/.

Source file: MemoryTokenStore.java

  31 
vote

/** 
 * Creates a new  {@link MemoryTokenStore}.
 */
public MemoryTokenStore(){
  this.cache=new MapMaker().softValues().expiration(120,TimeUnit.SECONDS).makeMap();
  ReadWriteLock lock=new ReentrantReadWriteLock();
  this.r=lock.readLock();
  this.w=lock.writeLock();
}
 

Example 19

From project Solbase-Solr, under directory /src/java/org/apache/solr/update/.

Source file: DirectUpdateHandler2.java

  31 
vote

public DirectUpdateHandler2(SolrCore core) throws IOException {
  super(core);
  ReadWriteLock rwl=new ReentrantReadWriteLock();
  iwAccess=rwl.readLock();
  iwCommit=rwl.writeLock();
  tracker=new CommitTracker();
}
 

Example 20

From project spring-security-saml, under directory /saml2-core/src/main/java/org/springframework/security/saml/trust/.

Source file: PKIXInformationResolver.java

  31 
vote

/** 
 * Constructor.
 * @param metadataResolver resolver used to extract basic credentials out of metadata
 * @param metadataProvider provider of the metadata used to load extended metadata for an entity
 * @param keyManager       key manager
 * @throws IllegalArgumentException thrown if the supplied provider is null
 */
public PKIXInformationResolver(MetadataCredentialResolver metadataResolver,MetadataManager metadataProvider,KeyManager keyManager){
  if (metadataProvider == null) {
    throw new IllegalArgumentException("Metadata provider may not be null");
  }
  this.metadataResolver=metadataResolver;
  this.metadata=metadataProvider;
  this.keyManager=keyManager;
  this.cache=new HashMap<MetadataCacheKey,SoftReference<Collection<PKIXValidationInformation>>>();
  this.rwlock=new ReentrantReadWriteLock();
  this.metadata.getObservers().add(new MetadataProviderObserver());
}
 

Example 21

From project sulky, under directory /sulky-buffers-filtering/src/main/java/de/huxhorn/sulky/buffers/filtering/.

Source file: FilteringBuffer.java

  31 
vote

public FilteringBuffer(Buffer<E> sourceBuffer,Condition condition){
  this.indicesLock=new ReentrantReadWriteLock(true);
  this.sourceBuffer=sourceBuffer;
  this.condition=condition;
  this.filteredIndices=new ArrayList<Long>();
  this.disposed=false;
}
 

Example 22

From project VolD, under directory /server/src/main/java/de/zib/vold/frontend/.

Source file: Frontend.java

  31 
vote

/** 
 * Construct an uninitialized Frontend.
 */
public Frontend(){
  this.volatileDirectory=null;
  this.rwlock=new ReentrantReadWriteLock(true);
  setRecursiveScopeLookups(true);
  setPrefixLookupsAllowed(true);
}
 

Example 23

From project CouchbaseMock, under directory /src/main/java/org/couchbase/mock/.

Source file: Bucket.java

  30 
vote

public Bucket(String name,String hostname,int port,int numNodes,int bucketStartPort,int numVBuckets,CouchbaseMock cluster,String password) throws IOException {
  this.cluster=cluster;
  this.name=name;
  this.numVBuckets=numVBuckets;
  this.password=password;
  datastore=new DataStore(numVBuckets);
  servers=new MemcachedServer[numNodes];
  this.configurationRwLock=new ReentrantReadWriteLock();
  BucketType type;
  if (this.getClass() == MemcacheBucket.class) {
    type=BucketType.MEMCACHE;
  }
 else   if (this.getClass() == CouchbaseBucket.class) {
    type=BucketType.COUCHBASE;
  }
 else {
    throw new FileNotFoundException("I don't know about this type...");
  }
  for (int ii=0; ii < servers.length; ii++) {
    servers[ii]=new MemcachedServer(this,hostname,(bucketStartPort == 0 ? 0 : bucketStartPort + ii),datastore);
  }
  rebalance();
}
 

Example 24

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/job/.

Source file: JobInAppMaster.java

  30 
vote

public JobInAppMaster(JobId jobId,Configuration conf,AppContext appContext){
  this.applicationAttemptId=appContext.getApplicationAttemptId();
  this.jobId=jobId;
  this.jobName=conf.get(DragonJobConfig.JOB_NAME,"<missing job name>");
  this.conf=new Configuration(conf);
  this.metrics=appContext.getMetrics();
  this.clock=appContext.getClock();
  this.amInfos=appContext.getAmInfos();
  this.appContext=appContext;
  this.userName=appContext.getUser();
  this.queueName=conf.get(DragonJobConfig.QUEUE_NAME,"default");
  this.appSubmitTime=appContext.getStartTime();
  this.eventHandler=appContext.getEventHandler();
  ReadWriteLock readWriteLock=new ReentrantReadWriteLock();
  this.readLock=readWriteLock.readLock();
  this.writeLock=readWriteLock.writeLock();
  this.fsTokens=appContext.getFsTokens();
  this.jobTokenSecretManager=appContext.getJobTokenSecretManager();
  this.username=conf.get(DragonJobConfig.USER_NAME);
  this.mapNumTasks=conf.getInt(DragonJobConfig.MAP_PARALLELISM,1);
  this.reduceNumTasks=conf.getInt(DragonJobConfig.REDUCE_PARALLELISM,1);
  stateMachine=stateMachineFactory.make(this);
}
 

Example 25

From project EMF-IncQuery, under directory /plugins/org.eclipse.viatra2.gtasm.patternmatcher.incremental.rete/src/org/eclipse/viatra2/gtasm/patternmatcher/incremental/rete/network/.

Source file: Network.java

  30 
vote

/** 
 * @param threads the number of threads to operate the network with; 0 means single-threaded operation,  1 starts an asynchronous thread to operate the RETE net,  >1 uses multiple RETE containers.
 */
public Network(int threads,IPatternMatcherRuntimeContext<?> context){
  super();
  this.threads=threads;
  this.context=context;
  containers=new ArrayList<ReteContainer>();
  firstContainer=(threads > 1) ? Options.firstFreeContainer : 0;
  nextContainer=firstContainer;
  if (threads > 0) {
    globalTerminationCriteria=new HashMap<ReteContainer,Long>();
    reportedClocks=new HashMap<ReteContainer,Long>();
    ReadWriteLock rwl=new ReentrantReadWriteLock();
    updateLock=rwl.readLock();
    structuralChangeLock=rwl.writeLock();
    for (int i=0; i < threads; ++i)     containers.add(new ReteContainer(this,true));
  }
 else   containers.add(new ReteContainer(this,false));
  headContainer=containers.get(0);
}
 

Example 26

From project floodlight, under directory /src/main/java/net/floodlightcontroller/core/internal/.

Source file: OFSwitchImpl.java

  30 
vote

public OFSwitchImpl(){
  this.attributes=new ConcurrentHashMap<Object,Object>();
  this.connectedSince=new Date();
  this.transactionIdSource=new AtomicInteger();
  this.portLock=new Object();
  this.portsByNumber=new ConcurrentHashMap<Short,OFPhysicalPort>();
  this.portsByName=new ConcurrentHashMap<String,OFPhysicalPort>();
  this.connected=true;
  this.statsFutureMap=new ConcurrentHashMap<Integer,OFStatisticsFuture>();
  this.iofMsgListenersMap=new ConcurrentHashMap<Integer,IOFMessageListener>();
  this.role=null;
  this.timedCache=new TimedCache<Long>(100,5 * 1000);
  this.listenerLock=new ReentrantReadWriteLock();
  this.portBroadcastCacheHitMap=new ConcurrentHashMap<Short,Long>();
  this.pendingRoleRequests=new LinkedList<OFSwitchImpl.PendingRoleRequestEntry>();
  this.setAttribute(PROP_FASTWILDCARDS,OFMatch.OFPFW_ALL);
  this.setAttribute(PROP_SUPPORTS_OFPP_FLOOD,new Boolean(true));
  this.setAttribute(PROP_SUPPORTS_OFPP_TABLE,new Boolean(true));
}
 

Example 27

From project indextank-engine, under directory /src/main/java/com/flaptor/indextank/index/lsi/.

Source file: LargeScaleIndex.java

  30 
vote

/** 
 * Create an LSI and its components
 * @param scorer The scorer to use when ranking results
 * @param parser 
 * @param basePath The base path (a directory) from the which all the LSI directories will be found.   
 */
public LargeScaleIndex(Scorer scorer,IndexEngineParser parser,File baseDir,FacetingManager facetingManager){
  Preconditions.checkNotNull(scorer);
  Preconditions.checkNotNull(parser);
  Preconditions.checkNotNull(baseDir);
  this.baseDir=baseDir;
  if (!baseDir.exists() || !baseDir.isDirectory()) {
    throw new IllegalArgumentException("The basePath must be an existing directory");
  }
  File indexDir=new File(baseDir,INDEX_DIRECTORY);
  if (!indexDir.exists()) {
    logger.info("Starting with a FRESH, BRAND NEW index.");
    indexDir.mkdir();
  }
  try {
    index=new LsiIndex(parser,indexDir.getAbsolutePath(),scorer,facetingManager);
  }
 catch (  IOException e) {
    throw new IllegalArgumentException("IOException when trying to use the directory set in the index.directory property.",e);
  }
  this.scorer=scorer;
  this.indexer=new LsiIndexer(index);
  this.searcher=new LsiSearcher(index);
  this.queue=new ArrayBlockingQueue<Operation>(1000);
  this.rwl=new ReentrantReadWriteLock();
  this.r=rwl.readLock();
  this.w=rwl.writeLock();
  this.checkpoint=false;
}
 

Example 28

From project SpoutAPI, under directory /src/main/java/org/spout/api/util/map/concurrent/.

Source file: TSyncIntIntHashMap.java

  30 
vote

/** 
 * Creates a synchronised map based on the Trove int object map
 * @param mapCount the number of sub-maps
 * @param initialCapacity the initial capacity of the map
 * @param loadFactor the load factor for the map
 * @param noEntryKey the key used to indicate a null key
 * @param noEntryValue the value used to indicate a null value
 */
public TSyncIntIntHashMap(int mapCount,int initialCapacity,float loadFactor,int noEntryKey,int noEntryValue){
  if (mapCount > 0x100000) {
    throw new IllegalArgumentException("Map count exceeds valid range");
  }
  mapCount=MathHelper.roundUpPow2(mapCount);
  mapMask=mapCount - 1;
  this.mapCount=mapCount;
  this.hashScramble=(mapCount << 8) + 1;
  mapArray=new TIntIntHashMap[mapCount];
  lockArray=new ReadWriteLock[mapCount];
  for (int i=0; i < mapCount; i++) {
    mapArray[i]=new TIntIntHashMap(initialCapacity / mapCount,loadFactor,noEntryKey,noEntryValue);
    lockArray[i]=new ReentrantReadWriteLock();
  }
  this.noEntryKey=noEntryKey;
  this.noEntryValue=noEntryValue;
}
 

Example 29

From project ubuntu-packaging-floodlight, under directory /src/main/java/net/floodlightcontroller/core/internal/.

Source file: OFSwitchImpl.java

  30 
vote

public OFSwitchImpl(){
  this.attributes=new ConcurrentHashMap<Object,Object>();
  this.connectedSince=new Date();
  this.transactionIdSource=new AtomicInteger();
  this.ports=new ConcurrentHashMap<Short,OFPhysicalPort>();
  this.switchClusterId=null;
  this.connected=true;
  this.statsFutureMap=new ConcurrentHashMap<Integer,OFStatisticsFuture>();
  this.iofMsgListenersMap=new ConcurrentHashMap<Integer,IOFMessageListener>();
  this.role=null;
  this.timedCache=new TimedCache<Long>(100,5 * 1000);
  this.listenerLock=new ReentrantReadWriteLock();
  this.portBroadcastCacheHitMap=new ConcurrentHashMap<Short,Long>();
  this.pendingRoleRequests=new LinkedList<OFSwitchImpl.PendingRoleRequestEntry>();
  this.setAttribute(PROP_FASTWILDCARDS,(Integer)OFMatch.OFPFW_ALL);
  this.setAttribute(PROP_SUPPORTS_OFPP_FLOOD,new Boolean(true));
  this.setAttribute(PROP_SUPPORTS_OFPP_TABLE,new Boolean(true));
}
 

Example 30

From project Possom, under directory /site-spi/src/main/java/no/sesat/search/site/.

Source file: AbstractSiteKeyedFactory.java

  29 
vote

/** 
 * Handles the locking pattern around the INSTANCES map that's done with a ReentrantReadWriteLock.
 * @see http://permalink.gmane.org/gmane.comp.java.sesat.kernel.devel/228
 * @param < T > the type of SiteKeyedFactory that can be constructed.
 * @param site the site this factory will answer to.
 * @param instances the map of factories of type T already in existence.
 * @param instancesLock the lock used around the instances map
 * @param constructor the wrapper around the constructor used to create factories of type T.
 * @return the singleton instance of factory of type T related to the given site.
 */
protected static final <T extends AbstractSiteKeyedFactory>T instanceOf(final Site site,final Map<Site,T> instances,final ReentrantReadWriteLock instancesLock,final FactoryConstructor<T> constructor){
  try {
    instancesLock.readLock().lock();
    if (!instances.containsKey(site)) {
      instancesLock.readLock().unlock();
      instancesLock.writeLock().lock();
      try {
        if (!instances.containsKey(site)) {
          instances.put(site,constructor.construct());
        }
      }
 catch (      SiteKeyedFactoryInstantiationException e) {
        LOG.error(constructor + ERR_DOC_BUILDER_CREATION + site,e);
      }
 finally {
        instancesLock.readLock().lock();
        instancesLock.writeLock().unlock();
      }
    }
    return instances.get(site);
  }
  finally {
    instancesLock.readLock().unlock();
  }
}