java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock Java Examples

The following examples show how to use java.util.concurrent.locks.ReentrantReadWriteLock.WriteLock. 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: WriteCacheService.java    From database with GNU General Public License v2.0 6 votes vote down vote up
public void resetAndClear() throws InterruptedException {
    final WriteLock writeLock = lock.writeLock();
    writeLock.lockInterruptibly();
    try {
 	reset();
     /*
      * Note: DO NOT clear the service record map. This still has valid
      * cache entries (the read cache).
      */
     // clear the service record map.
     serviceMap.clear();
	
     // reset each buffer.
     for (WriteCache t : writeBuffers) {
         t.reset();
     }
    } finally {
    	writeLock.unlock();
    }

}
 
Example #2
Source File: MapWithLock.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @param otherMap
 * @author tanyaowu
 */
public void putAll(Map<K, V> otherMap) {
	if (otherMap == null || otherMap.isEmpty()) {
		return;
	}

	WriteLock writeLock = this.writeLock();
	writeLock.lock();
	try {
		Map<K, V> map = this.getObj();
		map.putAll(otherMap);
	} catch (Throwable e) {
		log.error(e.getMessage(), e);
	} finally {
		writeLock.unlock();
	}
}
 
Example #3
Source File: MapWithLock.java    From t-io with Apache License 2.0 6 votes vote down vote up
/**
 * 如果key值已经存在,则不会把新value put进去
 * 如果key值不存在,此方法同put(key, value)
 * @param key
 * @param value
 * @return
 * @author tanyaowu
 */
public V putIfAbsent(K key, V value) {
	WriteLock writeLock = this.writeLock();
	writeLock.lock();
	try {
		Map<K, V> map = this.getObj();
		V oldValue = map.putIfAbsent(key, value);
		if (oldValue == null) {
			return value;
		} else {
			return oldValue;
		}
	} catch (Throwable e) {
		log.error(e.getMessage(), e);
	} finally {
		writeLock.unlock();
	}
	return null;
}
 
Example #4
Source File: EndpointService.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
/**
 * Remove resources matching the given {@code location} and all their direct and indirect descendant resources.
 *
 * Note that this method may block if a discovery scan is currently in progress. The removal will occur when
 * the discovery scan finishes - only then will this method return.
 *
 * @param location a location that can contain wildcards
 */
public void removeResources(L location) {
    status.assertRunning(getClass(), "removeResources()");
    try (S session = openSession()) {
        // we must not alter the resource manager while a discovery scan is in progress
        WriteLock lock = EndpointService.this.discoveryScanRWLock.writeLock();
        lock.lock();
        try {
            List<Resource<L>> removed = getResourceManager().removeResources(location,
                    session.getLocationResolver());
            inventoryListenerSupport.fireResourcesRemoved(removed);
        } finally {
            lock.unlock();
        }
    } catch (Exception e) {
        LOG.errorCouldNotAccess(this, e);
    }
}
 
Example #5
Source File: StreamProcessor.java    From incubator-retired-blur with Apache License 2.0 6 votes vote down vote up
private <T> StreamWriter<T> getWriter(final ObjectOutputStream objectOutputStream) {
  final WriteLock writeLock = new ReentrantReadWriteLock(true).writeLock();
  return new StreamWriter<T>() {
    @Override
    public void write(T obj) throws IOException {
      writeLock.lock();
      try {
        objectOutputStream.writeObject(obj);
      } finally {
        writeLock.unlock();
      }
    }

    @Override
    public void write(Iterable<T> it) throws IOException {
      writeLock.lock();
      try {
        for (T t : it) {
          objectOutputStream.writeObject(t);
        }
      } finally {
        writeLock.unlock();
      }
    }
  };
}
 
Example #6
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void invalidateObject(final K key, final V obj) {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        keyedPool.invalidateObject(key, obj);
    } catch (final Exception e) {
        // swallowed as of Pool 2
    } finally {
        writeLock.unlock();
    }
}
 
Example #7
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public V borrowObject(final K key) throws Exception,
        NoSuchElementException, IllegalStateException {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        return keyedPool.borrowObject(key);
    } finally {
        writeLock.unlock();
    }
}
 
Example #8
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void close() {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        keyedPool.close();
    } catch (final Exception e) {
        // swallowed as of Pool 2
    } finally {
        writeLock.unlock();
    }
}
 
Example #9
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void clear(final K key) throws Exception,
        UnsupportedOperationException {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        keyedPool.clear(key);
    } finally {
        writeLock.unlock();
    }
}
 
Example #10
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void clear() throws Exception, UnsupportedOperationException {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        keyedPool.clear();
    } finally {
        writeLock.unlock();
    }
}
 
Example #11
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addObject(final K key) throws Exception,
        IllegalStateException, UnsupportedOperationException {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        keyedPool.addObject(key);
    } finally {
        writeLock.unlock();
    }
}
 
Example #12
Source File: UsingExplicitReadWriteLocks.java    From banyan with MIT License 5 votes vote down vote up
public void writeContent(String newContentToAppend) {
    WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        System.err.println("Writing " + newContentToAppend);
        myContent = new StringBuilder().append(myContent).append(newContentToAppend).toString();
    } finally {
        writeLock.unlock();
    }
}
 
Example #13
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void returnObject(final K key, final V obj) {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        keyedPool.returnObject(key, obj);
    } catch (final Exception e) {
        // swallowed
    } finally {
        writeLock.unlock();
    }
}
 
Example #14
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void addObject() throws Exception, IllegalStateException,
        UnsupportedOperationException {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        pool.addObject();
    } finally {
        writeLock.unlock();
    }
}
 
Example #15
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public T borrowObject() throws Exception, NoSuchElementException,
        IllegalStateException {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        return pool.borrowObject();
    } finally {
        writeLock.unlock();
    }
}
 
Example #16
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void returnObject(final T obj) {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        pool.returnObject(obj);
    } catch (final Exception e) {
        // swallowed as of Pool 2
    } finally {
        writeLock.unlock();
    }
}
 
Example #17
Source File: PoolUtils.java    From commons-pool with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void invalidateObject(final T obj) {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        pool.invalidateObject(obj);
    } catch (final Exception e) {
        // swallowed as of Pool 2
    } finally {
        writeLock.unlock();
    }
}
 
Example #18
Source File: SetWithLock.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 *
 *
 * @author tanyaowu
 */
public void clear() {
	WriteLock writeLock = this.writeLock();
	writeLock.lock();
	try {
		Set<T> set = this.getObj();
		set.clear();
	} catch (Throwable e) {
		log.error(e.getMessage(), e);
	} finally {
		writeLock.unlock();
	}
}
 
Example #19
Source File: Bug2033091.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
static void method2(int n) throws IOException {

        WriteLock lock = lockArray[n].writeLock();
        lock.lock();
        try {
            // do some disk I/O
        } finally {
            lock.unlock();
        }
    }
 
Example #20
Source File: MemoryBranch.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public void releaseLock(Object lock) {
	Lock l = (Lock) lock;
	if (l instanceof WriteLock) {
		WriteLock w = (WriteLock) l;
		if (w.getHoldCount() == 1) {
			currentRevision = currentRevision.increment();
		}
	}
	l.unlock();
}
 
Example #21
Source File: QuickInput.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public IAutoCloseable lockForWriting()
{
	final WriteLock writeLock = readwriteLock.writeLock();
	logger.debug("Acquiring write lock for {}: {}", this, writeLock);
	writeLock.lock();
	logger.debug("Acquired write lock for {}: {}", this, writeLock);

	return () -> {
		writeLock.unlock();
		logger.debug("Released write lock for {}: {}", this, writeLock);
	};
}
 
Example #22
Source File: ASIDocument.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
IAutoCloseable lockForWriting()
{
	// assume _lock is not null
	final WriteLock writeLock = _lock.writeLock();
	logger.debug("Acquiring write lock for {}: {}", this, writeLock);
	writeLock.lock();
	logger.debug("Acquired write lock for {}: {}", this, writeLock);

	return () -> {
		writeLock.unlock();
		logger.debug("Released write lock for {}: {}", this, writeLock);
	};
}
 
Example #23
Source File: ADProcessInstanceController.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
IAutoCloseable lockForWriting()
{
	final WriteLock writeLock = readwriteLock.writeLock();
	logger.debug("Acquiring write lock for {}: {}", this, writeLock);
	writeLock.lock();
	logger.debug("Acquired write lock for {}: {}", this, writeLock);

	return () -> {
		writeLock.unlock();
		logger.debug("Released write lock for {}: {}", this, writeLock);
	};
}
 
Example #24
Source File: Document.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
public IAutoCloseable lockForWriting()
{
	// assume _lock is not null
	final WriteLock writeLock = _lock.writeLock();
	logger.debug("Acquiring write lock for {}: {}", this, writeLock);
	writeLock.lock();
	logger.debug("Acquired write lock for {}: {}", this, writeLock);

	return () -> {
		writeLock.unlock();
		logger.debug("Released write lock for {}: {}", this, writeLock);
	};
}
 
Example #25
Source File: ConcurrentCountingMap.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
/** Sets the value associated with a given key.
 *
 * @param array a byte array.
 * @param offset the first valid byte in {@code array}.
 * @param length the number of valid elements in {@code array}.
 * @param value a value to be associated with the specified key.
 * @return the previous value of the counter associated with the specified key.
 */
public int put(final byte[] array, final int offset, final int length, final int value) {
	final long hash = MurmurHash3.hash(array, offset, length);
	final WriteLock writeLock = lock[(int)(hash >>> shift)].writeLock();
	try {
		writeLock.lock();
		return stripe[(int)(hash >>> shift)].put(array, offset, length, hash, value);
	}
	finally {
		writeLock.unlock();
	}
}
 
Example #26
Source File: ConcurrentCountingMap.java    From BUbiNG with Apache License 2.0 5 votes vote down vote up
/** Adds a value to the counter associated with a given key.
 *
 * @param array a byte array.
 * @param offset the first valid byte in {@code array}.
 * @param length the number of valid elements in {@code array}.
 * @param delta a value to be added to the counter associated with the specified key.
 * @return the previous value of the counter associated with the specified key.
 */
public int addTo(final byte[] array, final int offset, final int length, final int delta) {
	final long hash = MurmurHash3.hash(array, offset, length);
	final WriteLock writeLock = lock[(int)(hash >>> shift)].writeLock();
	try {
		writeLock.lock();
		return stripe[(int)(hash >>> shift)].addTo(array, offset, length, hash, delta);
	}
	finally {
		writeLock.unlock();
	}
}
 
Example #27
Source File: ReconnRunnable.java    From t-io with Apache License 2.0 5 votes vote down vote up
@Override
public void runTask() {
	channelContext.getReconnCount().incrementAndGet();
	ReentrantReadWriteLock closeLock = channelContext.closeLock;
	WriteLock writeLock = closeLock.writeLock();
	writeLock.lock();
	try {
		if (!channelContext.isClosed) //已经连上了,不需要再重连了
		{
			return;
		}
		long start = SystemTimer.currTime;
		tioClient.reconnect(channelContext, 2);
		long end = SystemTimer.currTime;
		long iv = end - start;
		//			if (iv >= 100) {
		//				log.error("{}, 第{}次重连,重连耗时:{} ms", channelContext, channelContext.getReconnCount(), iv);
		//			} else {
		//				log.info("{}, 第{}次重连,重连耗时:{} ms", channelContext, channelContext.getReconnCount(), iv);
		//			}

		log.error("{}, 第{}次重连,重连耗时:{} ms", channelContext, channelContext.getReconnCount(), iv);

		//			if (channelContext.isClosed) {
		//				//					cacheMap.put(channelContext.getServerNode(), SystemTimer.currTime);
		//				return;
		//			}
	} catch (java.lang.Throwable e) {
		log.error(e.toString(), e);
	} finally {
		writeLock.unlock();
	}

}
 
Example #28
Source File: LockUtils.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
	 * 运行write或者等待读锁<br>
	 * 1、能拿到写锁的线程会执行readWriteLockHandler.write()<br>
	 * 2、没拿到写锁的线程,会等待获取读锁,注:获取到读锁的线程,什么也不会执行<br>
	 * 3、当一段代码只允许被一个线程执行时,才用本函数,不要理解成同步等待了<br>
	 * <br>
	 * <strong>注意:对于一些需要判断null等其它条件才执行的操作,在write()方法中建议再检查一次,这个跟double check的原理是一样的</strong><br>
	 * @param key
	 * @param myLock 获取ReentrantReadWriteLock的锁,可以为null
	 * @param readWriteLockHandler 小心:该对象的write()方法并不一定会被执行
	 * @param readWaitTimeInSecond 没拿到写锁的线程,等读锁的时间,单位:秒
	 * @return
	 * @throws Exception
	 * @author tanyaowu
	 */
	public static void runWriteOrWaitRead(String key, Object myLock, ReadWriteLockHandler readWriteLockHandler, Long readWaitTimeInSecond) throws Exception {
		ReentrantReadWriteLock rwLock = getReentrantReadWriteLock(key, myLock);
//		ReadWriteRet ret = new ReadWriteRet();
		WriteLock writeLock = rwLock.writeLock();
		boolean tryWrite = writeLock.tryLock();
		if (tryWrite) {
			try {
				readWriteLockHandler.write();
//				ret.writeRet = writeRet;
			} finally {
//				ret.isWriteRunned = true;
				writeLock.unlock();
			}
		} else {
			ReadLock readLock = rwLock.readLock();
			boolean tryRead = false;
			try {
				tryRead = readLock.tryLock(readWaitTimeInSecond, TimeUnit.SECONDS);
				if (tryRead) {
//					try {
//						readWriteLockHandler.read();
//						ret.readRet = readRet;
//					} finally {
//						ret.isReadRunned = true;
						readLock.unlock();
//					}
				}
			} catch (InterruptedException e) {
				log.error(e.toString(), e);
			}
		}
//		return ret;
	}
 
Example #29
Source File: SetWithLock.java    From t-io with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param t
 * @return
 * @author tanyaowu
 */
public boolean remove(T t) {
	WriteLock writeLock = this.writeLock();
	writeLock.lock();
	try {
		Set<T> set = this.getObj();
		return set.remove(t);
	} catch (Throwable e) {
		log.error(e.getMessage(), e);
	} finally {
		writeLock.unlock();
	}
	return false;
}
 
Example #30
Source File: PoolUtils.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void returnObject(final T obj) {
    final WriteLock writeLock = readWriteLock.writeLock();
    writeLock.lock();
    try {
        pool.returnObject(obj);
    } catch (final Exception e) {
        // swallowed as of Pool 2
    } finally {
        writeLock.unlock();
    }
}