java.util.concurrent.locks.ReentrantReadWriteLock Java Examples

The following examples show how to use java.util.concurrent.locks.ReentrantReadWriteLock. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: neoscada   Author: eclipse   File: HiveCommon.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public HiveCommon ()
{
    final ReentrantReadWriteLock itemMapLock = new ReentrantReadWriteLock ( Boolean.getBoolean ( "org.eclipse.scada.da.server.common.fairItemMapLock" ) );

    this.itemMapReadLock = itemMapLock.readLock ();
    this.itemMapWriteLock = itemMapLock.writeLock ();

    this.subscriptionValidator = new SubscriptionValidator<String> () {

        @Override
        public boolean validate ( final SubscriptionListener<String> listener, final String topic )
        {
            return validateItem ( topic );
        }
    };
}
 
Example #2
Source Project: buffer-trigger   Author: PhantomThief   File: SimpleBufferTrigger.java    License: Artistic License 2.0 6 votes vote down vote up
SimpleBufferTrigger(SimpleBufferTriggerBuilder<E, C> builder) {
    this.queueAdder = builder.queueAdder;
    this.bufferFactory = builder.bufferFactory;
    this.consumer = builder.consumer;
    this.exceptionHandler = builder.exceptionHandler;
    this.maxBufferCount = builder.maxBufferCount;
    this.rejectHandler = builder.rejectHandler;
    this.buffer.set(this.bufferFactory.get());
    if (!builder.disableSwitchLock) {
        ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
        readLock = lock.readLock();
        writeLock = lock.writeLock();
        writeCondition = writeLock.newCondition();
    } else {
        readLock = null;
        writeLock = null;
        writeCondition = null;
    }
    builder.scheduledExecutorService.schedule(
            new TriggerRunnable(builder.scheduledExecutorService, builder.triggerStrategy),
            DEFAULT_NEXT_TRIGGER_PERIOD, MILLISECONDS);
}
 
Example #3
Source Project: scava   Author: crossminer   File: StorageDirect2.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public StorageDirect2(Volume.Factory volFac, boolean readOnly) {
    this.readOnly = readOnly;

    locks = new ReentrantReadWriteLock[CONCURRENCY_FACTOR];
    for(int i=0;i<locks.length;i++) locks[i] = new ReentrantReadWriteLock();
    freeSpaceLock = new ReentrantLock();

    index = volFac.createIndexVolume();
    phys = volFac.createPhysVolume();
    if(index.isEmpty()){
        createStructure();
    }else{
        checkHeaders();
    }

}
 
Example #4
Source Project: Aceso   Author: meili   File: AbstractPatchesLoaderImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean load() {
    try {
        InstantFixClassMap.setClassLoader(getClass().getClassLoader());
        HashMap<Integer, ReadWriteLock> lockMap = new HashMap<>();
        HashMap<Integer, String> classIndexMap = new HashMap<>();
        String[] patchedClasses = getPatchedClasses();
        int[] patchedClassIndexes = getPatchedClassIndexes();
        if (patchedClasses.length != patchedClassIndexes.length) {
            throw new IllegalArgumentException("patchedClasses's len is " + patchedClasses.length + ", but patchedClassIndexs's len is " + patchedClassIndexes.length);
        }
        for (int i = 0; i < patchedClasses.length; i++) {
            String className = patchedClasses[i];
            int classIndex = patchedClassIndexes[i];
            lockMap.put(classIndex, new ReentrantReadWriteLock());
            classIndexMap.put(classIndex, className);
            Log.i(TAG, String.format("patched %s", className));
        }
        InstantFixClassMap.setAtomMap(new InstantFixClassMap.AtomMap(classIndexMap, lockMap));
    } catch (Throwable e) {
        e.printStackTrace();
        return false;
    }
    return true;
}
 
Example #5
Source Project: hypergraphdb   Author: hypergraphdb   File: WeakRefAtomCache.java    License: Apache License 2.0 6 votes vote down vote up
private void reset()
{
    graph = null;
    incidenceCache = null;
    liveHandles = null;
    liveHandlesTx = null;
    atoms = null;
    atomsTx = null;
    frozenAtoms = null;
    coldAtoms = new ColdAtoms();
    gcLock = new ReentrantReadWriteLock();
    refQueue = new ReferenceQueue<Object>();
    cleanupThread = null;
    cleanupTxConfig = new HGTransactionConfig();
    phantomQueuePollInterval = DEFAULT_PHANTOM_QUEUE_POLL_INTERVAL;
    closing = false;
}
 
Example #6
Source Project: incubator-tez   Author: apache   File: TaskImpl.java    License: Apache License 2.0 6 votes vote down vote up
public TaskImpl(TezVertexID vertexId, int taskIndex,
    EventHandler eventHandler, Configuration conf,
    TaskAttemptListener taskAttemptListener,
    Clock clock, TaskHeartbeatHandler thh, AppContext appContext,
    boolean leafVertex, Resource resource,
    ContainerContext containerContext) {
  this.conf = conf;
  this.clock = clock;
  ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  readLock = readWriteLock.readLock();
  writeLock = readWriteLock.writeLock();
  this.attempts = Collections.emptyMap();
  // TODO Avoid reading this from configuration for each task.
  maxFailedAttempts = this.conf.getInt(TezConfiguration.TEZ_AM_TASK_MAX_FAILED_ATTEMPTS,
                            TezConfiguration.TEZ_AM_TASK_MAX_FAILED_ATTEMPTS_DEFAULT);
  taskId = TezTaskID.getInstance(vertexId, taskIndex);
  this.taskAttemptListener = taskAttemptListener;
  this.taskHeartbeatHandler = thh;
  this.eventHandler = eventHandler;
  this.appContext = appContext;

  this.leafVertex = leafVertex;
  this.taskResource = resource;
  this.containerContext = containerContext;
  stateMachine = stateMachineFactory.make(this);
}
 
Example #7
Source Project: bt   Author: atomashpolskiy   File: PeerExchangePeerSourceFactory.java    License: Apache License 2.0 6 votes vote down vote up
@Inject
public PeerExchangePeerSourceFactory(EventSource eventSource,
                                     IRuntimeLifecycleBinder lifecycleBinder,
                                     PeerExchangeConfig config) {
    this.peerSources = new ConcurrentHashMap<>();
    this.peerEvents = new ConcurrentHashMap<>();
    this.rwLock = new ReentrantReadWriteLock();
    this.peers = ConcurrentHashMap.newKeySet();
    this.lastSentPEXMessage = new ConcurrentHashMap<>();
    if (config.getMaxMessageInterval().compareTo(config.getMinMessageInterval()) < 0) {
        throw new IllegalArgumentException("Max message interval is greater than min interval");
    }
    this.minMessageInterval = config.getMinMessageInterval();
    this.maxMessageInterval = config.getMaxMessageInterval();
    this.minEventsPerMessage = config.getMinEventsPerMessage();
    this.maxEventsPerMessage = config.getMaxEventsPerMessage();

    eventSource.onPeerConnected(e -> onPeerConnected(e.getConnectionKey()))
            .onPeerDisconnected(e -> onPeerDisconnected(e.getConnectionKey()));

    ScheduledExecutorService executor =
            Executors.newSingleThreadScheduledExecutor(r -> new Thread(r, "bt.peerexchange.cleaner"));
    lifecycleBinder.onStartup("Schedule periodic cleanup of PEX messages", () -> executor.scheduleAtFixedRate(
            new Cleaner(), CLEANER_INTERVAL.toMillis(), CLEANER_INTERVAL.toMillis(), TimeUnit.MILLISECONDS));
    lifecycleBinder.onShutdown("Shutdown PEX cleanup scheduler", executor::shutdownNow);
}
 
Example #8
Source Project: hollow   Author: Netflix   File: HollowConsumer.java    License: Apache License 2.0 6 votes vote down vote up
protected  <B extends Builder<B>> HollowConsumer(B builder) {
    // duplicated with HollowConsumer(...) constructor above. We cannot chain constructor calls because that
    // constructor subscribes to the announcement watcher and we have more setup to do first
    this.metrics = new HollowConsumerMetrics();
    this.updater = new HollowClientUpdater(builder.blobRetriever,
            builder.refreshListeners,
            builder.apiFactory,
            builder.doubleSnapshotConfig,
            builder.hashCodeFinder,
            builder.objectLongevityConfig,
            builder.objectLongevityDetector,
            metrics,
            builder.metricsCollector);
    updater.setFilter(builder.typeFilter);
    this.announcementWatcher = builder.announcementWatcher;
    this.refreshExecutor = builder.refreshExecutor;
    this.refreshLock = new ReentrantReadWriteLock();
    if (announcementWatcher != null)
        announcementWatcher.subscribeToUpdates(this);
}
 
Example #9
Source Project: tajo   Author: apache   File: QueryInProgress.java    License: Apache License 2.0 6 votes vote down vote up
public QueryInProgress(
    TajoMaster.MasterContext masterContext,
    Session session,
    QueryContext queryContext,
    QueryId queryId, String sql, String jsonExpr, LogicalRootNode plan) {

  this.masterContext = masterContext;
  this.session = session;
  this.queryId = queryId;
  this.plan = plan;

  queryInfo = new QueryInfo(queryId, queryContext, sql, jsonExpr);
  queryInfo.setStartTime(System.currentTimeMillis());

  rpcParams = RpcParameterFactory.get(masterContext.getConf());

  ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
  this.readLock = readWriteLock.readLock();
  this.writeLock = readWriteLock.writeLock();
}
 
Example #10
Source Project: hbase   Author: apache   File: Segment.java    License: Apache License 2.0 6 votes vote down vote up
protected Segment(CellComparator comparator, List<ImmutableSegment> segments,
    TimeRangeTracker trt) {
  long dataSize = 0;
  long heapSize = 0;
  long OffHeapSize = 0;
  int cellsCount = 0;
  for (Segment segment : segments) {
    MemStoreSize memStoreSize = segment.getMemStoreSize();
    dataSize += memStoreSize.getDataSize();
    heapSize += memStoreSize.getHeapSize();
    OffHeapSize += memStoreSize.getOffHeapSize();
    cellsCount += memStoreSize.getCellsCount();
  }
  this.comparator = comparator;
  this.updatesLock = new ReentrantReadWriteLock();
  // Do we need to be thread safe always? What if ImmutableSegment?
  // DITTO for the TimeRangeTracker below.
  this.memStoreSizing = new ThreadSafeMemStoreSizing(dataSize, heapSize, OffHeapSize, cellsCount);
  this.timeRangeTracker = trt;
}
 
Example #11
Source Project: blazingcache   Author: diennea   File: LocalLockManager.java    License: Apache License 2.0 6 votes vote down vote up
private ReentrantReadWriteLock returnLockForKey(String key) throws IllegalStateException {
    ReentrantReadWriteLock lock;
    generalLock.lock();
    try {
        lock = liveLocks.get(key);
        if (lock == null) {
            LOGGER.log(Level.SEVERE, "no lock object exists for key {0}", key);
            throw new IllegalStateException("no lock object exists for key " + key);
        }
        int actualCount = locksCounter.get(key).decrementAndGet();
        if (actualCount == 0) {
            liveLocks.remove(key);
            locksCounter.remove(key);
        }
    } finally {
        generalLock.unlock();
    }
    return lock;
}
 
Example #12
Source Project: linstor-server   Author: LINBIT   File: SatelliteCoreModule.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void configure()
{
    bind(String.class).annotatedWith(Names.named(CoreModule.MODULE_NAME))
        .toInstance(LinStor.SATELLITE_MODULE);

    bind(ReadWriteLock.class).annotatedWith(Names.named(STLT_CONF_LOCK))
        .toInstance(new ReentrantReadWriteLock(true));

    bind(ControllerPeerConnector.class).to(ControllerPeerConnectorImpl.class);
    // bind(UpdateMonitor.class).to(UpdateMonitorImpl.class);
    // bind(DeviceManager.class).to(DeviceManagerImpl.class);
    // install(new FactoryModuleBuilder()
    //    .implement(DeviceManagerImpl.DeviceHandlerInvocation.class,
    //       DeviceManagerImpl.DeviceHandlerInvocation.class)
    //    .build(DeviceManagerImpl.DeviceHandlerInvocationFactory.class));

    bind(Path.class).annotatedWith(Names.named(DRBD_CONFIG_PATH)).toInstance(
        FileSystems.getDefault().getPath(CoreModule.CONFIG_PATH)
    );
}
 
Example #13
Source Project: gemfirexd-oss   Author: gemxd   File: SortedOplogSetImpl.java    License: Apache License 2.0 6 votes vote down vote up
public SortedOplogSetImpl(final SortedOplogFactory factory, Executor exec, Compactor ctor) throws IOException {
  this.factory = factory;
  this.flusher = new AbortableTaskService(exec);
  this.compactor = ctor;
  
  rwlock = new ReentrantReadWriteLock();
  bufferCount = new AtomicInteger(0);
  unflushed = new ArrayDeque<SortedBuffer<Integer>>();
  current = new AtomicReference<SortedBuffer<Integer>>(
      new SortedBuffer<Integer>(factory.getConfiguration(), 0));
  
  logger = ComponentLogWriter.getSoplogLogWriter(factory.getConfiguration().getName(), LogService.logger());
  if (logger.fineEnabled()) {
    logger.fine("Creating soplog set");
  }
}
 
Example #14
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: Repository.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Construct a new repository with the given default domain.
 */
public Repository(String domain, boolean fairLock) {
    lock = new ReentrantReadWriteLock(fairLock);

    domainTb = new HashMap<String,Map<String,NamedObject>>(5);

    if (domain != null && domain.length() != 0)
        this.domain = domain.intern(); // we use == domain later on...
    else
        this.domain = ServiceName.DOMAIN;

    // Creates a new hashtable for the default domain
    domainTb.put(this.domain, new HashMap<String,NamedObject>());
}
 
Example #15
Source Project: mapleLemon   Author: icelemon1314   File: MapleMap.java    License: GNU General Public License v2.0 5 votes vote down vote up
public List<MapleReactor> getAllReactorsThreadsafe() {
    ArrayList ret = new ArrayList();
    ((ReentrantReadWriteLock) this.mapobjectlocks.get(MapleMapObjectType.REACTOR)).readLock().lock();
    try {
        for (MapleMapObject mmo : mapobjects.get(MapleMapObjectType.REACTOR).values()) {
            ret.add((MapleReactor) mmo);
        }
    } finally {
        ((ReentrantReadWriteLock) this.mapobjectlocks.get(MapleMapObjectType.REACTOR)).readLock().unlock();
    }
    return ret;
}
 
Example #16
Source Project: bitcoin-verde   Author: SoftwareVerde   File: StratumMineBlockTaskBuilderCore.java    License: MIT License 5 votes vote down vote up
public StratumMineBlockTaskBuilderCore(final Integer totalExtraNonceByteCount, final TransactionDeflater transactionDeflater) {
    _totalExtraNonceByteCount = totalExtraNonceByteCount;
    _transactionDeflater = transactionDeflater;

    final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    _prototypeBlockReadLock = readWriteLock.readLock();
    _prototypeBlockWriteLock = readWriteLock.writeLock();

    _initPrototypeBlock();
}
 
Example #17
Source Project: flink   Author: apache   File: AbstractBlobCache.java    License: Apache License 2.0 5 votes vote down vote up
public AbstractBlobCache(
		final Configuration blobClientConfig,
		final BlobView blobView,
		final Logger logger,
		@Nullable final InetSocketAddress serverAddress) throws IOException {

	this.log = checkNotNull(logger);
	this.blobClientConfig = checkNotNull(blobClientConfig);
	this.blobView = checkNotNull(blobView);
	this.readWriteLock = new ReentrantReadWriteLock();

	// configure and create the storage directory
	this.storageDir = BlobUtils.initLocalStorageDirectory(blobClientConfig);
	log.info("Created BLOB cache storage directory " + storageDir);

	// configure the number of fetch retries
	final int fetchRetries = blobClientConfig.getInteger(BlobServerOptions.FETCH_RETRIES);
	if (fetchRetries >= 0) {
		this.numFetchRetries = fetchRetries;
	} else {
		log.warn("Invalid value for {}. System will attempt no retries on failed fetch operations of BLOBs.",
			BlobServerOptions.FETCH_RETRIES.key());
		this.numFetchRetries = 0;
	}

	// Add shutdown hook to delete storage directory
	shutdownHook = ShutdownHookUtil.addShutdownHook(this, getClass().getSimpleName(), log);

	this.serverAddress = serverAddress;
}
 
Example #18
Source Project: joal   Author: anthonyraymond   File: BandwidthDispatcher.java    License: Apache License 2.0 5 votes vote down vote up
public BandwidthDispatcher(final int threadPauseInterval, final RandomSpeedProvider randomSpeedProvider) {
    this.threadPauseInterval = threadPauseInterval;
    this.torrentsSeedStats = new HashMap<>();
    this.speedMap = new HashMap<>();
    this.lock = new ReentrantReadWriteLock();


    this.weightHolder = new WeightHolder<>(new PeersAwareWeightCalculator());
    this.randomSpeedProvider = randomSpeedProvider;
}
 
Example #19
Source Project: dble   Author: actiontech   File: PhysicalDataHost.java    License: GNU General Public License v2.0 5 votes vote down vote up
public String switchMaster(String writeHost, boolean syncWriteConf) {
    final ReentrantReadWriteLock lock = DbleServer.getInstance().getConfig().getLock();
    lock.readLock().lock();
    adjustLock.writeLock().lock();
    try {
        HaConfigManager.getInstance().updateConfDataHost(createSwitchSnapshot(writeHost), syncWriteConf);

        PhysicalDataSource newWriteHost = allSourceMap.get(writeHost);
        writeSource.setReadNode(true);
        //close all old master connection ,so that new write query would not put into the old writeHost
        writeSource.clearCons("ha command switch datasource");
        if (!newWriteHost.isDisabled()) {
            GetAndSyncDataSourceKeyVariables task = new GetAndSyncDataSourceKeyVariables(newWriteHost, true);
            KeyVariables variables = task.call();
            if (variables != null) {
                newWriteHost.setReadOnly(variables.isReadOnly());
            } else {
                LOGGER.warn(" GetAndSyncDataSourceKeyVariables failed, set newWriteHost ReadOnly");
                newWriteHost.setReadOnly(true);
            }
        }
        newWriteHost.setReadNode(false);
        writeSource = newWriteHost;
        return this.getClusterHaJson();
    } catch (Exception e) {
        LOGGER.warn("switchMaster Exception ", e);
        throw e;
    } finally {
        lock.readLock().unlock();
        adjustLock.writeLock().unlock();
    }
}
 
Example #20
Source Project: incubator-retired-blur   Author: apache   File: ThriftCacheServer.java    License: Apache License 2.0 5 votes vote down vote up
private Lock getOrCreateLock(ThriftCacheKey<?> key) {
  Lock lock = _lockMap.get(key);
  if (lock == null) {
    Lock nLock = new ReentrantReadWriteLock().writeLock();
    Lock pLock = _lockMap.putIfAbsent(key, new InternalLock(nLock, _lockMap, key));
    if (pLock == null) {
      return nLock;
    } else {
      return pLock;
    }
  } else {
    return lock;
  }
}
 
Example #21
Source Project: strongbox   Author: schibsted   File: FileTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void file_try_with_resources() {
    String path = "test.sbx";
    SecretIdentifier secretIdentifier1 = new SecretIdentifier("MySecret");
    long version1 = 1;
    State state1 = State.ENABLED;
    byte[] payload = Encoder.asUTF8("encryptedPayload");
    RawSecretEntry entry1 = new RawSecretEntry(secretIdentifier1, version1, state1, Optional.empty(), Optional.empty(), payload);

    SecretIdentifier secretIdentifier2 = new SecretIdentifier("MySecret2");
    long version2 = 2;
    Optional<ZonedDateTime> notBeforeValue = Optional.of(ZonedDateTime.of(2016, 5, 4, 2, 0 ,0, 0, ZoneId.of("UTC")));
    RawSecretEntry entry2 = new RawSecretEntry(secretIdentifier2, version2, state1, notBeforeValue, Optional.empty(), payload);

    try (File store = new File(new java.io.File(path), new DummyEncryptor(), new FileEncryptionContext(group), new ReentrantReadWriteLock())) {
        if (store.exists()) {
            store.delete();
        }
        store.create(entry1);
        store.create(entry2);
    } // auto closeable should write the results to disk when exiting the try clause, and thus be readable in the next section

    try (File file = new File(new java.io.File(path), new DummyEncryptor(), new FileEncryptionContext(group), new ReentrantReadWriteLock())) {
        List<RawSecretEntry> list = file.stream().toList();
        boolean t = list.get(1).equals(entry2);
        assertThat(list, containsInAnyOrder(entry1, entry2));
    }

    java.io.File f = new java.io.File(path);
    if (!f.delete()) {
        throw new UnexpectedStateException(path, "EXISTS", "DELETED", "File store deletion failed");
    }
}
 
Example #22
Source Project: moleculer-java   Author: moleculer-java   File: NodeDescriptor.java    License: MIT License 5 votes vote down vote up
public NodeDescriptor(String nodeID, boolean preferHostname, boolean local) {

		// Init final properties
		this.nodeID = nodeID;
		this.preferHostname = preferHostname;
		this.local = local;

		// Init locks
		ReentrantReadWriteLock lock = new ReentrantReadWriteLock(false);
		readLock = lock.readLock();
		writeLock = lock.writeLock();
	}
 
Example #23
Source Project: jdk1.8-source-analysis   Author: raysonfang   File: Repository.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Construct a new repository with the given default domain.
 */
public Repository(String domain, boolean fairLock) {
    lock = new ReentrantReadWriteLock(fairLock);

    domainTb = new HashMap<String,Map<String,NamedObject>>(5);

    if (domain != null && domain.length() != 0)
        this.domain = domain.intern(); // we use == domain later on...
    else
        this.domain = ServiceName.DOMAIN;

    // Creates a new hashtable for the default domain
    domainTb.put(this.domain, new HashMap<String,NamedObject>());
}
 
Example #24
Source Project: incubator-tajo   Author: apache   File: Worker.java    License: Apache License 2.0 5 votes vote down vote up
public Worker(TajoRMContext rmContext, WorkerResource resource) {
  this.rmContext = rmContext;

  this.lastHeartbeatTime = System.currentTimeMillis();
  this.resource = resource;

  ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  this.readLock = lock.readLock();
  this.writeLock = lock.writeLock();
}
 
Example #25
Source Project: hop   Author: project-hop   File: BaseTransform.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Adds the result file.
 *
 * @param resultFile the result file
 */
public void addResultFile( ResultFile resultFile ) {
  ReentrantReadWriteLock.WriteLock lock = resultFilesLock.writeLock();
  lock.lock();
  try {
    resultFiles.put( resultFile.getFile().toString(), resultFile );
  } finally {
    lock.unlock();
  }
}
 
Example #26
Source Project: signalfx-java   Author: signalfx   File: ResettingExponentiallyDecayingReservoir.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link ResettingExponentiallyDecayingReservoir}.
 *
 * @param size  the number of samples to keep in the sampling reservoir
 * @param alpha the exponential decay factor; the higher this is, the more biased the reservoir
 *              will be towards newer values
 * @param clock the clock used to timestamp samples and track rescaling
 */
public ResettingExponentiallyDecayingReservoir(int size, double alpha, Clock clock) {
    this.values = new ConcurrentSkipListMap<Double, WeightedSample>();
    this.lock = new ReentrantReadWriteLock();
    this.alpha = alpha;
    this.size = size;
    this.clock = clock;
    this.count = new AtomicLong(0);
    this.startTime = currentTimeInSeconds();
    this.nextScaleTime = new AtomicLong(clock.getTick() + RESCALE_THRESHOLD);
}
 
Example #27
Source Project: APICloud-Studio   Author: apicloudcom   File: Index.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * Index
 * 
 * @param containerURI
 * @param reuseExistingFile
 * @throws IOException
 */
protected Index(URI containerURI, boolean reuseExistingFile) throws IOException
{
	this.containerURI = containerURI;

	this.memoryIndex = new MemoryIndex();
	this.monitor = new ReentrantReadWriteLock();

	// Convert to a filename we can use for the actual index on disk
	IPath diskIndexPath = computeIndexLocation(containerURI);
	if (diskIndexPath == null)
	{
		return;
	}
	String diskIndexPathString = (diskIndexPath.getDevice() == null) ? diskIndexPath.toString() : diskIndexPath
			.toOSString();
	this.enterWrite();
	try
	{
		this.diskIndex = new DiskIndex(diskIndexPathString);
		this.diskIndex.initialize(reuseExistingFile);
	}
	finally
	{
		this.exitWrite();
	}
}
 
Example #28
Source Project: gemfirexd-oss   Author: gemxd   File: StoppableReentrantReadWriteLock.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new instance
 * @param stopper the cancellation criterion
 */
public StoppableReentrantReadWriteLock(CancelCriterion stopper) {
  Assert.assertTrue(stopper != null);
  ReadWriteLock lock = new ReentrantReadWriteLock();
  this.readLock = new StoppableReadLock(lock, stopper);
  this.writeLock = new StoppableWriteLock(lock, stopper);
}
 
Example #29
Source Project: datacollector   Author: streamsets   File: StatsInfo.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param extensions Immutable list of callbacks to extend stats behavior.
 */
public StatsInfo(List<AbstractStatsExtension> extensions) {
  rwLock = new ReentrantReadWriteLock(true);
  doWithLock(() -> {
    collectedStats = new ArrayList<>();
    extensions.stream().forEach(e -> e.setStatsInfo(this));
    activeStats = new ActiveStats(extensions.stream().map(AbstractStatsExtension::snapshotAndPopulateStatsInfo).collect(Collectors.toList()));
    activeStats.setStatsInfo(this);
  }, true);
}
 
Example #30
Source Project: triplea   Author: triplea-game   File: GameData.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void readObject(final ObjectInputStream in) throws IOException, ClassNotFoundException {
  // The process of deserializing makes use of this lock,
  // we'll get an NPE if we don't set this field here already.
  readWriteLock = new ReentrantReadWriteLock();
  in.defaultReadObject();
  gameDataEventListeners = new GameDataEventListeners();
}