示例#1
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);
  }
示例#2
0
  @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);
    }
  }
示例#3
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);
     }
   }
 }
示例#4
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.
 }
 @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();
   }
 }
示例#6
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));
  }
 public static void checkQueue() {
   // 需要通过Reference访问这些对象,但是对象还是被回收了
   Reference<? extends VeryBig> inq = rq.poll();
   if (inq != null) {
     System.out.println("In queue: " + inq.get());
   }
 }
示例#10
0
 File getAbsoluteFile() {
   File absFile = (absFileRef == null ? null : absFileRef.get());
   if (absFile == null) {
     absFile = zipFile.getAbsoluteFile();
     absFileRef = new SoftReference<File>(absFile);
   }
   return absFile;
 }
示例#11
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;
 }
示例#13
0
 /**
  * Semantics is similar to {@link org.openide.windows.TopComponent#getActivatedNodes()} except
  * that this method returns File objects instead od Nodes. Every node is examined for Files it
  * represents. File and Folder nodes represent their underlying files or folders. Project nodes
  * are represented by their source groups. Other logical nodes must provide FileObjects in their
  * Lookup.
  *
  * @return File [] array of activated files
  * @param nodes or null (then taken from windowsystem, it may be wrong on editor tabs #66700).
  */
 public static Context getCurrentContext(Node[] nodes) {
   if (nodes == null) {
     nodes = TopComponent.getRegistry().getActivatedNodes();
   }
   if (Arrays.equals(contextNodesCached.get(), nodes)) {
     Context ctx = contextCached.get();
     if (ctx != null) return ctx;
   }
   VCSContext vcsCtx = VCSContext.forNodes(nodes);
   Context ctx =
       new Context(
           new HashSet(vcsCtx.computeFiles(cvsFileFilter)),
           new HashSet(vcsCtx.getRootFiles()),
           new HashSet(vcsCtx.getExclusions()));
   contextCached = new WeakReference<Context>(ctx);
   contextNodesCached = new WeakReference<Node[]>(nodes);
   return ctx;
 }
示例#14
0
    public V getValue() {
      Reference<V> valueReference = _entry.getValue();

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

      return null;
    }
示例#15
0
    public V next() {
      Reference<V> valueReference = _iterator.next();

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

      return null;
    }
示例#16
0
  public V get(Object key) {
    Reference<V> valueReference = _map.get(key);

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

    return null;
  }
 void deregister(Reference<? extends Adapter> listenerRef) {
   Adapter adapter = listenerRef.get();
   if (adapter == null) {
     // WeakHashMaps with adapter as key don't need to be taken care of anymore
     registrationManager.deregister(listenerRef);
   } else {
     deregister(adapter);
   }
 }
示例#18
0
 @Override
 public Controller getController() {
   GdbAttachPanel panel = customizerRef.get();
   if (panel != null) {
     return panel.getController();
   } else {
     return null;
   }
 }
 public void close() {
   if (!isClosed()) {
     isClosed = true;
     final K key = keyRef.get();
     if (key != null) {
       removeResource(key, this, isShared);
     }
   }
 }
示例#20
0
 private static ResourceBundle getBundle() {
   ResourceBundle bundle = null;
   if (ourBundle != null) bundle = ourBundle.get();
   if (bundle == null) {
     bundle = ResourceBundle.getBundle(BUNDLE);
     ourBundle = new SoftReference<ResourceBundle>(bundle);
   }
   return bundle;
 }
 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;
 }
示例#22
0
  @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());
    }
  }
 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;
 }
示例#24
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();
 }
示例#25
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;
 }
示例#26
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
    }
示例#27
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();
   }
 }
示例#28
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;
 }
示例#29
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);
     }
   }
 }
示例#30
-1
 public void actionPerformed(ActionEvent e) {
   JTextComponent c = (JTextComponent) componentRef.get();
   if (c != null) { // Override action event to text component
     e = new ActionEvent(c, e.getID(), e.getActionCommand());
   }
   delegate.actionPerformed(e);
 }