Java Code Examples for java.lang.ref.Reference#get()

The following examples show how to use java.lang.ref.Reference#get() . 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: TCPTransport.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 2
Source File: TCPTransport.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 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 3
Source File: FileFont.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
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.dispose();
    }
    scaler = FontScaler.getNullScaler();
}
 
Example 4
Source File: ProjectServicesImpl.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void removeProjectOpenListener(IDEProject.OpenListener listener) {
    if (ideProjectOpenListeners != null) {
        Iterator<Reference<IDEProject.OpenListener>> it = ideProjectOpenListeners.iterator();
        while (it.hasNext()) {
            Reference<IDEProject.OpenListener> r = it.next();
            IDEProject.OpenListener l = r.get();
            if (l == null || l == listener) {
                it.remove(); // also doing cleanup of GC'ed references
            }
        }
        if (ideProjectOpenListeners.isEmpty()) {
            ideProjectOpenListeners = null;
            if (projectOpenListener != null) {
                OpenProjects.getDefault().removePropertyChangeListener(projectOpenListener);
                projectOpenListener = null;
            }
        }
    }
}
 
Example 5
Source File: ToolProvider.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private <T> Class<? extends T> getSystemToolClass(Class<T> clazz, String name) {
    Reference<Class<?>> refClass = toolClasses.get(name);
    Class<?> c = (refClass == null ? null : refClass.get());
    if (c == null) {
        try {
            c = findSystemToolClass(name);
        } catch (Throwable e) {
            return trace(WARNING, e);
        }
        toolClasses.put(name, new WeakReference<Class<?>>(c));
    }
    return c.asSubclass(clazz);
}
 
Example 6
Source File: DefaultListableBeanFactory.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private Object readResolve() {
	Reference<?> ref = serializableFactories.get(this.id);
	if (ref != null) {
		Object result = ref.get();
		if (result != null) {
			return result;
		}
	}
	// Lenient fallback: dummy factory in case of original factory not found...
	DefaultListableBeanFactory dummyFactory = new DefaultListableBeanFactory();
	dummyFactory.serializationId = this.id;
	return dummyFactory;
}
 
Example 7
Source File: WeakCache.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a value to which the specified {@code key} is mapped,
 * or {@code null} if this map contains no mapping for the {@code key}.
 *
 * @param key  the key whose associated value is returned
 * @return a value to which the specified {@code key} is mapped
 */
public V get(K key) {
    Reference<V> reference = this.map.get(key);
    if (reference == null) {
        return null;
    }
    V value = reference.get();
    if (value == null) {
        this.map.remove(key);
    }
    return value;
}
 
Example 8
Source File: MethodDescriptor.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private synchronized Class<?>[] getParams() {
    Class<?>[] clss = new Class<?>[params.size()];

    for (int i = 0; i < params.size(); i++) {
        Reference<? extends Class<?>> ref = (Reference<? extends Class<?>>)params.get(i);
        Class<?> cls = ref.get();
        if (cls == null) {
            return null;
        } else {
            clss[i] = cls;
        }
    }
    return clss;
}
 
Example 9
Source File: BuildArtifactMapperImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public CompileOnSaveAction forRoot(@NonNull final URL root) {
    synchronized (normCache) {
        final Reference<DefaultCompileOnSaveAction> ref = normCache.get(root);
        DefaultCompileOnSaveAction res;
        if (ref == null || (res = ref.get()) == null) {
            res = new DefaultCompileOnSaveAction(root);
            normCache.put(root, new WeakReference<>(res));
        }
        return res;
    }
}
 
Example 10
Source File: InstanceWatcher.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public synchronized Collection<?> getInstances() {
    List<Object> l = new ArrayList<Object>(getReferences().size());
    for (Reference wr : getReferences().keySet()) {
        Object inst = wr.get();
        if (inst != null) l.add(inst);
    }
    return l;
}
 
Example 11
Source File: TypeCache.java    From byte-buddy with Apache License 2.0 5 votes vote down vote up
/**
 * Finds a stored type or returns {@code null} if no type was stored.
 *
 * @param classLoader The class loader for which this type is stored.
 * @param key         The key for the type in question.
 * @return The stored type or {@code null} if no type was stored.
 */
@SuppressFBWarnings(value = "GC_UNRELATED_TYPES", justification = "Cross-comparison is intended")
public Class<?> find(ClassLoader classLoader, T key) {
    ConcurrentMap<T, Reference<Class<?>>> storage = cache.get(new LookupKey(classLoader));
    if (storage == null) {
        return NOT_FOUND;
    } else {
        Reference<Class<?>> reference = storage.get(key);
        if (reference == null) {
            return NOT_FOUND;
        } else {
            return reference.get();
        }
    }
}
 
Example 12
Source File: BaseMemoryCache.java    From mobile-manager-tool with MIT License 5 votes vote down vote up
@Override
public Bitmap get(String key) {
	Bitmap result = null;
	Reference<Bitmap> reference = softMap.get(key);
	if (reference != null) {
		result = reference.get();
	}
	return result;
}
 
Example 13
Source File: ToolProvider.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
private <T> Class<? extends T> getSystemToolClass(Class<T> clazz, String name) {
    Reference<Class<?>> refClass = toolClasses.get(name);
    Class<?> c = (refClass == null ? null : refClass.get());
    if (c == null) {
        try {
            c = findSystemToolClass(name);
        } catch (Throwable e) {
            return trace(WARNING, e);
        }
        toolClasses.put(name, new WeakReference<Class<?>>(c));
    }
    return c.asSubclass(clazz);
}
 
Example 14
Source File: PinLastArguments.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    System.err.println("\nRegression test for bug 6332349\n");

    Ping impl = new PingImpl();
    Reference<?> ref = new WeakReference<Ping>(impl);
    try {
        Ping stub = (Ping) UnicastRemoteObject.exportObject(impl, 0);
        Object notSerializable = new Object();
        stub.ping(impl, null);
        try {
            stub.ping(impl, notSerializable);
        } catch (MarshalException e) {
            if (e.getCause() instanceof NotSerializableException) {
                System.err.println("ping invocation failed as expected");
            } else {
                throw e;
            }
        }
    } finally {
        UnicastRemoteObject.unexportObject(impl, true);
    }
    impl = null;

    // Might require multiple calls to System.gc() for weak-references
    // processing to be complete. If the weak-reference is not cleared as
    // expected we will hang here until timed out by the test harness.
    while (true) {
        System.gc();
        Thread.sleep(20);
        if (ref.get() == null) {
            break;
        }
    }

    System.err.println("TEST PASSED");
}
 
Example 15
Source File: WeakCache.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a value to which the specified {@code key} is mapped,
 * or {@code null} if this map contains no mapping for the {@code key}.
 *
 * @param key  the key whose associated value is returned
 * @return a value to which the specified {@code key} is mapped
 */
public V get(K key) {
    Reference<V> reference = this.map.get(key);
    if (reference == null) {
        return null;
    }
    V value = reference.get();
    if (value == null) {
        this.map.remove(key);
    }
    return value;
}
 
Example 16
Source File: LockForFile.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void hardLock() throws IOException {
    Collection<Reference<LockForFile>> refs = values();
    for (Reference<LockForFile> reference : refs) {
        if (reference != null) {
            LockForFile lockForFile = reference.get();
            if (lockForFile != null) {
                if (!FileChangedManager.getInstance().exists(lockForFile.getLock())) {
                    lockForFile.hardLock();
                }
            }
        }
    }
}
 
Example 17
Source File: ShellRegistry.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public JShellEnvironment get(FileObject consoleFile) {
    synchronized (this) {
        Reference<JShellEnvironment> ref = fileIndex.get(consoleFile);
        return ref == null ? null : ref.get();
    }
}
 
Example 18
Source File: ObjectStreamClass.java    From jdk1.8-source-analysis with Apache License 2.0 4 votes vote down vote up
/**
 * Looks up and returns class descriptor for given class, or null if class
 * is non-serializable and "all" is set to false.
 *
 * @param   cl class to look up
 * @param   all if true, return descriptors for all classes; if false, only
 *          return descriptors for serializable classes
 */
static ObjectStreamClass lookup(Class<?> cl, boolean all) {
    if (!(all || Serializable.class.isAssignableFrom(cl))) {
        return null;
    }
    processQueue(Caches.localDescsQueue, Caches.localDescs);
    WeakClassKey key = new WeakClassKey(cl, Caches.localDescsQueue);
    Reference<?> ref = Caches.localDescs.get(key);
    Object entry = null;
    if (ref != null) {
        entry = ref.get();
    }
    EntryFuture future = null;
    if (entry == null) {
        EntryFuture newEntry = new EntryFuture();
        Reference<?> newRef = new SoftReference<>(newEntry);
        do {
            if (ref != null) {
                Caches.localDescs.remove(key, ref);
            }
            ref = Caches.localDescs.putIfAbsent(key, newRef);
            if (ref != null) {
                entry = ref.get();
            }
        } while (ref != null && entry == null);
        if (entry == null) {
            future = newEntry;
        }
    }

    if (entry instanceof ObjectStreamClass) {  // check common case first
        return (ObjectStreamClass) entry;
    }
    if (entry instanceof EntryFuture) {
        future = (EntryFuture) entry;
        if (future.getOwner() == Thread.currentThread()) {
            /*
             * Handle nested call situation described by 4803747: waiting
             * for future value to be set by a lookup() call further up the
             * stack will result in deadlock, so calculate and set the
             * future value here instead.
             */
            entry = null;
        } else {
            entry = future.get();
        }
    }
    if (entry == null) {
        try {
            entry = new ObjectStreamClass(cl);
        } catch (Throwable th) {
            entry = th;
        }
        if (future.set(entry)) {
            Caches.localDescs.put(key, new SoftReference<Object>(entry));
        } else {
            // nested lookup call already set future
            entry = future.get();
        }
    }

    if (entry instanceof ObjectStreamClass) {
        return (ObjectStreamClass) entry;
    } else if (entry instanceof RuntimeException) {
        throw (RuntimeException) entry;
    } else if (entry instanceof Error) {
        throw (Error) entry;
    } else {
        throw new InternalError("unexpected entry: " + entry);
    }
}
 
Example 19
Source File: SourceFactory.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Source removeSource(@NonNull final FileObject file) {
    Parameters.notNull("file", file);   //NOI18N
    final Reference<Source> ref = instances.remove(file);
    return ref == null ? null : ref.get();
}
 
Example 20
Source File: URLCache.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@CheckForNull
public FileObject findFileObject(
        final @NonNull URL url,
        final boolean validate) {
    URI uri = null;
    try {
        uri  = url.toURI();
    } catch (URISyntaxException e) {
        Exceptions.printStackTrace(e);
    }
    FileObject f = null;
    if (uri != null) {
        Reference<FileObject> ref = cache.get(uri);
        if (ref != null) {
            f = ref.get();
        }
        if (f != null && f.isValid() && (!validate || f.toURI().equals(uri))) {
            if (LOG.isLoggable(Level.FINEST)) {
                LOG.log(
                    Level.FINEST,
                    "Found: {0} in cache for: {1}", //NOI18N
                    new Object[]{
                        f,
                        url
                    });
            }
            return f;
        }
    }

    f = URLMapper.findFileObject(url);

    if (uri != null && f != null && f.isValid()) {
        if (LOG.isLoggable(Level.FINEST)) {
            LOG.log(
               Level.FINEST,
               "Caching: {0} for: {1}", //NOI18N
               new Object[]{
                   f,
                   url
               });
        }
        cache.put(uri, new CleanReference(f,uri));
    }

    return f;
}