Java Code Examples for java.lang.ref.ReferenceQueue

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project commons-logging, under directory /src/test/org/apache/commons/logging/impl/.

Source file: WeakHashtableTest.java

  21 
vote

public void testRelease() throws Exception {
  assertNotNull(weakHashtable.get(new Long(1)));
  ReferenceQueue testQueue=new ReferenceQueue();
  WeakReference weakKeyOne=new WeakReference(keyOne,testQueue);
  keyOne=null;
  keyTwo=null;
  keyThree=null;
  valueOne=null;
  valueTwo=null;
  valueThree=null;
  int iterations=0;
  int bytz=2;
  while (true) {
    System.gc();
    if (iterations++ > MAX_GC_ITERATIONS) {
      fail("Max iterations reached before resource released.");
    }
    if (weakHashtable.get(new Long(1)) == null) {
      break;
    }
 else {
      byte[] b=new byte[bytz];
      bytz=bytz * 2;
    }
  }
  while (testQueue.poll() == null) {
  }
  assertEquals("underlying table not emptied",0,weakHashtable.size());
}
 

Example 2

From project echo2, under directory /src/webcontainer/java/nextapp/echo2/webcontainer/util/.

Source file: IdTable.java

  21 
vote

/** 
 * @see java.io.Serializable Writes objects directly into values of Map as straight references. The values will be changed to <code>WeakReference</code>s when  purge() is called.
 */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  in.defaultReadObject();
  idToReferenceMap=new HashMap();
  referenceQueue=new ReferenceQueue();
  String id=(String)in.readObject();
  if (id != null) {
    hasHardReferences=true;
    while (id != null) {
      RenderIdSupport object=(RenderIdSupport)in.readObject();
      idToReferenceMap.put(id,object);
      id=(String)in.readObject();
    }
  }
}
 

Example 3

From project echo3, under directory /src/server-java/webcontainer/nextapp/echo/webcontainer/util/.

Source file: IdTable.java

  21 
vote

/** 
 * @see java.io.Serializable Writes objects directly into values of Map as straight references. The values will be changed to <code>WeakReference</code>s when  purge() is called.
 */
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
  in.defaultReadObject();
  idToReferenceMap=new HashMap();
  referenceQueue=new ReferenceQueue();
  String id=(String)in.readObject();
  if (id != null) {
    hasHardReferences=true;
    while (id != null) {
      RenderIdSupport object=(RenderIdSupport)in.readObject();
      idToReferenceMap.put(id,object);
      id=(String)in.readObject();
    }
  }
}
 

Example 4

From project geronimo-xbean, under directory /xbean-reflect/src/main/java/org/apache/xbean/propertyeditor/.

Source file: ReferenceIdentityMap.java

  21 
vote

public ReferenceIdentityMap(){
  this.loadFactor=DEFAULT_LOAD_FACTOR;
  this.data=new ReferenceEntry[DEFAULT_CAPACITY];
  this.threshold=calculateThreshold(DEFAULT_CAPACITY,loadFactor);
  this.purgeQueue=new ReferenceQueue();
}
 

Example 5

From project indextank-engine, under directory /cojen-2.2.1-sources/org/cojen/util/.

Source file: WeakIdentityMap.java

  21 
vote

public WeakIdentityMap(int initialCapacity,float loadFactor){
  if (initialCapacity <= 0) {
    throw new IllegalArgumentException("Initial capacity must be greater than 0");
  }
  if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
    throw new IllegalArgumentException("Load factor must be greater than 0");
  }
  this.loadFactor=loadFactor;
  this.table=new Entry[initialCapacity];
  this.threshold=(int)(initialCapacity * loadFactor);
  this.queue=new ReferenceQueue();
}
 

Example 6

From project morphia, under directory /morphia/src/main/java/relocated/morphia/org/apache/commons/collections/.

Source file: ReferenceMap.java

  21 
vote

/** 
 * Reads the contents of this object from the given input stream.
 * @param inp  the input stream to read from
 * @throws IOException  if the stream raises it
 * @throws ClassNotFoundException  if the stream raises it
 */
private void readObject(ObjectInputStream inp) throws IOException, ClassNotFoundException {
  inp.defaultReadObject();
  table=new Entry[inp.readInt()];
  threshold=(int)(table.length * loadFactor);
  queue=new ReferenceQueue();
  Object key=inp.readObject();
  while (key != null) {
    Object value=inp.readObject();
    put(key,value);
    key=inp.readObject();
  }
}
 

Example 7

From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/client/cache/.

Source file: ManagedHttpCacheStorage.java

  19 
vote

public ManagedHttpCacheStorage(final CacheConfig config){
  super();
  this.entries=new CacheMap(config.getMaxCacheEntries());
  this.morque=new ReferenceQueue<HttpCacheEntry>();
  this.resources=new HashSet<ResourceReference>();
}
 

Example 8

From project android_external_guava, under directory /src/com/google/common/base/.

Source file: FinalizableReferenceQueue.java

  19 
vote

/** 
 * Constructs a new queue.
 */
@SuppressWarnings("unchecked") public FinalizableReferenceQueue(){
  ReferenceQueue<Object> queue;
  boolean threadStarted=false;
  try {
    queue=(ReferenceQueue<Object>)startFinalizer.invoke(null,FinalizableReference.class,this);
    threadStarted=true;
  }
 catch (  IllegalAccessException e) {
    throw new AssertionError(e);
  }
catch (  Throwable t) {
    logger.log(Level.INFO,"Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are" + " created.",t);
    queue=new ReferenceQueue<Object>();
  }
  this.queue=queue;
  this.threadStarted=threadStarted;
}
 

Example 9

From project clojure, under directory /src/jvm/clojure/lang/.

Source file: Util.java

  19 
vote

static public <K,V>void clearCache(ReferenceQueue rq,ConcurrentHashMap<K,Reference<V>> cache){
  if (rq.poll() != null) {
    while (rq.poll() != null)     ;
    for (    Map.Entry<K,Reference<V>> e : cache.entrySet()) {
      Reference<V> val=e.getValue();
      if (val != null && val.get() == null)       cache.remove(e.getKey(),val);
    }
  }
}
 

Example 10

From project CommitCoin, under directory /src/com/google/bitcoin/core/.

Source file: MemoryPool.java

  19 
vote

/** 
 * Creates a memory pool that will track at most the given number of transactions (allowing you to bound memory usage).
 * @param size Max number of transactions to track. The pool will fill up to this size then stop growing.
 */
public MemoryPool(final int size){
  memoryPool=new LinkedHashMap<Sha256Hash,Entry>(){
    @Override protected boolean removeEldestEntry(    Map.Entry<Sha256Hash,Entry> entry){
      return size() > size;
    }
  }
;
  referenceQueue=new ReferenceQueue<Transaction>();
}
 

Example 11

From project commons-io, under directory /src/test/java/org/apache/commons/io/.

Source file: FileCleaningTrackerTestCase.java

  19 
vote

/** 
 * @see junit.framework.TestCase#tearDown() 
 */
@Override protected void tearDown() throws Exception {
  FileUtils.deleteDirectory(getTestDirectory());
{
    theInstance.q=new ReferenceQueue<Object>();
    theInstance.trackers.clear();
    theInstance.deleteFailures.clear();
    theInstance.exitWhenFinished=false;
    theInstance.reaper=null;
  }
  theInstance=null;
}
 

Example 12

From project droid-fu, under directory /src/main/java/com/google/common/base/.

Source file: FinalizableReferenceQueue.java

  19 
vote

/** 
 * Constructs a new queue.
 */
@SuppressWarnings("unchecked") public FinalizableReferenceQueue(){
  ReferenceQueue<Object> queue;
  boolean threadStarted=false;
  try {
    queue=(ReferenceQueue<Object>)startFinalizer.invoke(null,FinalizableReference.class,this);
    threadStarted=true;
  }
 catch (  IllegalAccessException e) {
    throw new AssertionError(e);
  }
catch (  Throwable t) {
    logger.log(Level.INFO,"Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are" + " created.",t);
    queue=new ReferenceQueue<Object>();
  }
  this.queue=queue;
  this.threadStarted=threadStarted;
}
 

Example 13

From project event-bus, under directory /src/main/java/com/northconcepts/eventbus/.

Source file: EventListenerStub.java

  19 
vote

public EventListenerStub(EventFilter filter,T listener,ReferenceQueue<? super T> referenceQueue){
  if (filter == null) {
    filter=EventFilter.NULL;
  }
  this.filter=filter;
  this.listener=new SoftReference<T>(listener,referenceQueue);
}
 

Example 14

From project FlipDroid, under directory /web-image-view/src/main/java/common/base/.

Source file: FinalizableReferenceQueue.java

  19 
vote

/** 
 * Constructs a new queue.
 */
@SuppressWarnings("unchecked") public FinalizableReferenceQueue(){
  ReferenceQueue<Object> queue;
  boolean threadStarted=false;
  try {
    queue=(ReferenceQueue<Object>)startFinalizer.invoke(null,FinalizableReference.class,this);
    threadStarted=true;
  }
 catch (  IllegalAccessException e) {
    throw new AssertionError(e);
  }
catch (  Throwable t) {
    logger.log(Level.INFO,"Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are" + " created.",t);
    queue=new ReferenceQueue<Object>();
  }
  this.queue=queue;
  this.threadStarted=threadStarted;
}
 

Example 15

From project generic-store-for-android, under directory /src/com/google/common/base/.

Source file: FinalizableReferenceQueue.java

  19 
vote

/** 
 * Constructs a new queue.
 */
@SuppressWarnings("unchecked") public FinalizableReferenceQueue(){
  ReferenceQueue<Object> queue;
  boolean threadStarted=false;
  try {
    queue=(ReferenceQueue<Object>)startFinalizer.invoke(null,FinalizableReference.class,this);
    threadStarted=true;
  }
 catch (  IllegalAccessException e) {
    throw new AssertionError(e);
  }
catch (  Throwable t) {
    logger.log(Level.INFO,"Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are" + " created.",t);
    queue=new ReferenceQueue<Object>();
  }
  this.queue=queue;
  this.threadStarted=threadStarted;
}
 

Example 16

From project heritrix3, under directory /commons/src/main/java/org/archive/util/.

Source file: ObjectIdentityBdbCache.java

  19 
vote

/** 
 * Call this method when you have an instance when you used the default constructor or when you have a deserialized instance that you want to reconnect with an extant bdbje environment.  Do not call this method if you used the {@link #CachedBdbMap(File,String,Class,Class)} constructor.
 * @param env
 * @param keyClass
 * @param valueClass
 * @param classCatalog
 * @throws DatabaseException
 */
public void initialize(final Environment env,String dbName,final Class valueClass,final StoredClassCatalog classCatalog) throws DatabaseException {
  this.memMap=new ConcurrentHashMap<String,SoftEntry<V>>(8192,0.9f,64);
  this.refQueue=new ReferenceQueue<V>();
  canary=new SoftReference<LowMemoryCanary>(new LowMemoryCanary());
  this.db=openDatabase(env,dbName);
  this.diskMap=createDiskMap(this.db,classCatalog,valueClass);
  this.count=new AtomicLong(diskMap.size());
}
 

Example 17

From project hibernate-validator, under directory /engine/src/main/java/org/hibernate/validator/internal/util/.

Source file: ConcurrentReferenceHashMap.java

  19 
vote

HashEntry(K key,int hash,HashEntry<K,V> next,V value,ReferenceType keyType,ReferenceType valueType,ReferenceQueue<Object> refQueue){
  this.hash=hash;
  this.next=next;
  this.keyRef=newKeyReference(key,keyType,refQueue);
  this.valueRef=newValueReference(value,valueType,refQueue);
}
 

Example 18

From project httpClient, under directory /httpclient/src/main/java/org/apache/http/impl/conn/tsccm/.

Source file: BasicPoolEntry.java

  19 
vote

public BasicPoolEntry(ClientConnectionOperator op,HttpRoute route,ReferenceQueue<Object> queue){
  super(op,route);
  if (route == null) {
    throw new IllegalArgumentException("HTTP route may not be null");
  }
  this.created=System.currentTimeMillis();
  this.validUntil=Long.MAX_VALUE;
  this.expiry=this.validUntil;
}
 

Example 19

From project ioke, under directory /src/ikj/main/com/google/common/base/.

Source file: FinalizableReferenceQueue.java

  19 
vote

/** 
 * Constructs a new queue.
 */
@SuppressWarnings("unchecked") public FinalizableReferenceQueue(){
  ReferenceQueue<Object> queue;
  boolean threadStarted=false;
  try {
    queue=(ReferenceQueue<Object>)startFinalizer.invoke(null,FinalizableReference.class,this);
    threadStarted=true;
  }
 catch (  IllegalAccessException e) {
    throw new AssertionError(e);
  }
catch (  Throwable t) {
    logger.log(Level.INFO,"Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are" + " created.",t);
    queue=new ReferenceQueue<Object>();
  }
  this.queue=queue;
  this.threadStarted=threadStarted;
}
 

Example 20

From project jboss-logmanager, under directory /src/main/java/org/jboss/logmanager/.

Source file: ConcurrentReferenceHashMap.java

  19 
vote

HashEntry(K key,int hash,HashEntry<K,V> next,V value,ReferenceType keyType,ReferenceType valueType,ReferenceQueue<Object> refQueue){
  this.hash=hash;
  this.next=next;
  this.keyRef=newKeyReference(key,keyType,refQueue);
  this.valueRef=newValueReference(value,valueType,refQueue);
}
 

Example 21

From project jboss-modules, under directory /src/main/java/org/jboss/modules/ref/.

Source file: References.java

  19 
vote

/** 
 * Create a reference of a given type with the provided value and attachment.  If the reference type is {@link Reference.Type#STRONG} or {@link Reference.Type#NULL} then the reference queue argument is ignored.  Ifthe reference type is  {@link Reference.Type#NULL} then the value and attachment arguments are ignored.
 * @param type the reference type
 * @param value the reference value
 * @param attachment the attachment value
 * @param referenceQueue the reference queue to use, if any
 * @param < T > the reference value type
 * @param < A > the reference attachment type
 * @return the reference
 */
public static <T,A>Reference<T,A> create(Reference.Type type,T value,A attachment,ReferenceQueue<? super T> referenceQueue){
switch (type) {
case STRONG:
    return new StrongReference<T,A>(value,attachment);
case WEAK:
  return new WeakReference<T,A>(value,attachment,referenceQueue);
case PHANTOM:
return new PhantomReference<T,A>(value,attachment,referenceQueue);
case SOFT:
return new SoftReference<T,A>(value,attachment,referenceQueue);
case NULL:
return getNullReference();
default :
throw new IllegalStateException();
}
}
 

Example 22

From project jboss-msc, under directory /src/test/java/org/jboss/msc/value/.

Source file: ReferenceValueTestCase.java

  19 
vote

@Test public void softReferenceValue() throws Exception {
  final List<String> referent=new ArrayList<String>();
  final ReferenceQueue<List<String>> queue=new ReferenceQueue<List<String>>();
  final Reference<List<String>,String> reference=References.create(Type.SOFT,referent,"attachment",queue);
  final Value<List<String>> value=new ReferenceValue<List<String>>(reference);
  assertSame(referent,value.getValue());
}
 

Example 23

From project jcarder, under directory /src/com/enea/jcarder/agent/.

Source file: LockingContextIdCache.java

  19 
vote

/** 
 * Create a LockingContextIdCache backed by a ContextWriterIfc.
 */
public LockingContextIdCache(Logger logger,ContextWriterIfc writer){
  mLogger=logger;
  mCache=new HashMap<EqualsComparableKey,Integer>();
  mReferenceQueue=new ReferenceQueue<Object>();
  mContextWriter=writer;
}
 

Example 24

From project JDBM3, under directory /src/main/java/org/apache/jdbm/.

Source file: DBCacheRef.java

  19 
vote

/** 
 * Construct a CacheRecordManager wrapping another DB and using a given cache policy.
 */
public DBCacheRef(String filename,boolean readonly,boolean transactionDisabled,Cipher cipherIn,Cipher cipherOut,boolean useRandomAccessFile,boolean deleteFilesAfterClose,byte cacheType,boolean cacheAutoClearOnLowMem,boolean lockingDisabled){
  super(filename,readonly,transactionDisabled,cipherIn,cipherOut,useRandomAccessFile,deleteFilesAfterClose,lockingDisabled);
  this._cacheType=cacheType;
  _autoClearReferenceCacheOnLowMem=cacheAutoClearOnLowMem;
  _softHash=new LongHashMap<ReferenceCacheEntry>();
  _refQueue=new ReferenceQueue<ReferenceCacheEntry>();
  _softRefThread=new Thread(new SoftRunnable(this,_refQueue),"JDBM Soft Cache Disposer " + (threadCounter.incrementAndGet()));
  _softRefThread.setDaemon(true);
  _softRefThread.start();
}
 

Example 25

From project JGit, under directory /org.spearce.jgit/src/org/spearce/jgit/lib/.

Source file: ByteWindow.java

  19 
vote

/** 
 * Constructor for ByteWindow.
 * @param o the WindowedFile providing data access
 * @param pos the position in the file the data comes from.
 * @param d an id provided by the WindowedFile. See {@link WindowCache#get(WindowCursor,WindowedFile,long)}.
 * @param ref the object value required to perform data access.
 * @param sz the total number of bytes in this window.
 */
@SuppressWarnings("unchecked") ByteWindow(final WindowedFile o,final long pos,final int d,final T ref,final int sz){
  super(ref,(ReferenceQueue<T>)WindowCache.clearedWindowQueue);
  provider=o;
  size=sz;
  id=d;
  start=pos;
  end=start + size;
}
 

Example 26

From project jSCSI, under directory /bundles/commons/src/main/java/org/jscsi/utils/.

Source file: SoftHashMap.java

  19 
vote

/** 
 * Constructor that allows to specify how many strong references should be used internally.
 * @param initStrongReferenceCount Number of internal strong references.
 */
@SuppressWarnings("unchecked") public SoftHashMap(final int initStrongReferenceCount){
  internalMap=new HashMap<K,SoftReference<V>>();
  strongReferenceCount=initStrongReferenceCount;
  strongReferenceArray=(V[])new Object[initStrongReferenceCount];
  currentStrongReferenceOffset=0;
  queue=new ReferenceQueue<SoftValue<V>>();
}
 

Example 27

From project p2-bridge, under directory /eclipse-bridge/src/main/java/org/sonatype/eclipse/bridge/internal/.

Source file: DefaultEclipseInstance.java

  19 
vote

public Started(){
  activeServices=new HashMap<WeakReference<?>,ServiceReference>();
  staleReferences=new ReferenceQueue<Object>();
  lock=new ReentrantReadWriteLock();
  cleanupThread=new Thread(new Cleanup(),"Stale Eclipse services cleanup");
  cleanupThread.start();
}
 

Example 28

From project pepe, under directory /pepe/src/edu/stanford/pepe/.

Source file: ArrayShadowMap.java

  19 
vote

private static void cleanupOne(final ReferenceQueue queue){
  try {
    final WeakKey key=(WeakKey)queue.remove();
    shadows.remove(key);
  }
 catch (  final InterruptedException xx) {
    System.out.println("unexpected interrupt");
  }
}
 

Example 29

From project platform_external_apache-http, under directory /src/org/apache/http/impl/conn/tsccm/.

Source file: AbstractConnPool.java

  19 
vote

/** 
 * Enables connection garbage collection (GC). This method must be called immediately after creating the connection pool. It is not possible to enable connection GC after pool entries have been created. Neither is it possible to disable connection GC.
 * @throws IllegalStateException if connection GC is already enabled, or if it cannot be enabled because there already are pool entries
 */
public void enableConnectionGC() throws IllegalStateException {
  if (refQueue != null) {
    throw new IllegalStateException("Connection GC already enabled.");
  }
  poolLock.lock();
  try {
    if (numConnections > 0) {
      throw new IllegalStateException("Pool already in use.");
    }
  }
  finally {
    poolLock.unlock();
  }
  refQueue=new ReferenceQueue<Object>();
  refWorker=new RefQueueWorker(refQueue,this);
  Thread t=new Thread(refWorker);
  t.setDaemon(true);
  t.setName("[email protected]" + this);
  t.start();
}
 

Example 30

From project platform_external_guava, under directory /src/com/google/common/base/.

Source file: FinalizableReferenceQueue.java

  19 
vote

/** 
 * Constructs a new queue.
 */
@SuppressWarnings("unchecked") public FinalizableReferenceQueue(){
  ReferenceQueue<Object> queue;
  boolean threadStarted=false;
  try {
    queue=(ReferenceQueue<Object>)startFinalizer.invoke(null,FinalizableReference.class,this);
    threadStarted=true;
  }
 catch (  IllegalAccessException e) {
    throw new AssertionError(e);
  }
catch (  Throwable t) {
    logger.log(Level.INFO,"Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are" + " created.",t);
    queue=new ReferenceQueue<Object>();
  }
  this.queue=queue;
  this.threadStarted=threadStarted;
}
 

Example 31

From project rhevm-api, under directory /common/jaxrs/src/main/java/com/redhat/rhevm/api/common/util/.

Source file: ReapedMap.java

  19 
vote

/** 
 * Package-protected constructor intended for test use.
 * @param reapAfter entries become eligible for reaping after this duration (ms)
 * @param accessBasedAging reset reapAfter timeout on each access
 * @param queue reference queue to avoid leaked mappings in case whereaggressive GC eats referent before it is reaped
 */
ReapedMap(long reapAfter,boolean accessBasedAging,ReferenceQueue<V> queue){
  this.reapAfter=reapAfter;
  this.accessBasedAging=accessBasedAging;
  this.queue=queue;
  reapableMap=new LinkedHashMap<K,IdAwareReference<K,V>>();
}
 

Example 32

From project shiro, under directory /core/src/main/java/org/apache/shiro/util/.

Source file: SoftHashMap.java

  19 
vote

/** 
 * Creates a new SoftHashMap with the specified retention size. <p/> The retention size (n) is the total number of most recent entries in the map that will be strongly referenced (ie 'retained') to prevent them from being eagerly garbage collected.  That is, the point of a SoftHashMap is to allow the garbage collector to remove as many entries from this map as it desires, but there will always be (n) elements retained after a GC due to the strong references. <p/> Note that in a highly concurrent environments the exact total number of strong references may differ slightly than the actual <code>retentionSize</code> value.  This number is intended to be a best-effort retention low water mark.
 * @param retentionSize the total number of most recent entries in the map that will be strongly referenced(retained), preventing them from being eagerly garbage collected by the JVM.
 */
@SuppressWarnings({"unchecked"}) public SoftHashMap(int retentionSize){
  super();
  RETENTION_SIZE=Math.max(0,retentionSize);
  queue=new ReferenceQueue<V>();
  strongReferencesLock=new ReentrantLock();
  map=new ConcurrentHashMap<K,SoftValue<V,K>>();
  strongReferences=new ConcurrentLinkedQueue<V>();
}
 

Example 33

From project summer, under directory /modules/el/src/main/java/org/jboss/el/util/.

Source file: ReferenceCache.java

  19 
vote

public ReferenceValue<V> createValue(ReferenceQueue queue,final V value){
  return new ReferenceValue<V>(){
    public V get(){
      return value;
    }
  }
;
}
 

Example 34

From project zoie, under directory /zoie-core/src/main/java/proj/zoie/impl/indexing/.

Source file: SmartReaderCache.java

  19 
vote

public SmartReaderCache(IndexReaderFactory<ZoieIndexReader<R>> readerfactory){
  readermap=new HashMap<WeakReference<List<ZoieIndexReader<R>>>,List<ZoieIndexReader<R>>>();
  refq=new ReferenceQueue<List<ZoieIndexReader<R>>>();
  _readerfactory=readerfactory;
  _maintenance=newMaintenanceThread();
  _maintenance.setDaemon(true);
}