下面列出了怎么用java.util.concurrent.locks.ReentrantReadWriteLock的API类实例代码及写法,或者点击链接到github查看源代码。
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 );
}
};
}
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);
}
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();
}
}
@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;
}
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;
}
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);
}
@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);
}
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);
}
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();
}
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;
}
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;
}
@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)
);
}
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");
}
}
/**
* 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>());
}
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;
}
public StratumMineBlockTaskBuilderCore(final Integer totalExtraNonceByteCount, final TransactionDeflater transactionDeflater) {
_totalExtraNonceByteCount = totalExtraNonceByteCount;
_transactionDeflater = transactionDeflater;
final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
_prototypeBlockReadLock = readWriteLock.readLock();
_prototypeBlockWriteLock = readWriteLock.writeLock();
_initPrototypeBlock();
}
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;
}
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;
}
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();
}
}
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;
}
}
@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");
}
}
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();
}
/**
* 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>());
}
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();
}
/**
* 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();
}
}
/**
* 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);
}
/**
* 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();
}
}
/**
* 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);
}
/**
* @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);
}
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();
}