List of usage examples for java.util.concurrent.locks Lock lock
lock
From source file:com.ery.ertc.estorm.util.ByteBufferArray.java
/** * Access(read or write) this buffer array with a position and length as the given array. Here we will only lock one buffer even if it * may be need visit several buffers. The consistency is guaranteed by the caller. * /*from w w w .j ava 2 s .c o m*/ * @param start * start offset of this buffer array * @param len * The maximum number of bytes to be accessed * @param array * The array from/to which bytes are to be read/written * @param arrayOffset * The offset within the given array of the first byte to be read or written * @param visitor * implement of how to visit the byte buffer */ void multiple(long start, int len, byte[] array, int arrayOffset, Visitor visitor) { assert len >= 0; long end = start + len; int startBuffer = (int) (start / bufferSize), startOffset = (int) (start % bufferSize); int endBuffer = (int) (end / bufferSize), endOffset = (int) (end % bufferSize); assert array.length >= len + arrayOffset; assert startBuffer >= 0 && startBuffer < bufferCount; assert endBuffer >= 0 && endBuffer < bufferCount || (endBuffer == bufferCount && endOffset == 0); if (startBuffer >= locks.length || startBuffer < 0) { String msg = "Failed multiple, start=" + start + ",startBuffer=" + startBuffer + ",bufferSize=" + bufferSize; LOG.error(msg); throw new RuntimeException(msg); } int srcIndex = 0, cnt = -1; for (int i = startBuffer; i <= endBuffer; ++i) { Lock lock = locks[i]; lock.lock(); try { ByteBuffer bb = buffers[i]; if (i == startBuffer) { cnt = bufferSize - startOffset; if (cnt > len) cnt = len; bb.limit(startOffset + cnt).position(startOffset); } else if (i == endBuffer) { cnt = endOffset; bb.limit(cnt).position(0); } else { cnt = bufferSize; bb.limit(cnt).position(0); } visitor.visit(bb, array, srcIndex + arrayOffset, cnt); srcIndex += cnt; } finally { lock.unlock(); } } assert srcIndex == len; }
From source file:de.hoegertn.demo.cxfsimple.SpringStarter.java
public final void doStart() throws Exception { try {/* w ww. j av a 2s.c o m*/ this.doBeforeSpringStart(); } catch (Exception e) { throw new RuntimeException("Before spring failed", e); } Lock writeLock = this.rwLock.writeLock(); AbstractXmlApplicationContext ctx = null; try { writeLock.lock(); if (this.context.get() != null) { throw new RuntimeException("Already started"); } ctx = this.createSpringContext(); final PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer(); configurer.setProperties(System.getProperties()); ctx.addBeanFactoryPostProcessor(configurer); ctx.setConfigLocation(this.getSpringResource()); ctx.refresh(); } catch (Exception e) { if (ctx != null) { try { ctx.close(); } catch (Exception e1) { this.logger.warn("Failed to close context", e1); } ctx = null; } throw new RuntimeException("Spring context failed", e); } finally { if (ctx != null) { this.context.set(ctx); } writeLock.unlock(); } try { this.doAfterSpringStart(); } catch (Exception e) { throw new RuntimeException("After spring failed", e); } }
From source file:SoftReferenceCache.java
/** * @see java.util.Map#keySet()/*from w ww . j a v a2s .co m*/ */ public Set<K> keySet() { Lock lock = theLock.writeLock(); lock.lock(); final Object[] keys; try { removeQueued(); keys = theCache.keySet().toArray(); } finally { lock.unlock(); } return new java.util.AbstractSet<K>() { @Override public Iterator<K> iterator() { return new java.util.Iterator<K>() { private int index = 0; public boolean hasNext() { return index < keys.length - 1; } public K next() { index++; return (K) keys[index - 1]; } public void remove() { SoftReferenceCache.this.remove(keys[index - 1]); } }; } @Override public int size() { return keys.length; } }; }
From source file:edu.internet2.middleware.shibboleth.common.relyingparty.provider.SAMLMDRelyingPartyConfigurationManager.java
/** {@inheritDoc} */ public RelyingPartyConfiguration getRelyingPartyConfiguration(String relyingPartyEntityID) { Lock readLock = getReadWriteLock().readLock(); readLock.lock(); try {// ww w .j a va 2 s.com log.debug("Looking up relying party configuration for {}", relyingPartyEntityID); if (rpConfigs.containsKey(relyingPartyEntityID)) { log.debug("Custom relying party configuration found for {}", relyingPartyEntityID); return rpConfigs.get(relyingPartyEntityID); } log.debug( "No custom relying party configuration found for {}, looking up configuration based on metadata groups.", relyingPartyEntityID); try { if (metadataProvider == null) { log.debug( "No metadata provider available, unable to lookup configuration based on entity group"); } else { EntityDescriptor entityDescriptor = metadataProvider.getEntityDescriptor(relyingPartyEntityID); if (entityDescriptor != null) { EntitiesDescriptor entityGroup = (EntitiesDescriptor) entityDescriptor.getParent(); while (entityGroup != null) { if (rpConfigs.containsKey(entityGroup.getName())) { log.debug("Relying party configuration found for {} as member of metadata group {}", relyingPartyEntityID, entityGroup.getName()); return rpConfigs.get(entityGroup.getName()); } entityGroup = (EntitiesDescriptor) entityGroup.getParent(); } } } } catch (MetadataProviderException e) { log.error("Error fetching metadata for relying party " + relyingPartyEntityID, e); } log.debug( "No custom or group-based relying party configuration found for {}. Using default relying party configuration.", relyingPartyEntityID); return getDefaultRelyingPartyConfiguration(); } finally { readLock.unlock(); } }
From source file:com.xpn.xwiki.doc.FilesystemAttachmentContent.java
@Override public InputStream getContentInputStream() { /** An InputStream which locks a lock while it is being read. */ final class LockingFileInputStream extends FileInputStream { /** The lock to lock while reading the file. */ private Lock lock; /**//from www . j a v a2 s . c o m * The Constructor. * * @param toRead the file for this stream to read. * @param lock the lock to lock on creation of the stream and unlock when it is closed. * @throws IOException if the extended FileInputStream throws one. */ public LockingFileInputStream(final File toRead, final Lock lock) throws IOException { super(toRead); this.lock = lock; lock.lock(); } /** {@inheritDoc} */ public void close() throws IOException { // Make sure this only happens once. if (this.lock != null) { super.close(); this.lock.unlock(); this.lock = null; } } } try { return new AutoCloseInputStream(new LockingFileInputStream(this.storageFile, this.lock.readLock())); } catch (IOException e) { throw new RuntimeException("Failed to get InputStream", e); } }
From source file:net.sf.fakenames.fddemo.BaseDirLayout.java
public void init() throws IOException { home = getBaseDir();// w w w.ja v a 2 s . c om mountInfo = MountsSingleton.get(os); final HashMap<File, String> pathNameMap = new HashMap<>(); File systemRoot = Environment.getRootDirectory(); try { systemRoot = systemRoot.getCanonicalFile(); } catch (IOException ignore) { // ok } pathNameMap.put(systemRoot, "Android system root"); File filesDir = getFilesDir(); try { filesDir = filesDir.getCanonicalFile(); } catch (IOException ignore) { // ok } pathNameMap.put(filesDir, "Internal private storage"); File[] external = ContextCompat.getExternalFilesDirs(this, null); for (int i = 0; i < external.length; ++i) { File resolved = external[i]; if (resolved == null) continue; try { resolved = resolved.getCanonicalFile(); } catch (IOException ignore) { // ok } pathNameMap.put(resolved, "External storage " + i); } List<StorageVolume> volumes = new ArrayList<>(); if (Build.VERSION.SDK_INT >= 24) { final StorageManager sm = (StorageManager) getSystemService(STORAGE_SERVICE); volumes.addAll(sm.getStorageVolumes()); } final Lock lock = mountInfo.getLock(); lock.lock(); try { parseMounts(pathNameMap, volumes); } finally { lock.unlock(); } }
From source file:org.springframework.integration.metadata.PropertiesPersistingMetadataStore.java
@Override public String get(String key) { Assert.notNull(key, "'key' cannot be null"); Lock lock = this.lockRegistry.obtain(key); lock.lock(); try {/* www . j av a2s. c om*/ return this.metadata.getProperty(key); } finally { lock.unlock(); } }
From source file:org.springframework.integration.metadata.PropertiesPersistingMetadataStore.java
@Override public String remove(String key) { Assert.notNull(key, "'key' cannot be null"); Lock lock = this.lockRegistry.obtain(key); lock.lock(); try {/*from ww w . j av a2 s . c om*/ return (String) this.metadata.remove(key); } finally { this.dirty = true; lock.unlock(); } }
From source file:org.springframework.integration.metadata.PropertiesPersistingMetadataStore.java
@Override public void put(String key, String value) { Assert.notNull(key, "'key' cannot be null"); Assert.notNull(value, "'value' cannot be null"); Lock lock = this.lockRegistry.obtain(key); lock.lock(); try {//w ww . jav a 2s .com this.metadata.setProperty(key, value); } finally { this.dirty = true; lock.unlock(); } }
From source file:org.springframework.integration.metadata.PropertiesPersistingMetadataStore.java
@Override public String putIfAbsent(String key, String value) { Assert.notNull(key, "'key' cannot be null"); Assert.notNull(value, "'value' cannot be null"); Lock lock = this.lockRegistry.obtain(key); lock.lock(); try {//from w w w . j a va2 s. c o m String property = this.metadata.getProperty(key); if (property == null) { this.metadata.setProperty(key, value); this.dirty = true; return null; } else { return property; } } finally { lock.unlock(); } }