/**
  * Undo after some positions have been garbage collected.
  *
  * @throws BadLocationException
  */
 public void testUndoGC() throws BadLocationException {
   content.insertString(0, "012345678");
   Vector<WeakReference<Position>> pos = new Vector<WeakReference<Position>>(10);
   ReferenceQueue<Position> rq = new ReferenceQueue<Position>();
   for (int i = 0; i < content.length(); i += 2) {
     pos.add(new WeakReference<Position>(content.createPosition(i), rq));
   }
   int count = 0;
   int i;
   for (i = 0; i < 100; i++) {
     System.gc();
     Reference<?> r;
     if ((r = rq.poll()) != null) {
       pos.remove(r);
       count++;
       if (pos.size() == 0) {
         break;
       }
     }
   }
   // This call causes all the garbage collected positions to be
   // removed from the internal list
   UndoableEdit ue = content.remove(0, 5);
   assertEquals("5678", content.getString(0, content.length() - 1));
   // Test (it shouldn't fail with any NullPointerException)
   ue.undo();
   assertEquals("012345678", content.getString(0, content.length() - 1));
 }
 /** Removes stale symbols from the table. */
 private void clean() {
   SREntry entry = (SREntry) fReferenceQueue.poll();
   while (entry != null) {
     removeEntry(entry);
     entry = (SREntry) fReferenceQueue.poll();
   }
 }
Example #3
0
    public void run() {
      while (true)
        try {

          // collect next item from cache,
          // limit 10000 ms is to keep periodically checking if recman was GCed
          SoftCacheEntry e = (SoftCacheEntry) entryQueue.remove(10000);

          // check if  recman was GCed, cancel in that case
          CacheRecordManager recman = recman2.get();
          if (recman == null) return;
          if (e != null) {
            synchronized (recman._softHash) {
              while (e != null) {
                recman._softHash.remove(e._recid);
                e = (SoftCacheEntry) entryQueue.poll();
              }
            }
          }

        } catch (InterruptedException e) {
          return;
        } catch (Throwable e) {
          // this thread must keep spinning,
          // otherwise SoftCacheEntries would not be disposed
          e.printStackTrace();
        }
    }
Example #4
0
  @Test
  public void testQueuedWeakReference() {
    final boolean[] dealloced = {false};
    ReferenceQueue<? super Object> queue = new ReferenceQueue<Object>();
    for (@AutoreleasePool int i = 0; i < 1; i++) {
      Object referent =
          new Object() {
            public void finalize() {
              dealloced[0] = true;
            }
          };
      weakRef = new WeakReference<Object>(referent, queue);
      assertSame("weakRef.get doesn't return referent", referent, weakRef.get());

      // Remove reference to o, verify it's still available in the reference.
      referent = null;
      assertNotNull("weakRef cleared too soon", weakRef.get());
      assertFalse("referent dealloc'ed too soon", dealloced[0]);
    }

    // Verify weak reference was queued.
    Reference<?> queuedRef = queue.poll();
    assertNotNull("weakRef wasn't queued", queuedRef);

    // Verify weak reference was cleared.
    assertNull("weakRef wasn't cleared", weakRef.get());
    assertTrue("referent wasn't dealloc'ed", dealloced[0]);
  }
 @Override
 public synchronized Object call() {
   boolean needsSchedule = true;
   try {
     quota = maxErrors;
     Reference<? extends Object> ref = refQueue.poll();
     while (ref != null) {
       if (quota > 0) quota--;
       String msg = messages.remove(ref);
       if (msg != null) log.error("Uncollected failure: " + msg);
       if (quota == 0) {
         schedule((long) (1000.0 * (1.0 / maxPerSecond)), TimeUnit.MILLISECONDS);
         needsSchedule = false;
         ref = null;
       } else if (finished) {
         ref = null;
       } else {
         ref = refQueue.poll();
       }
     }
   } catch (Exception e) {
     log.error("Error logging uncollected failure", e);
   }
   if (needsSchedule) schedule(delay, units);
   return null;
 }
  public void cleanCleared() {
    WKey wk;
    while ((wk = (WKey) keyQ.poll()) != null) inner.remove(wk);

    WVal wv;
    while ((wv = (WVal) valQ.poll()) != null) inner.remove(wv.getWKey());
  }
 private void processQueue() {
   CacheEntry gcedEntry = (CacheEntry) refQueue.poll();
   while (gcedEntry != null) {
     removeEntry(gcedEntry);
     gcedEntry = (CacheEntry) refQueue.poll();
   }
 }
Example #8
0
 public void cleanRows() {
   NativeObjectReference reference = (NativeObjectReference) referenceQueue.poll();
   while (reference != null) {
     UncheckedRow.nativeClose(reference.nativePointer);
     rowReferences.remove(reference);
     reference = (NativeObjectReference) referenceQueue.poll();
   }
 }
Example #9
0
 public void clear() {
   while (queue.poll() != null) ;
   modCount++;
   Entry[] tab = table;
   for (int i = 0; i < tab.length; ++i) tab[i] = null;
   size = 0;
   while (queue.poll() != null) ;
 }
 protected void cleanUp() {
   WeakEntryReference reference = (WeakEntryReference) referenceQueue.poll();
   while (reference != null) {
     // remove the entry but do not increment the modcount
     // since this is not a user action
     removeEntry(reference.owner, false);
     reference = (WeakEntryReference) referenceQueue.poll();
   }
 }
  @SideEffect("Causes OutOfMemoryError to test finalization")
  public void test_get_SoftReference() {

    class TestObject {
      public boolean finalized;

      public TestObject() {
        finalized = false;
      }

      protected void finalize() {
        finalized = true;
      }
    }

    final ReferenceQueue rq = new ReferenceQueue();

    class TestThread extends Thread {
      public void run() {
        Object testObj = new TestObject();
        r = new SoftReference(testObj, rq);
      }
    }
    Reference ref;
    try {
      TestThread t = new TestThread();
      t.start();
      t.join();
      Vector<StringBuffer> v = new Vector<StringBuffer>();
      try {
        while (true) {
          v.add(new StringBuffer(10000));
        }
      } catch (OutOfMemoryError ofme) {
        v = null;
      }
    } catch (InterruptedException e) {
      fail("InterruptedException : " + e.getMessage());
    }

    assertNull("get() should return null " + "if OutOfMemoryError is thrown.", r.get());

    try {
      TestThread t = new TestThread();
      t.start();
      t.join();
      System.gc();
      System.runFinalization();
      ref = rq.poll();
      assertNotNull("Object not garbage collected.", ref);
      assertNull("Object is not null.", ref.get());
      assertNotNull("Object could not be reclaimed.", r.get());
    } catch (Exception e) {
      fail("Exception : " + e.getMessage());
    }
  }
Example #12
0
 public static <K, V> void clearCache(
     ReferenceQueue rq, ConcurrentHashMap<K, Reference<V>> cache) {
   // cleanup any dead entries
   if (rq.poll() != null) {
     while (rq.poll() != null) ;
     for (Map.Entry<K, Reference<V>> e : cache.entrySet()) {
       if (e.getValue().get() == null) cache.remove(e.getKey(), e.getValue());
     }
   }
 }
    public void expungeStaleEntries() {
      Reference<? extends Image> ref = queue.poll();
      while (ref != null) {
        Texture texture = remove(ref);
        if (texture != null) {
          destroy(texture);
        }

        ref = queue.poll();
      }
    }
 public static void main(String[] args) {
   String str = new String("Hello Java!");
   ReferenceQueue<String> rq = new ReferenceQueue<String>();
   // 創建一個虛引用,指向Hello Java!
   PhantomReference<String> pr = new PhantomReference<String>(str, rq);
   str = null;
   // 不能通過虛引用訪問被引用對象,所以此處為null
   System.out.println(pr.get());
   System.gc();
   System.runFinalization();
   // 當被引用的對象回收后,虛引用將被放入引用隊列中
   System.out.println(rq.poll() == pr);
 }
 private void gcCache() {
   if (cacheReferenceQueue.poll() != null) {
     while (cacheReferenceQueue.poll() != null) {
       // clear the queue
     }
     for (Iterator<Reference<Object>> i = cache.values().iterator(); i.hasNext(); ) {
       Reference<Object> reference = i.next();
       if (reference.isEnqueued()) {
         i.remove();
       }
     }
   }
 }
  private static void gc() throws InterruptedException {
    ReferenceQueue<Object> referenceQueue = new ReferenceQueue<Object>();

    WeakReference<Object> weakReference = new WeakReference<Object>(new Object(), referenceQueue);

    while (weakReference.get() != null) {
      System.gc();

      System.runFinalization();
    }

    Assert.assertSame(weakReference, referenceQueue.remove());
  }
  /**
   * Disposes of any references that are no longer alive. Private helper method to remove the weak
   * references from the listener map.
   */
  private <T> void disposeReferences(Class<T> eventClass) {

    if (listenerMap.containsKey(eventClass)) {

      Set<Reference> referenceSet = Collections.emptySet();
      Reference ref = queue.poll();

      while (ref != null) {
        referenceSet.add(ref);
        ref = queue.poll();
      }

      listenerMap.get(eventClass).removeAll(referenceSet);
    }
  }
Example #18
0
  /** Removes all of the mappings from this map. The map will be empty after this call returns. */
  public void clear() {
    // clear out ref queue. We don't need to expunge entries
    // since table is getting cleared.
    while (queue.poll() != null) ;

    modCount++;
    Entry[] tab = table;
    for (int i = 0; i < tab.length; ++i) tab[i] = null;
    size = 0;

    // Allocation of array may have caused GC, which may have caused
    // additional entries to go stale.  Removing these entries from the
    // reference queue will make them eligible for reclamation.
    while (queue.poll() != null) ;
  }
  /** Cleans up any lingering state held by unrefeernced DesktopProperties. */
  static void flushUnreferencedProperties() {
    WeakPCL pcl;

    while ((pcl = (WeakPCL) queue.poll()) != null) {
      pcl.dispose();
    }
  }
 @SuppressWarnings("rawtypes")
 final void removeStale() {
   WeakKeyReference ref;
   while ((ref = (WeakKeyReference) refQueue.poll()) != null) {
     remove(ref.keyRef(), ref.keyHash(), null, true);
   }
 }
Example #21
0
  /** Expunges stale entries from the table. */
  private void expungeStaleEntries() {
    Entry<K, V> e;
    while ((e = (Entry<K, V>) queue.poll()) != null) {
      int h = e.hash;
      int i = indexFor(h, table.length);

      Entry<K, V> prev = table[i];
      Entry<K, V> p = prev;
      while (p != null) {
        Entry<K, V> next = p.next;
        if (p == e) {
          if (prev == e) table[i] = next;
          else {
            prev.next = next;
            if (prev == next) {
              throw new RuntimeException("circular");
            }
          }
          e.next = null; // Help GC
          e.key = null; //  "   "
          size--;
          break;
        }
        prev = p;
        p = next;
      }
    }
  }
 /**
  * Here we go through the ReferenceQueue and remove garbage collected SoftValue objects from the
  * HashMap by looking them up using the SoftValue.m_aKey data member.
  */
 @SuppressWarnings("unchecked")
 private void _processQueue() {
   SoftValue<K, V> aSoftValue;
   while ((aSoftValue = ((SoftValue<K, V>) m_aQueue.poll())) != null) {
     m_aSrcMap.remove(aSoftValue.m_aKey);
   }
 }
 public boolean queueIdle() {
   e e = (e) queue.poll();
   if (e != null) {
     activeResources.remove(e.access._mth000(e));
   }
   return true;
 }
 private static void drainRefQueueBounded() {
   while (true) {
     CipherContextRef next = (CipherContextRef) refQueue.poll();
     if (next == null) break;
     next.dispose(true);
   }
 }
Example #25
0
  /**
   * Cleans up a single reference. Catches and logs all throwables.
   *
   * @return true if the caller should continue, false if the associated FinalizableReferenceQueue
   *     is no longer referenced.
   */
  private boolean cleanUp(Reference<?> reference) {
    Method finalizeReferentMethod = getFinalizeReferentMethod();
    if (finalizeReferentMethod == null) {
      return false;
    }
    do {
      /*
       * This is for the benefit of phantom references. Weak and soft references will have already
       * been cleared by this point.
       */
      reference.clear();

      if (reference == frqReference) {
        /*
         * The client no longer has a reference to the FinalizableReferenceQueue. We can stop.
         */
        return false;
      }

      try {
        finalizeReferentMethod.invoke(reference);
      } catch (Throwable t) {
        logger.log(Level.SEVERE, "Error cleaning up after reference.", t);
      }

      /*
       * Loop as long as we have references available so as not to waste CPU looking up the Method
       * over and over again.
       */
    } while ((reference = queue.poll()) != null);
    return true;
  }
 /**
  * An incremental, poll-based expunger.
  *
  * <p>Package-protected for unit-test visibility.
  */
 @SuppressWarnings("unchecked")
 synchronized void pageOutStaleEntries() {
   int c = 0;
   long startTime = System.currentTimeMillis();
   for (SoftEntry<V> entry; (entry = (SoftEntry<V>) refQueue.poll()) != null; ) {
     pageOutStaleEntry(entry);
     c++;
   }
   if (c > 0 && logger.isLoggable(Level.FINER)) {
     long endTime = System.currentTimeMillis();
     try {
       logger.finer(
           "DB: "
               + db.getDatabaseName()
               + ",  Expunged: "
               + c
               + ", Diskmap size: "
               + diskMap.size()
               + ", Cache size: "
               + memMap.size()
               + ", in "
               + (endTime - startTime)
               + "ms");
     } catch (DatabaseException e) {
       logger.log(Level.FINER, "exception while logging", e);
     }
   }
 }
 public static void checkQueue() {
   // 需要通过Reference访问这些对象,但是对象还是被回收了
   Reference<? extends VeryBig> inq = rq.poll();
   if (inq != null) {
     System.out.println("In queue: " + inq.get());
   }
 }
 /**
  * Internal method to keep track of weak references and remove the enqueued references from
  * listener list by polling the reference queue.
  */
 @SuppressWarnings("unchecked")
 private static void removeEnqueuedReference() {
   WeakReference<KeyValueChangeListener> toRemove;
   while ((toRemove = (WeakReference<KeyValueChangeListener>) sRefQueue.poll()) != null) {
     sListeners.remove(toRemove);
   }
 }
Example #29
0
 public static void main(String[] args) throws Exception {
   // 创建一个字符串对象
   String str = new String("Struts2权威指南");
   // 创建一个引用队列
   ReferenceQueue rq = new ReferenceQueue();
   // 创建一个虚引用,让此虚引用引用到"Struts2权威指南"字符串
   PhantomReference pr = new PhantomReference(str, rq);
   // 切断str引用和"Struts2权威指南"字符串之间的引用
   str = null;
   // 取出虚引用所引用的对象,并不能通过虚引用访问被引用的对象,所以此处输出null
   System.out.println(pr.get());
   // 强制垃圾回收
   System.gc();
   System.runFinalization();
   // 取出引用队列中最先进入队列中引用与pr进行比较
   System.out.println(rq.poll() == pr);
 }
Example #30
0
 /*
  * This method requires external synchronization.
  * The logically uninterruptible pragma is a bold faced lie;
  * injecting it for now to avoid a warning message during the build
  * that users might find confusing. We think the problem is actually
  * not a 'real' problem...
  * FIXME update comment
  */
 public boolean enqueue() {
   if (nextOnQueue == null && queue != null) {
     queue.enqueue(this);
     queue = null;
     return true;
   }
   return false;
 }