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 File: LocalLockManager.java    From blazingcache with 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 #2
Source File: SimpleBufferTrigger.java    From buffer-trigger with 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 File: StorageDirect2.java    From scava with 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 File: AbstractPatchesLoaderImpl.java    From Aceso with 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 File: WeakRefAtomCache.java    From hypergraphdb with 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 File: TaskImpl.java    From incubator-tez with 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 File: PeerExchangePeerSourceFactory.java    From bt with 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 File: HollowConsumer.java    From hollow with 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 File: QueryInProgress.java    From tajo with 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 File: SatelliteCoreModule.java    From linstor-server with 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 #11
Source File: HiveCommon.java    From neoscada with 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 #12
Source File: Segment.java    From hbase with 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 #13
Source File: SortedOplogSetImpl.java    From gemfirexd-oss with 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 File: GroupModel.java    From strongbox with Apache License 2.0 5 votes vote down vote up
public void backup(String groupName, String fileName, Boolean force) {
    SecretsGroupIdentifier group = new SecretsGroupIdentifier(region, groupName);

    String challenge = String.format("%s.%s", group.region.name, group.name);
    Confirmation.acceptOrExit(String.format("DANGER! Are you sure you want to backup the group '%s' to '%s'?"
                    + "\nIf yes, type the identifier (region.name) as just shown: ",
            challenge, fileName), challenge, force);

    com.schibsted.security.strongbox.sdk.internal.kv4j.generated.File file = new com.schibsted.security.strongbox.sdk.internal.kv4j.generated.File(new java.io.File(fileName),
            secretsGroupManager.encryptor(group),
            new FileEncryptionContext(group),
            new ReentrantReadWriteLock());
    secretsGroupManager.backup(group, file, false);
}
 
Example #15
Source File: GenericScope.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public Object get(String name, ObjectFactory<?> objectFactory) {
	BeanLifecycleWrapper value = this.cache.put(name,
			new BeanLifecycleWrapper(name, objectFactory));
	this.locks.putIfAbsent(name, new ReentrantReadWriteLock());
	try {
		return value.getBean();
	}
	catch (RuntimeException e) {
		this.errors.put(name, e);
		throw e;
	}
}
 
Example #16
Source File: BucketEntry.java    From hbase with Apache License 2.0 5 votes vote down vote up
<T> T withWriteLock(IdReadWriteLock<Long> offsetLock, BucketEntryHandler<T> handler) {
  ReentrantReadWriteLock lock = offsetLock.getLock(this.offset());
  try {
    lock.writeLock().lock();
    return handler.handle();
  } finally {
    lock.writeLock().unlock();
  }
}
 
Example #17
Source File: FileBlocks.java    From crail with Apache License 2.0 5 votes vote down vote up
public FileBlocks(long fd, int fileComponent, CrailNodeType type, int storageClass, int locationClass) {
	super(fd, fileComponent, type, storageClass, locationClass);
	this.blocks = new ArrayList<NameNodeBlockInfo>(CrailConstants.NAMENODE_FILEBLOCKS);
	this.lock = new ReentrantReadWriteLock();
	this.readLock = lock.readLock();
	this.writeLock = lock.writeLock();
}
 
Example #18
Source File: Repository.java    From JDKSourceCode1.8 with MIT License 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 #19
Source File: KafkaProducerPool.java    From common-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new producer pool.
 */
public KafkaProducerPool() {
    this.pool = new HashMap<>();
    this.lock = new ReentrantReadWriteLock(true);
    this.readLock = lock.readLock();
    this.writeLock = lock.writeLock();
    this.producerRotation = new AtomicInteger(0);
    this.shutdown = false;
}
 
Example #20
Source File: MemoryGraphStore.java    From bitsy with Apache License 2.0 5 votes vote down vote up
public MemoryGraphStore(boolean allowFullGraphScans) {
    this.rwLock = new ReentrantReadWriteLock(true);
    this.allowFullGraphScans = allowFullGraphScans;
    this.spinCounter = new AtomicLong(0);

    reset();
}
 
Example #21
Source File: AbstractYarnScheduler.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Construct the service.
 *
 * @param name service name
 */
public AbstractYarnScheduler(String name) {
  super(name);
  ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  this.maxAllocReadLock = lock.readLock();
  this.maxAllocWriteLock = lock.writeLock();
}
 
Example #22
Source File: LockResolverClient.java    From client-java with Apache License 2.0 5 votes vote down vote up
public LockResolverClient(
    TiConfiguration conf,
    TikvBlockingStub blockingStub,
    TikvStub asyncStub,
    ChannelFactory channelFactory,
    RegionManager regionManager) {
  super(conf, channelFactory);
  resolved = new HashMap<>();
  recentResolved = new LinkedList<>();
  readWriteLock = new ReentrantReadWriteLock();
  this.blockingStub = blockingStub;
  this.regionManager = regionManager;
  this.asyncStub = asyncStub;
}
 
Example #23
Source File: FilterTask.java    From odyssey with GNU General Public License v3.0 5 votes vote down vote up
public FilterTask(final List<T> modelData, final ReentrantReadWriteLock.ReadLock readLock, final Filter<T> filter, final SuccessCallback<T> successCallback, final FailureCallback failureCallback) {
    mModelDataRef = new WeakReference<>(modelData);
    mFilter = filter;
    mSuccessCallback = successCallback;
    mFailureCallback = failureCallback;
    mReadLock = readLock;
}
 
Example #24
Source File: NameNodeAnalyticsHttpServer.java    From NNAnalytics with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param conf hadoop configuration
 * @param nnaConf nna configuration
 * @param bindAddress address to bind http server to
 * @param securityContext nna security context
 * @param nameNodeLoader the NameNodeLoader
 * @param hsqlDriver the HSQL embedded DB driver
 * @param usageMetrics nna user usage metrics
 * @param runningQueries list of tracking running queries
 * @param runningOperations list of tracking running operations
 * @param internalService executor for internal service threads
 * @param operationService executor for operation service threads
 * @param queryLock lock around queries
 * @param savingNamespace lock around namespace operations
 * @param cancelRequest lock around allowing next queries to process or not
 */
public NameNodeAnalyticsHttpServer(
    Configuration conf,
    ApplicationConfiguration nnaConf,
    InetSocketAddress bindAddress,
    SecurityContext securityContext,
    NameNodeLoader nameNodeLoader,
    HsqlDriver hsqlDriver,
    UsageMetrics usageMetrics,
    List<BaseQuery> runningQueries,
    Map<String, BaseOperation> runningOperations,
    ExecutorService internalService,
    ExecutorService operationService,
    ReentrantReadWriteLock queryLock,
    AtomicBoolean savingNamespace,
    AtomicBoolean cancelRequest) {
  this.conf = conf;
  this.nnaConf = nnaConf;
  this.bindAddress = bindAddress;
  this.nnLoader = nameNodeLoader;
  this.secContext = securityContext;
  this.hsqlDriver = hsqlDriver;
  this.usageMetrics = usageMetrics;
  this.runningQueries = runningQueries;
  this.runningOperations = runningOperations;
  this.internalService = internalService;
  this.operationService = operationService;
  this.queryLock = queryLock;
  this.savingNamespace = savingNamespace;
  this.cancelRequest = cancelRequest;
}
 
Example #25
Source File: AbstractTagCacheObject.java    From c2mon with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Default public constructor. TODO remove unused constructors
 *
 * Sets the default value of the quality to UNINITIALISED with no
 * description; the description should be added at a later stage
 * with information about this tag creation.
 */
protected AbstractTagCacheObject() {
  //TODO check this - done by config loader
  ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
  readLock = lock.readLock();
  writeLock = lock.writeLock();

  dataTagQuality = new DataTagQualityImpl();
  alarmIds = new ArrayList<>();
  ruleIds = new ArrayList<>();
  cacheTimestamp = new Timestamp(System.currentTimeMillis());
  metadata = new Metadata();
}
 
Example #26
Source File: MapleMap.java    From mapleLemon with GNU General Public License v2.0 5 votes vote down vote up
public void removeMapObject(MapleMapObject obj) {
    ReentrantReadWriteLock rl = this.mapobjectlocks.get(obj.getType());
    rl.writeLock().lock();
    try {
        ((LinkedHashMap) this.mapobjects.get(obj.getType())).remove(obj.getObjectId());
    } finally {
        rl.writeLock().unlock();
    }
}
 
Example #27
Source File: GameData.java    From triplea with 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();
}
 
Example #28
Source File: Repository.java    From openjdk-jdk8u with 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 #29
Source File: StatsInfo.java    From datacollector with 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 File: ReentrantReadWriteLockTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testWriteLockToString(boolean fair) {
    ReentrantReadWriteLock lock = new ReentrantReadWriteLock(fair);
    assertTrue(lock.writeLock().toString().contains("Unlocked"));
    lock.writeLock().lock();
    assertTrue(lock.writeLock().toString().contains("Locked"));
    lock.writeLock().unlock();
    assertTrue(lock.writeLock().toString().contains("Unlocked"));
}