Example usage for java.lang.ref Reference get

List of usage examples for java.lang.ref Reference get

Introduction

In this page you can find the example usage for java.lang.ref Reference get.

Prototype

@HotSpotIntrinsicCandidate
public T get() 

Source Link

Document

Returns this reference object's referent.

Usage

From source file:SoftValueMap.java

/**
 * Returns the value that is mapped to a given 'key'. Returns
 * null if (a) this key has never been mapped or (b) a previously mapped
 * value has been cleared by the garbage collector and removed from the table.
 *
 * @param key mapping key [may not be null].
 *
 * @return Object value mapping for 'key' [can be null].
 *///from  w w  w .j  a v a 2 s  .  co  m
public Object get(final Object key) {
    if (key == null)
        throw new IllegalArgumentException("null input: key");

    if ((++m_readAccessCount % m_readClearCheckFrequency) == 0)
        removeClearedValues();

    // index into the corresponding hash bucket:
    final int keyHashCode = key.hashCode();
    final SoftEntry[] buckets = m_buckets;
    final int bucketIndex = (keyHashCode & 0x7FFFFFFF) % buckets.length;

    Object result = null;

    // traverse the singly-linked list of entries in the bucket:
    for (SoftEntry entry = buckets[bucketIndex]; entry != null; entry = entry.m_next) {
        final Object entryKey = entry.m_key;

        if (IDENTITY_OPTIMIZATION) {
            // note: this uses an early identity comparison opimization, making this a bit
            // faster for table keys that do not override equals() [Thread, etc]
            if ((key == entryKey) || ((keyHashCode == entryKey.hashCode()) && key.equals(entryKey))) {
                final Reference ref = entry.m_softValue;
                result = ref.get(); // may return null to the caller

                // [see comment for ENQUEUE_FOUND_CLEARED_ENTRIES]
                if (ENQUEUE_FOUND_CLEARED_ENTRIES && (result == null)) {
                    ref.enqueue();
                }

                return result;
            }
        } else {
            if ((keyHashCode == entryKey.hashCode()) && key.equals(entryKey)) {
                final Reference ref = entry.m_softValue;
                result = ref.get(); // may return null to the caller

                // [see comment for ENQUEUE_FOUND_CLEARED_ENTRIES]
                if (ENQUEUE_FOUND_CLEARED_ENTRIES && (result == null)) {
                    ref.enqueue();
                }

                return result;
            }
        }
    }

    return null;
}

From source file:jenkins.model.lazy.AbstractLazyLoadRunMap.java

private R unwrap(Reference<R> ref) {
    return ref != null ? ref.get() : null;
}

From source file:gridool.dht.btree.Paged.java

/**
 * getPage returns the page specified by pageNum.
 *///from  w ww .j  a  v  a  2 s .  c om
protected final Page getPage(long pageNum) throws IndexException {
    Page p = null;
    // if not check if it's already loaded in the page cache
    Reference<Page> ref = _pages.get(pageNum); // Check if required page is in the volatile cache
    if (ref != null) {
        p = ref.get();
    }
    if (p == null) {
        // if still not found we need to create it and add it to the page cache.
        p = new Page(pageNum);
        try {
            p.read(); // Load the page from disk if necessary
        } catch (IOException e) {
            throw new IndexException(e);
        }
        _pages.put(pageNum, new WeakReference<Page>(p));
    }
    return p;
}

From source file:com.microsoft.tfs.core.httpclient.MultiThreadedHttpConnectionManager.java

/**
 * Closes and releases all connections currently checked out of the given
 * connection pool./*from   w ww. j a  v a  2  s  . c o  m*/
 *
 * @param connectionPool
 *        the connection pool to shutdown the connections for
 */
private static void shutdownCheckedOutConnections(final ConnectionPool connectionPool) {
    log.debug("shutdownCheckedOutConnections: waiting for synchronization.");

    // keep a list of the connections to be closed
    final ArrayList connectionsToClose = new ArrayList();

    synchronized (REFERENCE_TO_CONNECTION_SOURCE) {
        log.debug("shutdownCheckedOutConnections: collecting coonection list.");

        final Iterator referenceIter = REFERENCE_TO_CONNECTION_SOURCE.keySet().iterator();
        while (referenceIter.hasNext()) {
            final Reference ref = (Reference) referenceIter.next();
            final ConnectionSource source = (ConnectionSource) REFERENCE_TO_CONNECTION_SOURCE.get(ref);
            if (source.connectionPool == connectionPool) {
                referenceIter.remove();
                final HttpConnection connection = (HttpConnection) ref.get();
                if (connection != null) {
                    connectionsToClose.add(connection);
                }
            }
        }
    }

    log.debug("shutdownCheckedOutConnections: connections to close count = " + connectionsToClose.size());

    // close and release the connections outside of the synchronized block
    // to
    // avoid holding the lock for too long
    for (final Iterator i = connectionsToClose.iterator(); i.hasNext();) {
        final HttpConnection connection = (HttpConnection) i.next();
        connection.close();
        // remove the reference to the connection manager. this ensures
        // that the we don't accidentally end up here again
        connection.setHttpConnectionManager(null);
        connection.releaseConnection();
    }
}

From source file:com.meltmedia.cadmium.servlets.ClassLoaderLeakPreventor.java

protected void processThreadLocalMap(Thread thread, ThreadLocalProcessor threadLocalProcessor,
        Object threadLocalMap) throws IllegalAccessException {
    if (threadLocalMap != null && java_lang_ThreadLocal$ThreadLocalMap_table != null) {
        final Object[] threadLocalMapTable = (Object[]) java_lang_ThreadLocal$ThreadLocalMap_table
                .get(threadLocalMap); // java.lang.ThreadLocal.ThreadLocalMap.Entry[]
        for (Object entry : threadLocalMapTable) {
            if (entry != null) {
                // Key is kept in WeakReference
                Reference reference = (Reference) entry;
                final ThreadLocal<?> threadLocal = (ThreadLocal<?>) reference.get();

                if (java_lang_ThreadLocal$ThreadLocalMap$Entry_value == null) {
                    java_lang_ThreadLocal$ThreadLocalMap$Entry_value = findField(entry.getClass(), "value");
                }/*ww w. jav  a  2 s. c o  m*/

                final Object value = java_lang_ThreadLocal$ThreadLocalMap$Entry_value.get(entry);

                threadLocalProcessor.process(thread, reference, threadLocal, value);
            }
        }
    }
}

From source file:org.apache.hadoop.hdfs.hoss.db.FileBlockStore.java

/**
 * map a block(4KB) or a segment(256KB)//  ww w  .  j  a va2s . com
 * @param index 
 *          the index of block
 * @param useSegments
 *           whether use segmeng?
 * @return   the mapping Buffer
 */
@SuppressWarnings("unchecked")
public final MappedByteBuffer getMmapForIndex(final int index, boolean useSegments) {
    if (!validState)
        throw new InvalidStateException();
    final int mapIdx = (useSegments ? addressIndexToSegment(index) : index);
    final int mapSize = (useSegments ? segmentSize : blockSize);
    try {
        final Reference<MappedByteBuffer> bref = mmaps.get(mapIdx);
        MappedByteBuffer mbb = null;
        if (bref != null) {
            mbb = bref.get();
        }
        if (mbb == null) { // Create mmap
            final long mapOffset = ((long) mapIdx * mapSize);
            mbb = fileChannel.map(FileChannel.MapMode.READ_WRITE, mapOffset, mapSize);
            // mbb.load();
            mmaps.put(mapIdx, new BufferReference<MappedByteBuffer>(mapIdx, mbb));
        } else {
            mbb.clear();
        }
        if (useSegments) { // slice segment
            final int sliceBegin = (addressIndexToSegmentOffset(index) * blockSize);
            final int sliceEnd = (sliceBegin + blockSize);
            mbb.limit(sliceEnd);
            mbb.position(sliceBegin);
            mbb = (MappedByteBuffer) mbb.slice();
        }
        return mbb;
    } catch (IOException e) {
        LOG.error("IOException in getMmapForIndex(" + index + ")", e);
    }
    return null;
}

From source file:org.apache.hadoop.hdfs.hoss.db.FileBlockStore.java

@SuppressWarnings("unchecked")
private void syncAllMmaps() {
    final BufferReference<MappedByteBuffer>[] maps = mmaps.getValues();
    Arrays.sort(maps, comparatorByIdx);
    for (final Reference<MappedByteBuffer> ref : maps) {
        if (ref == null)
            break;
        final MappedByteBuffer mbb = ref.get();
        if (mbb != null) {
            try {
                mbb.force();//from w  ww.  jav  a 2  s. c  om
            } catch (Exception ign) {
            }
        }
    }
}

From source file:org.apache.xmlgraphics.image.loader.util.SoftMapCache.java

private Object getReference(Object key, Reference ref) {
    Object value = null;// w ww  .ja va2 s.com
    if (ref != null) {
        value = ref.get();
        if (value == null) {
            //Remove key if its value has been garbage collected
            if (log.isTraceEnabled()) {
                log.trace("Image has been collected: " + key);
            }
            checkReferenceQueue();
        }
    }
    return value;
}

From source file:org.diorite.impl.world.io.ChunkRegionCache.java

public ChunkRegion getChunkRegion(final int regionX, final int regionZ) {
    final long key = BigEndianUtils.toLong(regionX, regionZ);
    final File file = new File(this.regionDir, "r." + regionX + "." + regionZ + this.extension);

    final Reference<ChunkRegion> ref = this.cache.get(key);

    if ((ref != null) && (ref.get() != null)) {
        return ref.get();
    }/*from w  w  w .j  a  v  a  2 s.c  o  m*/

    if (!this.regionDir.isDirectory() && !this.regionDir.mkdirs()) {
        System.err.println("[WorldIO] Failed to create directory: " + this.regionDir);
    }

    if (this.cache.size() >= this.maxCacheSize) {
        this.clear();
    }

    final ChunkRegion reg = this.createNewRegion(file, regionX, regionZ);
    synchronized (this.cache) {
        this.cache.put(key, new SoftReference<>(reg));
    }
    return reg;
}

From source file:org.hopen.framework.rewrite.CachedIntrospectionResults.java

/**
 * 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
 *///w  w w .  j  a v a2s . c o  m
static CachedIntrospectionResults forClass(Class beanClass) throws BeansException {
    CachedIntrospectionResults results;
    Object value = classCache.get(beanClass);
    if (value instanceof Reference) {
        Reference ref = (Reference) value;
        results = (CachedIntrospectionResults) ref.get();
    } else {
        results = (CachedIntrospectionResults) value;
    }
    if (results == null) {
        // On JDK 1.5 and higher, it is almost always safe to cache the bean class...
        // The sole exception is a custom BeanInfo class being provided in a non-safe ClassLoader.
        boolean fullyCacheable = ClassUtils.isCacheSafe(beanClass,
                CachedIntrospectionResults.class.getClassLoader())
                || isClassLoaderAccepted(beanClass.getClassLoader());
        if (fullyCacheable
                || !ClassUtils.isPresent(beanClass.getName() + "BeanInfo", beanClass.getClassLoader())) {
            results = new CachedIntrospectionResults(beanClass, fullyCacheable);
            classCache.put(beanClass, results);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Not strongly caching class [" + beanClass.getName()
                        + "] because it is not cache-safe");
            }
            results = new CachedIntrospectionResults(beanClass, true);
            classCache.put(beanClass, new WeakReference<CachedIntrospectionResults>(results));
        }
    }
    return results;
}