java.lang.ref.Reference Java Examples
The following examples show how to use
java.lang.ref.Reference.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AlwaysEnabledActionTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testMemoryLeak() throws Exception { final AtomicInteger count = new AtomicInteger(); Action singleton = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { count.incrementAndGet(); } }; Object heavy = new Object(); AlwaysEnabledAction always = AlwaysEnabledAction.create( Collections.singletonMap("delegate", singleton) ); Action clone = always.createContextAwareInstance(Lookups.singleton(heavy)); clone.actionPerformed(null); assertEquals(1, count.get()); Reference<?> r = new WeakReference<Object>(heavy); clone = null; heavy = null; assertGC("should not leak context", r, Collections.singleton(singleton)); }
Example #2
Source File: WhiteListQueryImplementationMerged.java From netbeans with Apache License 2.0 | 6 votes |
@Override public synchronized WhiteListImplementation getWhiteList(final FileObject file) { final Reference<WhiteListImplementation> ref = canonicalCache.get(file); WhiteListImplementation wl = ref == null ? null : ref.get(); if (wl != null) { return wl; } final Lookup.Result<WhiteListQueryImplementation> lr = lkp.lookupResult(WhiteListQueryImplementation.class); boolean empty = true; for (WhiteListQueryImplementation impl : lr.allInstances()) { WhiteListImplementation i = impl.getWhiteList(file); if (i != null) { empty = false; break; } } if (empty) { return null; } wl = new WhiteListImplementationMerged(lr,file); canonicalCache.put(file,new WeakReference<WhiteListImplementation>(wl)); return wl; }
Example #3
Source File: FileObjectFactorySizeTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testIssuingFileObject() throws IOException { FileObjectFactory fbs = FileObjectFactory.getInstance(getWorkDir()); assertEquals("One file object exists?", 1, fbs.getSize()); FileObject workDir = FileUtil.toFileObject(getWorkDir()); assertNotNull(workDir); //root + workdir assertEquals(2, fbs.getSize()); assertEquals(2, fbs.getSize()); Reference<FileObject> rf = new WeakReference<>(workDir.getParent()); assertGC("", rf); assertNull(((BaseFileObj)workDir).getExistingParent()); assertEquals(2, fbs.getSize()); fbs.getRoot().getFileObject(workDir.getPath()); assertEquals(2, fbs.getSize()); rf = new WeakReference<>(workDir.getParent()); assertGC("", rf); assertNull(((BaseFileObj)workDir).getExistingParent()); assertEquals(2, fbs.getSize()); }
Example #4
Source File: CleanerTest.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Test that releasing the reference to the Cleaner service allows it to be * be freed. */ @Test void testCleanerTermination() { ReferenceQueue<Object> queue = new ReferenceQueue<>(); Cleaner service = Cleaner.create(); PhantomReference<Object> ref = new PhantomReference<>(service, queue); System.gc(); // Clear the Reference to the cleaning service and force a gc. service = null; System.gc(); try { Reference<?> r = queue.remove(1000L); Assert.assertNotNull(r, "queue.remove timeout,"); Assert.assertEquals(r, ref, "Wrong Reference dequeued"); } catch (InterruptedException ie) { System.out.printf("queue.remove Interrupted%n"); } }
Example #5
Source File: NodeUtilsTest.java From netbeans with Apache License 2.0 | 6 votes |
public void testReadOnlyLocalRepositoryFile() throws Exception { File repo = EmbedderFactory.getProjectEmbedder().getLocalRepositoryFile(); File f = TestFileUtils.writeFile(new File(repo, "ant/ant/1.5.1/ant-1.5.1.jar.sha1"), "a50e3e050a6e78e0656edc183435b9773f53ce78"); FileObject rw = FileUtil.toFileObject(f); FileObject ro = NodeUtils.readOnlyLocalRepositoryFile(rw); assertNotSame(rw, ro); assertFalse(ro.canWrite()); assertNotNull(DataObject.find(ro).getLookup().lookup(OpenCookie.class)); f = TestFileUtils.writeFile(new File(repo, "ant/ant/1.5.1/ant-1.5.1.pom.sha1"), "0ffdb41f140a621beeec4dc81b3d3ecaee085d28"); rw = FileUtil.toFileObject(f); ro = NodeUtils.readOnlyLocalRepositoryFile(rw); assertNotSame(rw, ro); assertFalse(ro.canWrite()); assertNotNull(DataObject.find(ro).getLookup().lookup(OpenCookie.class)); assertSame(ro, NodeUtils.readOnlyLocalRepositoryFile(rw)); FileObject skip = FileUtil.toFileObject(new File(repo, "ant/ant/1.5.1")); assertNotNull(skip); assertSame(skip, NodeUtils.readOnlyLocalRepositoryFile(skip)); File stuff = TestFileUtils.writeFile(new File(getWorkDir(), "stuff"), "stuff"); skip = FileUtil.toFileObject(stuff); assertNotNull(skip); assertSame(skip, NodeUtils.readOnlyLocalRepositoryFile(skip)); Reference<?> r = new WeakReference<Object>(ro.getFileSystem()); ro = null; assertGC("can collect FS", r); }
Example #6
Source File: StrikeCache.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
public static Reference getStrikeRef(FontStrike strike, boolean weak) { /* Some strikes may have no disposer as there's nothing * for them to free, as they allocated no native resource * eg, if they did not allocate resources because of a problem, * or they never hold native resources. So they create no disposer. * But any strike that reaches here that has a null disposer is * a potential memory leak. */ if (strike.disposer == null) { if (weak) { return new WeakReference(strike); } else { return new SoftReference(strike); } } if (weak) { return new WeakDisposerRef(strike); } else { return new SoftDisposerRef(strike); } }
Example #7
Source File: ReferenceMap.java From howsun-javaee-framework with Apache License 2.0 | 6 votes |
private void purge(Reference ref) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... int hash = ref.hashCode(); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if (entry.purge(ref)) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size--; return; } previous = entry; entry = entry.next; } }
Example #8
Source File: TCPTransport.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * Closes all cached connections in every channel subordinated to this * transport. Currently, this only closes outgoing connections. */ public void shedConnectionCaches() { List<TCPChannel> channels; synchronized (channelTable) { channels = new ArrayList<TCPChannel>(channelTable.values().size()); for (Reference<TCPChannel> ref : channelTable.values()) { TCPChannel ch = ref.get(); if (ch != null) { channels.add(ch); } } } for (TCPChannel channel : channels) { channel.shedCache(); } }
Example #9
Source File: NewInstanceNode.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@Override public void virtualize(VirtualizerTool tool) { /* * Reference objects can escape into their ReferenceQueue at any safepoint, therefore * they're excluded from escape analysis. */ if (!tool.getMetaAccessProvider().lookupJavaType(Reference.class).isAssignableFrom(instanceClass)) { VirtualInstanceNode virtualObject = createVirtualInstanceNode(true); ResolvedJavaField[] fields = virtualObject.getFields(); ValueNode[] state = new ValueNode[fields.length]; for (int i = 0; i < state.length; i++) { state[i] = defaultFieldValue(fields[i]); } tool.createVirtualObject(virtualObject, state, Collections.<MonitorIdNode> emptyList(), false); tool.replaceWithVirtual(virtualObject); } }
Example #10
Source File: BaseNDManager.java From djl with Apache License 2.0 | 6 votes |
/** * Prints information about this {@link NDManager} and all sub-managers to the console. * * @param level the level of this {@link NDManager} in the hierarchy */ public void debugDump(int level) { StringBuilder sb = new StringBuilder(100); for (int i = 0; i < level; ++i) { sb.append(" "); } sb.append("\\--- NDManager(") .append(uid.substring(24)) .append(") resource count: ") .append(resources.size()); System.out.println(sb.toString()); // NOPMD for (Reference<AutoCloseable> ref : resources.values()) { AutoCloseable c = ref.get(); if (c instanceof BaseNDManager) { ((BaseNDManager) c).debugDump(level + 1); } } }
Example #11
Source File: AbstractReferenceMap.java From Penetration_Testing_POC with Apache License 2.0 | 6 votes |
/** * Purges the specified reference * @param ref the reference to purge * @return true or false */ boolean purge(Reference ref) { boolean r = (parent.keyType > HARD) && (key == ref); r = r || ((parent.valueType > HARD) && (value == ref)); if (r) { if (parent.keyType > HARD) { ((Reference)key).clear(); } if (parent.valueType > HARD) { ((Reference)value).clear(); } else if (parent.purgeValues) { value = null; } } return r; }
Example #12
Source File: StrikeCache.java From Bytecoder with Apache License 2.0 | 6 votes |
public static Reference<FontStrike> getStrikeRef(FontStrike strike, boolean weak) { /* Some strikes may have no disposer as there's nothing * for them to free, as they allocated no native resource * eg, if they did not allocate resources because of a problem, * or they never hold native resources. So they create no disposer. * But any strike that reaches here that has a null disposer is * a potential memory leak. */ if (strike.disposer == null) { if (weak) { return new WeakReference<>(strike); } else { return new SoftReference<>(strike); } } if (weak) { return new WeakDisposerRef(strike); } else { return new SoftDisposerRef(strike); } }
Example #13
Source File: TCPTransport.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
/** * Returns a <I>Channel</I> that generates connections to the * endpoint <I>ep</I>. A Channel is an object that creates and * manages connections of a particular type to some particular * address space. * @param ep the endpoint to which connections will be generated. * @return the channel or null if the transport cannot * generate connections to this endpoint */ public TCPChannel getChannel(Endpoint ep) { TCPChannel ch = null; if (ep instanceof TCPEndpoint) { synchronized (channelTable) { Reference<TCPChannel> ref = channelTable.get(ep); if (ref != null) { ch = ref.get(); } if (ch == null) { TCPEndpoint tcpEndpoint = (TCPEndpoint) ep; ch = new TCPChannel(this, tcpEndpoint); channelTable.put(tcpEndpoint, new WeakReference<TCPChannel>(ch)); } } } return ch; }
Example #14
Source File: StrikeCache.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
public static Reference getStrikeRef(FontStrike strike, boolean weak) { /* Some strikes may have no disposer as there's nothing * for them to free, as they allocated no native resource * eg, if they did not allocate resources because of a problem, * or they never hold native resources. So they create no disposer. * But any strike that reaches here that has a null disposer is * a potential memory leak. */ if (strike.disposer == null) { if (weak) { return new WeakReference(strike); } else { return new SoftReference(strike); } } if (weak) { return new WeakDisposerRef(strike); } else { return new SoftDisposerRef(strike); } }
Example #15
Source File: DisposalCrashTest.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) { int[] ids = new int[]{ CS_sRGB, CS_CIEXYZ, CS_GRAY, CS_LINEAR_RGB, CS_PYCC }; for (int id : ids) { ICC_Profile p = getCopyOf(id); } while (!v.isEmpty()) { System.gc(); System.out.println("."); try { Thread.sleep(500); } catch (InterruptedException e) {}; final Reference<? extends ICC_Profile> ref = queue.poll(); System.out.println("Got reference: " + ref); v.remove(ref); } System.out.println("Test PASSED."); }
Example #16
Source File: WeakFaweQueueMap.java From FastAsyncWorldedit with GNU General Public License v3.0 | 6 votes |
@Override public FaweChunk getFaweChunk(int cx, int cz) { if (cx == lastX && cz == lastZ) { return lastWrappedChunk; } long pair = MathMan.pairInt(cx, cz); Reference<FaweChunk> chunkReference = this.blocks.get(pair); FaweChunk chunk; if (chunkReference == null || (chunk = chunkReference.get()) == null) { chunk = this.getNewFaweChunk(cx, cz); Reference<FaweChunk> previous = this.blocks.put(pair, new SoftReference(chunk)); if (previous != null) { FaweChunk tmp = previous.get(); if (tmp != null) { chunk = tmp; this.blocks.put(pair, previous); } } } return chunk; }
Example #17
Source File: TCPTransport.java From jdk8u60 with GNU General Public License v2.0 | 6 votes |
/** * 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; }
Example #18
Source File: FileFont.java From jdk8u_jdk with GNU General Public License v2.0 | 6 votes |
synchronized void deregisterFontAndClearStrikeCache() { SunFontManager fm = SunFontManager.getInstance(); fm.deRegisterBadFont(this); for (Reference 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.disposeScaler(); } scaler = FontScaler.getNullScaler(); }
Example #19
Source File: WrapTokenIdCache.java From netbeans with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") public static synchronized <T extends TokenId> WrapTokenIdCache<T> get(Language<T> language) { int lid = id(language); if (cacheRefs == null || lid >= cacheRefs.length) { Reference<WrapTokenIdCache<?>>[] n = (Reference<WrapTokenIdCache<?>>[]) new Reference[lid + 1]; if (cacheRefs != null) { System.arraycopy(cacheRefs, 0, n, 0, cacheRefs.length); } cacheRefs = n; } Reference<WrapTokenIdCache<?>> cacheRef = cacheRefs[lid]; WrapTokenIdCache<T> cache; if (cacheRef == null || (cache = (WrapTokenIdCache<T>) cacheRef.get()) == null) { cache = new WrapTokenIdCache<T>(language); cacheRefs[lid] = new WeakReference<WrapTokenIdCache<?>>(cache); } return cache; }
Example #20
Source File: LanguagePath.java From netbeans with Apache License 2.0 | 6 votes |
/** * Get language path corresponding to the suffix language path embedded * in this path. * * @param suffix non-null suffix to be added to this path. * @return non-null language path consisting of this path with the * suffix added to the end. */ public LanguagePath embedded(LanguagePath suffix) { if (suffix == null) { throw new IllegalArgumentException("suffix cannot be null"); } // Attempt to retrieve from the cache first synchronized (languages) { initLanguage2path(); Reference<LanguagePath> lpRef = language2path.get(suffix); LanguagePath lp; if (lpRef == null || (lp = lpRef.get()) == null) { // Construct the LanguagePath lp = this; for (int i = 0; i < suffix.size(); i++) { lp = lp.embedded(suffix.language(i)); } language2path.put(suffix, new SoftReference<LanguagePath>(lp)); } return lp; } }
Example #21
Source File: CallbackSystemAction.java From netbeans with Apache License 2.0 | 6 votes |
public void attach(Action action) { Reference<Action> d = delegate; if ((d == null) || (d.get() == action)) { return; } Action prev = d.get(); // reattaches to different action if (prev != null) { prev.removePropertyChangeListener(this); } this.delegate = new WeakReference<Action>(action); action.addPropertyChangeListener(this); }
Example #22
Source File: ObjectStreamClass.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
/** * Removes from the specified map any keys that have been enqueued * on the specified reference queue. */ static void processQueue(ReferenceQueue<Class<?>> queue, ConcurrentMap<? extends WeakReference<Class<?>>, ?> map) { Reference<? extends Class<?>> ref; while((ref = queue.poll()) != null) { map.remove(ref); } }
Example #23
Source File: VirtualMachineImpl.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
private void processQueue() { Reference<?> ref; //if ((traceFlags & TRACE_OBJREFS) != 0) { // printTrace("Checking for softly reachable objects"); //} while ((ref = referenceQueue.poll()) != null) { SoftObjectReference softRef = (SoftObjectReference)ref; removeObjectMirror(softRef); batchForDispose(softRef); } }
Example #24
Source File: AbstractReferenceMap.java From AndroidPNClient with Apache License 2.0 | 5 votes |
/** * Constructs a reference of the given type to the given referent. * The reference is registered with the queue for later purging. * * @param type HARD, SOFT or WEAK * @param referent the object to refer to * @param hash the hash code of the <i>key</i> of the mapping; * this number might be different from referent.hashCode() if * the referent represents a value and not a key */ protected <T> Reference<T> toReference(int type, T referent, int hash) { switch (type) { case SOFT: return new SoftRef<T>(hash, referent, parent.queue); case WEAK: return new WeakRef<T>(hash, referent, parent.queue); default: throw new Error("Attempt to create hard reference in ReferenceMap!"); } }
Example #25
Source File: KeyedRefCollector.java From commons-jcs with Apache License 2.0 | 5 votes |
/** * Executes one cycle of stale entries removal. */ public void run() { Reference ref; while ((ref = this.q.poll()) != null) { IKey keyedRef = (IKey)ref; // remove unused lock; may fail but that's fine. synMap.remove(keyedRef.getKey(), ref); // referent should have been cleared by GC. if (debug) this.count.incrementAndGet(); } }
Example #26
Source File: ReferenceObjectCache.java From ormlite-core with ISC License | 5 votes |
@Override public <T> int size(Class<T> clazz) { Map<Object, Reference<Object>> objectMap = getMapForClass(clazz); if (objectMap == null) { return 0; } else { return objectMap.size(); } }
Example #27
Source File: TCPTransport.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
/** * Removes the <I>Channel</I> that generates connections to the * endpoint <I>ep</I>. */ public void free(Endpoint ep) { if (ep instanceof TCPEndpoint) { synchronized (channelTable) { Reference<TCPChannel> ref = channelTable.remove(ep); if (ref != null) { TCPChannel channel = ref.get(); if (channel != null) { channel.shedCache(); } } } } }
Example #28
Source File: IterableThreadLocal.java From Nemisys with GNU General Public License v3.0 | 5 votes |
public static void cleanAll() { try { // Get a reference to the thread locals table of the current thread Thread thread = Thread.currentThread(); Field threadLocalsField = Thread.class.getDeclaredField("threadLocals"); threadLocalsField.setAccessible(true); Object threadLocalTable = threadLocalsField.get(thread); // Get a reference to the array holding the thread local variables inside the // ThreadLocalMap of the current thread Class threadLocalMapClass = Class.forName("java.lang.ThreadLocal$ThreadLocalMap"); Field tableField = threadLocalMapClass.getDeclaredField("table"); tableField.setAccessible(true); Object table = tableField.get(threadLocalTable); // The key to the ThreadLocalMap is a WeakReference object. The referent field of this object // is a reference to the actual ThreadLocal variable Field referentField = Reference.class.getDeclaredField("referent"); referentField.setAccessible(true); for (int i = 0; i < Array.getLength(table); i++) { // Each entry in the table array of ThreadLocalMap is an Entry object // representing the thread local reference and its value Object entry = Array.get(table, i); if (entry != null) { // Get a reference to the thread local object and remove it from the table ThreadLocal threadLocal = (ThreadLocal) referentField.get(entry); clean(threadLocal); } } } catch (Exception e) { // We will tolerate an exception here and just log it throw new IllegalStateException(e); } }
Example #29
Source File: VirtualMachineImpl.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
private void processQueue() { Reference ref; while ((ref = referenceQueue.poll()) != null) { SoftObjectReference softRef = (SoftObjectReference)ref; removeObjectMirror(softRef); } }
Example #30
Source File: Pool.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Gets a pooled connection for id. The pooled connection might be * newly created, as governed by the maxSize and prefSize settings. * If a pooled connection is unavailable and cannot be created due * to the maxSize constraint, this call blocks until the constraint * is removed or until 'timeout' ms has elapsed. * * @param id identity of the connection to get * @param timeout the number of milliseconds to wait before giving up * @param factory the factory to use for creating the connection if * creation is necessary * @return a pooled connection * @throws NamingException the connection could not be created due to * an error. */ public PooledConnection getPooledConnection(Object id, long timeout, PooledConnectionFactory factory) throws NamingException { d("get(): ", id); if (debug) { synchronized (map) { d("size: ", map.size()); } } expungeStaleConnections(); Connections conns; synchronized (map) { conns = getConnections(id); if (conns == null) { d("get(): creating new connections list for ", id); // No connections for this id so create a new list conns = new Connections(id, initSize, prefSize, maxSize, factory); ConnectionsRef connsRef = new ConnectionsRef(conns); map.put(id, connsRef); // Create a weak reference to ConnectionsRef Reference<ConnectionsRef> weakRef = new ConnectionsWeakRef(connsRef, queue); // Keep the weak reference through the element of a linked list weakRefs.add(weakRef); } d("get(): size after: ", map.size()); } return conns.get(timeout, factory); // get one connection from list }