public static synchronized List<CreatorBasedLazyFixList> getAndClearToCompute(FileObject file) { List<Reference<CreatorBasedLazyFixList>> references = file2Creators.get(file); if (references == null) { return Collections.emptyList(); } List<CreatorBasedLazyFixList> result = new ArrayList<CreatorBasedLazyFixList>(); for (Reference<CreatorBasedLazyFixList> r : references) { CreatorBasedLazyFixList c = r.get(); if (c != null) { result.add(c); } } references.clear(); return result; }
/** * Removes weak keys from the map that have been enqueued * on the reference queue and are no longer in use. */ private static void processQueue(ReferenceQueue<Key> queue, ConcurrentHashMap<? extends WeakReference<Key>, ?> pdMap) { Reference<? extends Key> ref; while ((ref = queue.poll()) != null) { pdMap.remove(ref); } }
@SuppressWarnings("ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD") @RandomlyFails public void testMemoryReleased() throws Exception { TimedWeakReference.TIMEOUT = 0; FileObject wd = FileUtil.toFileObject(getWorkDir()); TestFileUtils.writeFile(wd, "pom.xml", "<project><modelVersion>4.0.0</modelVersion>" + "<groupId>g</groupId><artifactId>a</artifactId>" + "<version>0</version></project>"); Project p = ProjectManager.getDefault().findProject(wd); ((NbMavenProjectImpl) p).attachUpdater(); /* Want to avoid leaks even if this is not called for some reason: ((NbMavenProjectImpl) p).detachUpdater(); */ Reference<?> r = new WeakReference<Object>(p); p = null; Thread.sleep(5000); //something has changed and the reference only gets cleared after some time. added @RandomlyFails // if it keeps on failing regularly, it's a candidate for removal, the point of the test is unclear to me. assertGC("can release project after updater detached", r, Collections.singleton(wd)); }
@Override public boolean equals(Object obj) { if (this == obj) { return true; } if (dead) { // Post-mortem cleanup looks for this specific Reference // instance return false; } if (!(obj instanceof Reference<?>)) { return false; } Object oA = get(); Object oB = ((Reference<?>) obj).get(); if (oA == oB) { return true; } if (oA == null || oB == null) { return false; } return oA.equals(oB); }
/** @return all active DataShadows or null */ private static synchronized List<BrokenDataShadow> getAllDataShadows() { if (allDataShadows == null || allDataShadows.isEmpty()) { return null; } List<BrokenDataShadow> ret = new ArrayList<BrokenDataShadow>(allDataShadows.size()); Iterator<Set<Reference<BrokenDataShadow>>> it = allDataShadows.values ().iterator(); while (it.hasNext()) { Set<Reference<BrokenDataShadow>> ref = it.next(); Iterator<Reference<BrokenDataShadow>> refs = ref.iterator (); while (refs.hasNext ()) { Reference<BrokenDataShadow> r = refs.next (); BrokenDataShadow shadow = r.get(); if (shadow != null) { ret.add(shadow); } } } return ret; }
private synchronized Object findLiveManagers() { JavaElementFoldManager oneMgr = null; List<JavaElementFoldManager> result = null; for (Iterator<Reference<JavaElementFoldManager>> it = managers.iterator(); it.hasNext(); ) { Reference<JavaElementFoldManager> ref = it.next(); JavaElementFoldManager fm = ref.get(); if (fm == null) { it.remove(); continue; } if (result != null) { result.add(fm); } else if (oneMgr != null) { result = new ArrayList<JavaElementFoldManager>(2); result.add(oneMgr); result.add(fm); } else { oneMgr = fm; } } return result != null ? result : oneMgr; }
NbTask toNbTask (ITask task) { NbTask nbTask = null; if (task != null) { synchronized (tasks) { Reference<NbTask> nbTaskRef = tasks.get(task); if (nbTaskRef != null) { nbTask = nbTaskRef.get(); } if (nbTask == null) { nbTask = new NbTask(task); tasks.put(task, new SoftReference<NbTask>(nbTask)); } } } return nbTask; }
static void testCleanupSecret(String algorithm) throws Exception { KeyGenerator desGen = KeyGenerator.getInstance(algorithm, SunJCEProvider); SecretKey key = desGen.generateKey(); // Break into the implementation to observe the key byte array. Class<?> keyClass = key.getClass(); Field keyField = keyClass.getDeclaredField("key"); keyField.setAccessible(true); byte[] array = (byte[])keyField.get(key); byte[] zeros = new byte[array.length]; do { // Wait for array to be cleared; if not cleared test will timeout System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array)); key = null; System.gc(); // attempt to reclaim the key } while (Arrays.compare(zeros, array) != 0); System.out.printf("%s array: %s%n", algorithm, Arrays.toString(array)); Reference.reachabilityFence(key); // Keep key alive Reference.reachabilityFence(array); // Keep array alive }
private Task detach() { Task t; synchronized (allSessions) { Reference<ShellSession> refS = allSessions.get(consoleDocument); if (refS != null && refS.get() == this) { allSessions.remove(consoleDocument); detached = true; } else { return Task.EMPTY; } } // closed = true; model.detach(); closed(); if (exec != null) { FORCE_CLOSE_RP.post(this::forceCloseStreams, 300); } // leave the model gsm.getGuardedSections().forEach((GuardedSection gs) -> gs.removeSection()); return sendJShellClose(); }
public void testLookupsRelease() { int idA = System.identityHashCode(MimeLookup.getLookup(MimePath.get("text/x-java"))); TestUtilities.consumeAllMemory(); TestUtilities.gc(); MimePath mp = MimePath.get("text/x-java"); Object obj = MimeLookup.getLookup(mp); int idB = System.identityHashCode(obj); assertEquals("Lookup instance was lost", idA, idB); // Force the MimePath instance to be dropped from the list of recently used for (int i = 0; i < MimePath.MAX_LRU_SIZE; i++) { MimePath.get("text/x-nonsense-" + i); } Reference<Object> ref = new WeakReference<Object>(obj); obj = null; mp = null; assertGC("Can disappear", ref); int idC = System.identityHashCode(MimeLookup.getLookup(MimePath.get("text/x-java"))); assertTrue("Lookup instance was not released", idA != idC); }
/** * Purges the specified reference * @param ref the reference to purge * @return true or false */ boolean purge(final Reference<?> ref) { boolean r = parent.keyType != ReferenceStrength.HARD && key == ref; r = r || parent.valueType != ReferenceStrength.HARD && value == ref; if (r) { if (parent.keyType != ReferenceStrength.HARD) { ((Reference<?>) key).clear(); } if (parent.valueType != ReferenceStrength.HARD) { ((Reference<?>) value).clear(); } else if (parent.purgeValues) { value = null; } } return r; }
private static ClassPath getJavacApiJarClasspath() { Reference<ClassPath> r = javacApiClasspath; ClassPath res = r.get(); if (res != null) { return res; } if (r == NONE) { return null; } CodeSource codeSource = Modifier.class.getProtectionDomain().getCodeSource(); URL javacApiJar = codeSource != null ? codeSource.getLocation() : null; if (javacApiJar != null) { Logger.getLogger(DeclarativeHintsParser.class.getName()).log(Level.FINE, "javacApiJar={0}", javacApiJar); File aj = FileUtil.archiveOrDirForURL(javacApiJar); if (aj != null) { res = ClassPathSupport.createClassPath(FileUtil.urlForArchiveOrDir(aj)); javacApiClasspath = new WeakReference<>(res); return res; } } javacApiClasspath = NONE; return null; }
/** * Repeatedly dequeues references from the queue and invokes {@link * FinalizableReference#finalizeReferent()} on them until the queue is empty. This method is a * no-op if the background thread was created successfully. */ void cleanUp() { if (threadStarted) { return; } Reference<?> reference; while ((reference = queue.poll()) != null) { /* * This is for the benefit of phantom references. Weak and soft references will have already * been cleared by this point. */ reference.clear(); try { ((FinalizableReference) reference).finalizeReferent(); } catch (Throwable t) { logger.log(Level.SEVERE, "Error cleaning up after reference.", t); } } }
public void testNodeListenersDetachedAtFinalizeIssue58065() throws Exception { CookieNode node = new CookieNode(); SimpleCookieAction2 sca = new SimpleCookieAction2(); Action action = sca.createContextAwareInstance(node.getLookup()); class NodeListenerMemoryFilter implements MemoryFilter { public int numofnodelisteners = 0; public boolean reject(Object obj) { numofnodelisteners += (obj instanceof NodeListener)?1:0; return !((obj instanceof EventListenerList) | (obj instanceof Object[])); } } NodeListenerMemoryFilter filter = new NodeListenerMemoryFilter(); assertSize("",Arrays.asList( new Object[] {node} ),1000000,filter); assertTrue("Node is expected to have a NodeListener attached", filter.numofnodelisteners > 0); Reference actionref = new WeakReference(sca); sca = null; action = null; assertGC("CookieAction is supposed to be GCed", actionref); NodeListenerMemoryFilter filter2 = new NodeListenerMemoryFilter(); assertSize("",Arrays.asList( new Object[] {node} ),1000000,filter2); assertEquals("Node is expected to have no NodeListener attached", 0, filter2.numofnodelisteners); }
public void testSourceForDocumentGCed() throws IOException { FileObject file = createFileObject("plain.txt", getName(), "\n"); Document doc = openDocument(file); Source source = Source.create(doc); assertNotNull("No Source for " + doc, source); Reference<Source> sourceRef = new WeakReference<Source>(source); Reference<Document> docRef = new WeakReference<Document>(doc); Reference<FileObject> fileRef = new WeakReference<FileObject>(file); source = null; assertGC("Source can't be GCed", sourceRef); doc = null; assertGC("Document can't be GCed", docRef); file = null; assertGC("FileObject can't be GCed", fileRef); }
public static boolean fenced() { AtomicBoolean finalized = new AtomicBoolean(); MyFinalizeable o = new MyFinalizeable(finalized); for (int i = 0; i < LOOP_ITERS; i++) { if (finalized.get()) break; if (i > WARMUP_LOOP_ITERS) { System.gc(); System.runFinalization(); } } Reference.reachabilityFence(o); return finalized.get(); }
public Parser findMimeParser(Lookup context, final String mimeType) { Parser p = null; final Reference<Parser> ref = cachedParsers.get (mimeType); if (ref != null) { p = ref.get(); } if (p == null) { final Lookup lookup = MimeLookup.getLookup (mimeType); final ParserFactory parserFactory = lookup.lookup (ParserFactory.class); if (parserFactory == null) { throw new IllegalArgumentException("No parser for mime type: " + mimeType); } p = parserFactory.createParser(Collections.<Snapshot>emptyList()); cachedParsers.put(mimeType, new SoftReference<Parser>(p)); } return p; }
private static synchronized void enqueueBrokenDataShadow(BrokenDataShadow ds) { Map<String, Set<Reference<BrokenDataShadow>>> m = getDataShadowsSet (); String prim = ds.getUrl().toExternalForm(); Reference<BrokenDataShadow> ref = new DataShadow.DSWeakReference<BrokenDataShadow>(ds); Set<Reference<BrokenDataShadow>> s = m.get (prim); if (s == null) { s = java.util.Collections.<Reference<BrokenDataShadow>>singleton (ref); getDataShadowsSet ().put (prim, s); } else { if (! (s instanceof HashSet)) { s = new HashSet<Reference<BrokenDataShadow>> (s); getDataShadowsSet ().put (prim, s); } s.add (ref); } }
@RandomlyFails // NB-Core-Build #7816: expected:<0> but was:<1> public void testPropertyChangeListenersDetachedAtFinalizeIssue58100() throws Exception { class MyAction extends AbstractAction implements ActionPerformer { public void actionPerformed(ActionEvent ev) { } public void performAction(SystemAction a) { } } MyAction action = new MyAction(); ActionMap map = new ActionMap(); CallbackSystemAction systemaction = (CallbackSystemAction)SystemAction.get(SimpleCallbackAction.class); map.put(systemaction.getActionMapKey(), action); Lookup context = Lookups.singleton(map); Action delegateaction = systemaction.createContextAwareInstance(context); assertTrue("Action is expected to have a PropertyChangeListener attached", action.getPropertyChangeListeners().length > 0); Reference actionref = new WeakReference(systemaction); systemaction = null; delegateaction = null; assertGC("CallbackSystemAction is supposed to be GCed", actionref); assertEquals("Action is expected to have no PropertyChangeListener attached", 0, action.getPropertyChangeListeners().length); }
synchronized void deregisterFontAndClearStrikeCache() { SunFontManager fm = SunFontManager.getInstance(); fm.deRegisterBadFont(this); for (Reference<FontStrike> strikeRef : strikeCache.values()) { if (strikeRef != null) { /* NB we know these are all FileFontStrike instances * because the cache is on this FileFont */ FileFontStrike strike = (FileFontStrike)strikeRef.get(); if (strike != null && strike.pScalerContext != 0L) { scaler.invalidateScalerContext(strike.pScalerContext); } } } if (scaler != null) { scaler.dispose(); } scaler = FontScaler.getNullScaler(); }
/** * Verify that the given AccessControlContext has permission to * accept this connection. */ void checkAcceptPermission(SecurityManager sm, AccessControlContext acc) { /* * Note: no need to synchronize on cache-related fields, since this * method only gets called from the ConnectionHandler's thread. */ if (sm != cacheSecurityManager) { okContext = null; authCache = new WeakHashMap<AccessControlContext, Reference<AccessControlContext>>(); cacheSecurityManager = sm; } if (acc.equals(okContext) || authCache.containsKey(acc)) { return; } InetAddress addr = socket.getInetAddress(); String host = (addr != null) ? addr.getHostAddress() : "*"; sm.checkAccept(host, socket.getPort()); authCache.put(acc, new SoftReference<AccessControlContext>(acc)); okContext = acc; }
@GuardedBy("this") void drainValueReferenceQueue() { Reference<? extends V> ref; int i = 0; while ((ref = valueReferenceQueue.poll()) != null) { @SuppressWarnings("unchecked") ValueReference<K, V> valueReference = (ValueReference<K, V>) ref; map.reclaimValue(valueReference); if (++i == DRAIN_MAX) { break; } } }
/** * Prunes any leaked allocations and then returns the number of remaining live allocations on * {@code connection}. Allocations are leaked if the connection is tracking them but the * application code has abandoned them. Leak detection is imprecise and relies on garbage * collection. */ private int pruneAndGetAllocationCount(RealConnection connection, long now) { List<Reference<StreamAllocation>> references = connection.allocations; for (int i = 0; i < references.size(); ) { Reference<StreamAllocation> reference = references.get(i); if (reference.get() != null) { i++; continue; } // We've discovered a leaked allocation. This is an application bug. StreamAllocation.StreamAllocationReference streamAllocRef = (StreamAllocation.StreamAllocationReference) reference; String message = "A connection to " + connection.route().address().url() + " was leaked. Did you forget to close a response body?"; Platform.get().logCloseableLeak(message, streamAllocRef.callStackTrace); references.remove(i); connection.noNewStreams = true; // If this was the last allocation, the connection is eligible for immediate eviction. if (references.isEmpty()) { connection.idleAtNanos = now - keepAliveDurationNs; return 0; } } return references.size(); }
@Override public T get(K key) { Reference<T> ref; lock.lock(); try { ref = map.get(key); } finally { lock.unlock(); } if (ref != null) { return ref.get(); } else { return null; } }
@Override public void run() { while (true) { try { Impl impl = obtainQueue(); if (impl == null) { return; } Reference<?> ref = impl.removeSuper(); LOGGER.log(Level.FINE, "Got dequeued reference {0}", new Object[] { ref }); if (!(ref instanceof Runnable)) { LOGGER.log(Level.WARNING, "A reference not implementing runnable has been added to the Utilities.activeReferenceQueue(): {0}", ref.getClass()); continue; } // do the cleanup try { ((Runnable) ref).run(); } catch (ThreadDeath td) { throw td; } catch (Throwable t) { // Should not happen. // If it happens, it is a bug in client code, notify! LOGGER.log(Level.WARNING, "Cannot process " + ref, t); } finally { // to allow GC ref = null; } } catch (InterruptedException ex) { // Can happen during VM shutdown, it seems. Ignore. continue; } } }
/** * Removes stale entries from the pool. */ private void clean() { Reference ref = fReferenceQueue.poll(); while (ref != null) { Entry entry = ((SoftGrammarReference) ref).entry; if (entry != null) { removeEntry(entry); } ref = fReferenceQueue.poll(); } }
/** * 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; }
void updateFoldManager(ConsoleFoldManager mgr, FileObject f) { if (f == null) { for (Iterator<Reference<ConsoleFoldManager>> it = managers.iterator(); it.hasNext(); ) { Reference<ConsoleFoldManager> ref = it.next(); ConsoleFoldManager fm = ref.get(); if (fm == null || fm == mgr) { it.remove(); break; } } } else { managers.add(new WeakReference<>(mgr)); } }
private synchronized boolean contains( Object o ) { for( Reference r : getReferences().keySet() ) { if ( r.get() == o ) { return true; } } return false; }
@Override public Bitmap get(String key) { Bitmap result = null; Reference<Bitmap> reference = softMap.get(key); if (reference != null) { result = reference.get(); } return result; }
private static void resetCaches(Set<String> storageDescriptionIds) { for(String id : storageDescriptionIds) { Reference<StorageImpl> ref = callbacks.get(id); StorageImpl storageImpl = ref == null ? null : ref.get(); if (storageImpl != null) { storageImpl.refresh(); } } }
private static boolean isCollectible(Reference reference) { int[] array = new int[10]; while (true) { try { array = new int[array.length + array.length / 3]; } catch (OutOfMemoryError error) { return null == reference.get(); } } }
public void testNewChildNoticed() throws Exception { FileObject fileObject1 = testFolder.createData("fileObject1"); FileObject[] arr = testFolder.getChildren(); assertEquals("One child", 1, arr.length); assertEquals("Right child", fileObject1, arr[0]); File file = FileUtil.toFile(fileObject1); assertNotNull("File found", file); arr = null; fileObject1 = null; Reference<FileObject> ref = new WeakReference<FileObject>(fileObject1); assertGC("File Object can disappear", ref); class L extends FileChangeAdapter { int cnt; FileEvent event; @Override public void fileDataCreated(FileEvent fe) { cnt++; event = fe; } } L listener = new L(); testFolder.addRecursiveListener(listener); File nfile = new File(file.getParentFile(), "new.txt"); nfile.createNewFile(); TestFileUtils.touch(nfile, null); testFolder.refresh(); assertEquals("Change notified", 1, listener.cnt); assertEquals("Right file", nfile, FileUtil.toFile(listener.event.getFile())); }
public static ImmutableInternalData create(Object lkp, Map<Template, Reference<R>> results) { if (results.size() == 0 && lkp == EMPTY_ARR) { return EMPTY; } if (results.size() == 1) { Entry<Template,Reference<R>> e = results.entrySet().iterator().next(); return new SingleInternalData(lkp, e.getKey(), e.getValue()); } return new RealInternalData(lkp, results); }
/** * Performs the actual registration of the target object to be disposed. * @param target Object to be registered, or if target is an instance * of DisposerTarget, its associated disposer referent * will be the Object that is registered * @param rec the associated DisposerRecord object * @see DisposerRecord */ synchronized void add(Object target, DisposerRecord rec) { if (target instanceof DisposerTarget) { target = ((DisposerTarget)target).getDisposerReferent(); } java.lang.ref.Reference<Object> ref; if (refType == PHANTOM) { ref = new PhantomReference<>(target, queue); } else { ref = new WeakReference<>(target, queue); } records.put(ref, rec); }
/** * {@inheritDoc} * @since 2017/12/13 */ @Override public String toString() { Reference<String> ref = this._string; String rv; if (ref == null || null == (rv = ref.get())) this._string = new WeakReference<>((rv = String.format( "{result=%d, body=%s}", this.code, this.body))); return rv; }
/** * Checks if the current caller has sufficient privilege to make * a connection to the remote endpoint. * @exception SecurityException if caller is not allowed to use this * Channel. */ private void checkConnectPermission() throws SecurityException { SecurityManager security = System.getSecurityManager(); if (security == null) return; if (security != cacheSecurityManager) { // The security manager changed: flush the cache okContext = null; authcache = new WeakHashMap<AccessControlContext, Reference<AccessControlContext>>(); cacheSecurityManager = security; } AccessControlContext ctx = AccessController.getContext(); // If ctx is the same context as last time, or if it // appears in the cache, bypass the checkConnect. if (okContext == null || !(okContext.equals(ctx) || authcache.containsKey(ctx))) { security.checkConnect(ep.getHost(), ep.getPort()); authcache.put(ctx, new SoftReference<AccessControlContext>(ctx)); // A WeakHashMap is transformed into a SoftHashSet by making // each value softly refer to its own key (Peter's idea). } okContext = ctx; }
CleanableCase(Reference<Object> ref, Cleaner.Cleanable cleanup, Semaphore semaphore, boolean throwsEx) { this.ref = ref; this.cleanup = cleanup; this.semaphore = semaphore; this.throwsEx = throwsEx; this.events = new int[4]; this.eventNdx = 0; }
public synchronized Collection<Object> getFiles() { List<Object> result = new ArrayList<Object>(); for (Reference<Object> r : files) { Object f = r.get(); if (f != null) result.add(f); } return result; }
/** factory */ protected static synchronized AbstractPhadhail forFile(File f, Factory y) { Map<File,Reference<AbstractPhadhail>> instances2 = instancesForFactory(y); Reference<AbstractPhadhail> r = instances2.get(f); AbstractPhadhail ph = (r != null) ? r.get() : null; if (ph == null) { // XXX could also yield lock while calling create, but don't bother ph = y.create(f); instances2.put(f, new WeakReference<AbstractPhadhail>(ph)); } return ph; }