public static void checkQueue() {
   // 需要通过Reference访问这些对象,但是对象还是被回收了
   Reference<? extends VeryBig> inq = rq.poll();
   if (inq != null) {
     System.out.println("In queue: " + inq.get());
   }
 }
Example #2
0
  @Test
  public void testLifecycle() throws Exception {
    Timer timer = SettingsRefreshInterval.timer;
    RefreshInterval interval = SettingsRefreshInterval.CLASSPATH;
    interval.setMilliseconds(1);
    PS ps = new PS(interval);
    Settings s = new SettingsBuilder().add(ps).build();
    Reference<Settings> ref = new WeakReference<>(s);
    Thread.sleep(20);
    int cc = ps.callCount;
    assertNotSame("Refresh task not called", 0, cc);
    Thread.sleep(20);
    assertNotSame("Refresh task not being called continuously", cc, ps.callCount);
    s = null;
    for (int i = 0; i < 10; i++) {
      System.gc();
      if (ref.get() == null) {
        break;
      }
      Thread.sleep(200);
    }
    assertNull("Settings not garbage collected", ref.get());

    cc = ps.callCount;
    Thread.sleep(30);
    assertSame(
        "Settings garbage collected, but its internals are " + "still being refreshed",
        cc,
        ps.callCount);
  }
Example #3
0
  public static synchronized RegionFile createOrLoadRegionFile(File par0File, int par1, int par2) {
    File file = new File(par0File, "region");
    File file1 =
        new File(
            file,
            (new StringBuilder())
                .append("r.")
                .append(par1 >> 5)
                .append(".")
                .append(par2 >> 5)
                .append(".mca")
                .toString());
    Reference reference = (Reference) regionsByFilename.get(file1);

    if (reference != null) {
      RegionFile regionfile = (RegionFile) reference.get();

      if (regionfile != null) {
        return regionfile;
      }
    }

    if (!file.exists()) {
      file.mkdirs();
    }

    if (regionsByFilename.size() >= 256) {
      clearRegionFileReferences();
    }

    RegionFile regionfile1 = new RegionFile(file1);
    regionsByFilename.put(file1, new SoftReference(regionfile1));
    return regionfile1;
  }
 /**
  * Create CachedIntrospectionResults for the given bean class.
  *
  * <p>We don't want to use synchronization here. Object references are atomic, so we can live with
  * doing the occasional unnecessary lookup at startup only.
  *
  * @param beanClass the bean class to analyze
  * @return the corresponding CachedIntrospectionResults
  * @throws BeansException in case of introspection failure
  */
 static CachedIntrospectionResults forClass(Class beanClass) throws BeansException {
   CachedIntrospectionResults results = null;
   Object value = classCache.get(beanClass);
   if (value instanceof Reference) {
     Reference ref = (Reference) value;
     results = (CachedIntrospectionResults) ref.get();
   } else {
     results = (CachedIntrospectionResults) value;
   }
   if (results == null) {
     // can throw BeansException
     results = new CachedIntrospectionResults(beanClass);
     if (ClassUtils.isCacheSafe(beanClass, CachedIntrospectionResults.class.getClassLoader())
         || isClassLoaderAccepted(beanClass.getClassLoader())) {
       classCache.put(beanClass, results);
     } else {
       if (logger.isDebugEnabled()) {
         logger.debug(
             "Not strongly caching class ["
                 + beanClass.getName()
                 + "] because it is not cache-safe");
       }
       classCache.put(beanClass, new WeakReference(results));
     }
   }
   return results;
 }
  public void testDocumentGced() throws Exception {
    VirtualFile vFile = createFile();
    PsiDocumentManagerImpl documentManager = getPsiDocumentManager();
    long id = System.identityHashCode(documentManager.getDocument(getPsiManager().findFile(vFile)));

    documentManager.commitAllDocuments();
    UIUtil.dispatchAllInvocationEvents();
    UIUtil.dispatchAllInvocationEvents();
    assertEmpty(documentManager.getUncommittedDocuments());

    LeakHunter.checkLeak(documentManager, DocumentImpl.class);
    LeakHunter.checkLeak(
        documentManager,
        PsiFileImpl.class,
        new Processor<PsiFileImpl>() {
          @Override
          public boolean process(PsiFileImpl psiFile) {
            return psiFile.getViewProvider().getVirtualFile().getFileSystem()
                instanceof LocalFileSystem;
          }
        });
    // Class.forName("com.intellij.util.ProfilingUtil").getDeclaredMethod("forceCaptureMemorySnapshot").invoke(null);

    Reference<Document> reference = vFile.getUserData(FileDocumentManagerImpl.DOCUMENT_KEY);
    assertNotNull(reference);
    for (int i = 0; i < 1000; i++) {
      UIUtil.dispatchAllInvocationEvents();
      if (reference.get() == null) break;
      System.gc();
    }
    assertNull(documentManager.getCachedDocument(getPsiManager().findFile(vFile)));

    Document newDoc = documentManager.getDocument(getPsiManager().findFile(vFile));
    assertTrue(id != System.identityHashCode(newDoc));
  }
 @Override
 public <A> boolean compareAndSwap(
     long recid, A expectedOldValue, A newValue, Serializer<A> serializer) {
   commitLock.readLock().lock();
   try {
     uncommitedData = true;
     Lock lock = locks[Store.lockPos(recid)].writeLock();
     lock.lock();
     try {
       boolean ret = super.compareAndSwap(recid, expectedOldValue, newValue, serializer);
       if (ret) {
         for (Reference<Tx> txr : txs) {
           Tx tx = txr.get();
           if (tx == null) continue;
           tx.old.putIfAbsent(recid, expectedOldValue);
         }
       }
       return ret;
     } finally {
       lock.unlock();
     }
   } finally {
     commitLock.readLock().unlock();
   }
 }
  @Override
  public Dataset getDataset(IMonitor mon, SliceND slice) throws IOException {

    if (slice.isAll()) {
      try {
        return getCompleteData(mon);
      } catch (Exception e) {
        throw new IOException("Cannot read " + path + ", " + fullPath, e);
      }
    }

    final SliceObject so = new SliceObject();
    so.setPath(path);
    so.setName(fullPath);
    so.setSlicedShape(slice.getSourceShape());
    so.setSliceStart(slice.getStart());
    so.setSliceStop(slice.getStop());
    so.setSliceStep(slice.getStep());

    if (cache.containsKey(so)) {
      final Reference<Dataset> sr = cache.get(so);
      if (sr.get() != null) {
        return sr.get();
      }
    }
    try {
      Dataset set = loader.slice(so, mon);
      cache.put(so, new SoftReference<Dataset>(set));
      return set;
    } catch (Exception e) {
      throw new IOException("Cannot slice " + path + ", " + fullPath, e);
    }
  }
Example #8
0
 @Override
 public void resultChanged(LookupEvent ev) {
   TopComponent tc = ref.get();
   if (tc == null) {
     r.removeLookupListener(this);
     synchronized (lookupListeners) {
       lookupListeners.remove(this);
     }
     return;
   }
   if (LOG.isLoggable(Level.FINER)) {
     LOG.log(Level.FINER, "  looking result changed for {0} ", new Object[] {ref.get()});
   }
   DataObject tcDataObject = tc.getLookup().lookup(DataObject.class);
   if (tcDataObject != null) {
     try {
       if (hasOpenedEditorPanes(tcDataObject)) {
         addOpenedFiles(getFiles(tcDataObject));
       }
     } catch (InterruptedException ex) {
       LOG.log(Level.WARNING, null, ex);
     } catch (InvocationTargetException ex) {
       LOG.log(Level.WARNING, null, ex);
     }
     r.removeLookupListener(this);
     synchronized (lookupListeners) {
       lookupListeners.remove(this);
     }
   }
 }
Example #9
0
 private void fireRefreshEvent() {
   final RefreshEvent event = new RefreshEvent(this);
   expungeRefreshListeners();
   for (final Reference<RefreshListener> reference : refreshListeners) {
     final RefreshListener listener = reference.get();
     if (listener != null) listener.onRefresh(event);
   }
 }
 public Object peek(final Object key) {
   Object stored = cache.get(key);
   if (stored instanceof Reference) {
     Reference reference = (Reference) stored;
     return reference.get();
   }
   return stored;
 }
 public synchronized Object find(Object key) throws Exception {
   Reference ref = (Reference) store.get(key);
   Object out;
   if (ref == null || (out = ref.get()) == null || isDirty(key, out)) {
     out = createFromKey(key);
     store.put(key, new SoftReference(out));
   }
   return out;
 }
Example #12
0
  public V get(Object key) {
    Reference<V> valueReference = _map.get(key);

    if (valueReference != null) {
      return valueReference.get();
    }

    return null;
  }
Example #13
0
    public V next() {
      Reference<V> valueReference = _iterator.next();

      if (valueReference != null) {
        return valueReference.get();
      }

      return null;
    }
Example #14
0
    public V getValue() {
      Reference<V> valueReference = _entry.getValue();

      if (valueReference != null) {
        return valueReference.get();
      }

      return null;
    }
  @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 #16
0
 /** Remove this allocation from the connection's list of allocations. */
 private void release(RealConnection connection) {
   for (int i = 0, size = connection.allocations.size(); i < size; i++) {
     Reference<StreamAllocation> reference = connection.allocations.get(i);
     if (reference.get() == this) {
       connection.allocations.remove(i);
       return;
     }
   }
   throw new IllegalStateException();
 }
 private <T> T getCached(String key, Class<T> type) {
   synchronized (cache) {
     gcCache();
     Reference<Object> reference = cache.get(key);
     if (reference != null) {
       return type.cast(reference.get());
     }
   }
   return null;
 }
Example #18
0
 private static synchronized TerminalImpl implGetTerminal(String name) {
   Reference<TerminalImpl> ref = terminals.get(name);
   TerminalImpl terminal = (ref != null) ? ref.get() : null;
   if (terminal != null) {
     return terminal;
   }
   terminal = new TerminalImpl(contextId, name);
   terminals.put(name, new WeakReference<TerminalImpl>(terminal));
   return terminal;
 }
Example #19
0
    /**
     * Unsubscribe from notifications. Note: calling with 'null' will clean-up the weakly referenced
     * array but this is not necessary as the Enumeration will skip them as needed.
     *
     * @param listenable removal happens automatically by Weak ref when no other Strongly reachable
     *     objects refer to it.
     */
    @SuppressWarnings("unchecked")
    @Override
    public synchronized void removeListener(final L listenable) {
      if (vNoGcListeners != null) {
        if (vNoGcListeners.length > 1) {
          final NotificationListenable[] srcArray = vNoGcListeners;
          final int atIndex = Util.indexOfIdentity(listenable, srcArray);
          if (atIndex != Util.INVALID_INDEX) { // got one, perform slice that removes identity
            final int lengthMinusOne = srcArray.length - 1;
            final NotificationListenable[] destArray = new NotificationListenable[lengthMinusOne];
            if (atIndex != lengthMinusOne)
              System.arraycopy(
                  srcArray,
                  atIndex + 1,
                  destArray,
                  atIndex,
                  lengthMinusOne - atIndex); // fill in from after removeRef
            if (atIndex != 0)
              System.arraycopy(srcArray, 0, destArray, 0, atIndex); // fill in from before removeRef
            vNoGcListeners = destArray;
            return;
          }
        } else if (vNoGcListeners[0] == listenable) { // length must be 1
          vNoGcListeners =
              null; // safely releases array while other observers may still be iterating thru it
          return;
        }
        // else might be weakly listening
      }
      // else might be weakly listening

      if (vWeakListeners != null) {
        if (vWeakListeners.length
            > 1) { // safe to assume the listener is present, rebuild the array without it or any
                   // weakly GC'd refs
          final Reference<L>[] srcRefs = vWeakListeners;
          final List<Reference<L>> refList = new ArrayList<Reference<L>>(srcRefs.length);
          for (final Reference<L> ref : srcRefs) {
            final L listener = ref.get();
            if (listener != listenable && listener != null) {
              refList.add(ref);
            }
            // else drop the ref-to-remove or weakly GC'd ref by not adding
          }

          vWeakListeners =
              (refList.isEmpty() == false) ? refList.toArray(new Reference[refList.size()]) : null;
        } else if (vWeakListeners[0].get() == listenable) { // length must be 1
          vWeakListeners =
              null; // safely releases array while other observers may still be iterating thru it
        }
        // else ignore
      }
      // else equivalent to length=0
    }
 public <T, ID> T updateId(Class<T> clazz, ID oldId, ID newId) {
   Map<Object, Reference<Object>> objectMap = getMapForClass(clazz);
   Reference<Object> ref = objectMap.remove(oldId);
   if (ref == null) {
     return null;
   }
   objectMap.put(newId, ref);
   @SuppressWarnings("unchecked")
   T castObj = (T) ref.get();
   return castObj;
 }
Example #21
0
  public V put(K key, V value) {
    Reference<V> valueReference = wrapValue(key, value);

    valueReference = _map.putIfAbsent(key, valueReference);

    if (valueReference != null) {
      return valueReference.get();
    }

    return null;
  }
Example #22
0
 private void dispatch(Integer type, SBPMessage msg) {
   List<Reference<SBPCallback>> cblist = callbacks.get(type);
   for (Reference<SBPCallback> wr : cblist) {
     SBPCallback cb = wr.get();
     if (cb != null) {
       cb.receiveCallback(msg);
     } else {
       cblist.remove(wr);
     }
   }
 }
Example #23
0
  public V replace(K key, V value) {
    Reference<V> valueReference = wrapValue(key, value);

    valueReference = _map.replace(key, valueReference);

    if (valueReference != null) {
      return valueReference.get();
    }

    return null;
  }
Example #24
0
 public T erase(String identifier) {
   synchronized (mLockList) {
     Lock l = mLockList.remove(identifier);
     Reference<T> rval = mEntryList.remove(identifier);
     if (l != null) l.unlock();
     if (rval == null) {
       return null;
     }
     return rval.get();
   }
 }
Example #25
0
 /**
  * Tests weak and soft references for identity equality. Compares references to other references
  * and wrappers. If o is a reference, this returns true if r == o or if r and o reference the same
  * non-null object. If o is a wrapper, this returns true if r's referent is identical to the
  * wrapped object.
  */
 private static boolean referenceEquals(Reference r, Object o) {
   if (o instanceof InternalReference) { // compare reference to reference.
     if (o == r) { // are they the same reference? used in cleanup.
       return true;
     }
     Object referent =
         ((Reference) o).get(); // do they reference identical values? used in conditional puts.
     return referent != null && referent == r.get();
   }
   return ((ReferenceAwareWrapper) o).unwrap()
       == r.get(); // is the wrapped object identical to the referent? used in lookups.
 }
Example #26
0
 public void removeCallback(SBPCallback cb) {
   synchronized (callbacks) {
     for (List<Reference<SBPCallback>> cblist : callbacks.values()) {
       for (Reference<SBPCallback> ref : cblist) {
         if (ref.get() == cb) {
           cblist.remove(ref);
         }
       }
     }
     strongCallbacks.remove(cb);
   }
 }
 /**
  * Returns the indicated object from the cache, or null if not found.
  *
  * @param key The authority code.
  */
 public Object get(final Object key) {
   Object stored = cache.get(key);
   if (stored instanceof Reference) {
     Reference reference = (Reference) stored;
     Object value = reference.get();
     if (value == null) {
       cache.remove(key);
     }
     return value;
   }
   return stored;
 }
  /**
   * Un-registers listener is there's one.
   *
   * @param listener a listener to unregister from config changes.
   * @see #registerListener(OnConfigChangedListener)
   */
  public final void unregisterListener(@NonNull OnConfigChangedListener listener) {
    synchronized (mListenersRefs) {
      for (Reference<OnConfigChangedListener> ref : mListenersRefs) {
        if (ref.get() == listener) {
          removeListenerRef(ref);
          return;
        }
      }

      Log.w(TAG, "Tried to unregister non-existent listener!");
    }
  }
Example #29
0
 protected Class<?> findClass(String name) throws ClassNotFoundException {
   Reference<Class> cr = classCache.get(name);
   if (cr != null) {
     Class c = cr.get();
     if (c != null) {
       return c;
     } else {
       classCache.remove(name, cr);
     }
   }
   return super.findClass(name);
 }
  public synchronized T intern(T object) {
    Reference<T> pooledRef = objects.get(object);
    if (pooledRef != null) {
      T pooled = pooledRef.get();
      if (pooled != null) {
        return pooled;
      }
    }

    objects.put(object, new WeakReference<T>(object));
    return object;
  }