Example usage for java.lang.ref SoftReference SoftReference

List of usage examples for java.lang.ref SoftReference SoftReference

Introduction

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

Prototype

public SoftReference(T referent) 

Source Link

Document

Creates a new soft reference that refers to the given object.

Usage

From source file:net.ontopia.topicmaps.query.utils.QueryUtils.java

/**
 * PUBLIC: Returns the default query processor for the given topic
 * map and base address. Will always return the same processor for
 * the same (query language, topic map, base address) combination.
 *
 * @since 2.0/*from w  w w. j  av  a 2 s . c om*/
 */
public static QueryProcessorIF getQueryProcessor(String queryLanguage, TopicMapIF topicmap, LocatorIF base) {
    // Get {LocatorIF : QueryProcessorIF} entry
    Map<LocatorIF, Map<String, Reference<QueryProcessorIF>>> qps = qpcache.get(topicmap);
    if (qps == null) {
        qps = new HashMap<LocatorIF, Map<String, Reference<QueryProcessorIF>>>();
        qpcache.put(topicmap, qps);
    }

    Map<String, Reference<QueryProcessorIF>> refmap = qps.get(base);
    if (refmap == null) {
        refmap = new HashMap<String, Reference<QueryProcessorIF>>();
        qps.put(base, refmap);
    }

    // Get QueryProcessorIF
    Reference<QueryProcessorIF> ref = refmap.get(queryLanguage);
    if (ref != null) {
        if (ref.get() != null) {
            return ref.get();
        }
    }

    QueryProcessorIF qp = createQueryProcessor(queryLanguage, topicmap, base);
    refmap.put(queryLanguage, new SoftReference<QueryProcessorIF>(qp));
    return qp;
}

From source file:biz.varkon.shelvesom.util.ImageUtilities.java

/**
 * Retrieves a drawable from the book covers cache, identified by the
 * specified id. If the drawable does not exist in the cache, it is loaded
 * and added to the cache. If the drawable cannot be added to the cache, the
 * specified default drawable is returned.
 * /*from  ww  w  .  ja  v  a 2 s .  c  om*/
 * @param id
 *            The id of the drawable to retrieve
 * @param defaultCover
 *            The default drawable returned if no drawable can be found that
 *            matches the id
 * 
 * @return The drawable identified by id or defaultCover
 * @throws IOException
 * @throws FileNotFoundException
 */
public static FastBitmapDrawable getCachedCover(String id, FastBitmapDrawable defaultCover) {
    FastBitmapDrawable drawable = null;

    SoftReference<FastBitmapDrawable> reference = sArtCache.get(id);
    if (reference != null) {
        drawable = reference.get();
    }

    if (drawable == null) {
        final Bitmap bitmap = loadCover(id);
        if (bitmap != null) {
            drawable = new FastBitmapDrawable(bitmap);
        } else {
            drawable = NULL_DRAWABLE;
        }

        sArtCache.put(id, new SoftReference<FastBitmapDrawable>(drawable));
    }

    return drawable == NULL_DRAWABLE ? defaultCover : drawable;
}

From source file:com.securecomcode.text.ConversationAdapter.java

private MessageRecord getMessageRecord(long messageId, Cursor cursor, String type) {
    SoftReference<MessageRecord> reference = messageRecordCache.get(type + messageId);

    if (reference != null) {
        MessageRecord record = reference.get();

        if (record != null)
            return record;
    }//www .java  2  s  . c o  m

    MmsSmsDatabase.Reader reader = DatabaseFactory.getMmsSmsDatabase(context).readerFor(cursor, masterSecret);

    MessageRecord messageRecord = reader.getCurrent();

    messageRecordCache.put(type + messageId, new SoftReference<MessageRecord>(messageRecord));

    return messageRecord;
}

From source file:net.sf.nmedit.jtheme.store.StorageContext.java

protected Method getStoreCreateMethod(String elementName) throws JTException {
    Map<String, Method> map = null;
    if (storeMethodMap != null) {
        map = storeMethodMap.get();/*from   w  ww . ja v  a 2 s.  co  m*/
    }
    if (map == null) {
        map = new HashMap<String, Method>(160);
        storeMethodMap = new SoftReference<Map<String, Method>>(map);
    }

    Method create = map.get(elementName);
    if (create == null) {
        Class<? extends ComponentElement> storeClass = getStoreClass(elementName);
        if (storeClass == null)
            throw new JTException("No store for element: " + elementName);

        try {
            create = storeClass.getDeclaredMethod("createElement",
                    new Class<?>[] { StorageContext.class, Element.class });
        } catch (SecurityException e) {
            throw new JTException(e);
        } catch (NoSuchMethodException e) {
            throw new JTException("method createElement() not found in " + storeClass, e);
        }

        map.put(elementName, create);
    }
    return create;
}

From source file:com.gokuai.yunkuandroidsdk.imageutils.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 */// w ww .  j  a va  2  s. com
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        // If we're running on Honeycomb or newer, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                    BitmapDrawable newValue) {
                if (RecyclingBitmapDrawable.class.isInstance(oldValue)) {
                    // The removed entry is a recycling drawable, so notify it
                    // that it has been removed from the memory cache
                    ((RecyclingBitmapDrawable) oldValue).setIsCached(false);
                } else {
                    // The removed entry is a standard BitmapDrawable

                    if (Utils.hasHoneycomb()) {
                        // We're running on Honeycomb or later, so add the bitmap
                        // to a SoftRefrence set for possible use with inBitmap later
                        mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue.getBitmap()));
                    }
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:com.github.programmerr47.vkgroups.imageloading.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *//*from w  ww. ja  va 2 s  .c  o  m*/
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    //BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());

        mMemoryCache = new LruCache<String, BitmapDrawable>(mCacheParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, BitmapDrawable oldValue,
                    BitmapDrawable newValue) {
                // We're running on Honeycomb or later, so add the bitmap
                // to a SoftReference set for possible use with inBitmap later
                mReusableBitmaps.add(new SoftReference<>(oldValue.getBitmap()));
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, BitmapDrawable value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
    //END_INCLUDE(init_memory_cache)

    // By default the disk cache is not initialized here as it should be initialized
    // on a separate thread due to disk access.
    if (cacheParams.initDiskCacheOnCreate) {
        // Set up disk cache
        initDiskCache();
    }
}

From source file:org.nativescript.widgets.image.Cache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams The cache parameters to initialize the cache
 *///from   w w  w .j av a  2  s  .  c  o  m
private void init(CacheParams cacheParams) {
    clearCache();
    if (mReusableBitmaps != null) {
        mReusableBitmaps.clear();
        mReusableBitmaps = null;
    }

    mParams = cacheParams;

    // Set up memory cache
    if (mParams.memoryCacheEnabled) {
        if (Worker.debuggable > 0) {
            Log.v(TAG, "Memory cache created (size = " + mParams.memCacheSize + ")");
        }

        // If we're running on Honeycomb or newer, create a set of reusable bitmaps that can be
        // populated into the inBitmap field of BitmapFactory.Options. Note that the set is
        // of SoftReferences which will actually not be very effective due to the garbage
        // collector being aggressive clearing Soft/WeakReferences. A better approach
        // would be to use a strongly references bitmaps, however this would require some
        // balancing of memory usage between this set and the bitmap LruCache. It would also
        // require knowledge of the expected size of the bitmaps. From Honeycomb to JellyBean
        // the size would need to be precise, from KitKat onward the size would just need to
        // be the upper bound (due to changes in how inBitmap can re-use bitmaps).
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = Collections.synchronizedSet(new HashSet<SoftReference<Bitmap>>());
        }

        mMemoryCacheUsage = new HashMap<String, Integer>();
        mMemoryCache = new LruCache<String, Bitmap>(mParams.memCacheSize) {

            /**
             * Notify the removed entry that is no longer being cached
             */
            @Override
            protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
                Integer count = mMemoryCacheUsage.get(key);
                if (Utils.hasHoneycomb() && (count == null || count == 0)) {
                    // We're running on Honeycomb or later, so add the bitmap
                    // to a SoftReference set for possible use with inBitmap later
                    mReusableBitmaps.add(new SoftReference<Bitmap>(oldValue));
                }
            }

            /**
             * Measure item size in kilobytes rather than units which is more practical
             * for a bitmap cache
             */
            @Override
            protected int sizeOf(String key, Bitmap value) {
                final int bitmapSize = getBitmapSize(value) / 1024;
                return bitmapSize == 0 ? 1 : bitmapSize;
            }
        };
    }
}

From source file:com.achep.base.content.ConfigBase.java

/**
 * @return the {@link java.util.HashMap HashMap} with option's keys as the keys, and
 * its {@link Option data} as the values.
 * @see #onCreateMap(java.util.Map)/*from   www .j ava2  s . c om*/
 */
@NonNull
public final Map<String, Option> getMap() {
    Map<String, Option> map = mMapRef.get();
    if (map == null) {
        map = new HashMap<>();
        onCreateMap(map);
        mMapRef = new SoftReference<>(map);
    }
    return map;
}

From source file:org.apache.ctakes.ytex.kernel.IntrinsicInfoContentEvaluatorImpl.java

/**
 * recursively compute the number of leaves. fill in the icInfoMap as we go
 * along//from w w  w  .ja v  a 2  s.  c o m
 * 
 * @param concept
 *            concept for which we should get the leaves
 * @param leafCache
 *            cache of concept's leaves
 * @param icInfoMap
 *            to be updated with leaf counts
 * @param cg
 * @param w
 * @param visitedNodes
 *            list of nodes that have already been visited - we don't need
 *            to revisit them when getting the leaves
 * @return
 * @throws IOException
 */
private HashSet<Integer> getLeaves(ConcRel concept, SoftReference<HashSet<Integer>>[] leafCache,
        Map<String, IntrinsicICInfo> icInfoMap, ConceptGraph cg, BufferedWriter w,
        HashSet<Integer> visitedNodes) throws IOException {
    // look in cache
    SoftReference<HashSet<Integer>> refLeaves = leafCache[concept.getNodeIndex()];
    if (refLeaves != null && refLeaves.get() != null) {
        return refLeaves.get();
    }
    // not in cache - compute recursively
    HashSet<Integer> leaves = new HashSet<Integer>();
    leafCache[concept.getNodeIndex()] = new SoftReference<HashSet<Integer>>(leaves);
    if (concept.isLeaf()) {
        // for leaves, just add the concept id
        leaves.add(concept.getNodeIndex());
    } else {
        IntrinsicICInfo icInfo = icInfoMap.get(concept.getConceptID());
        // have we already computed the leaf count for this node?
        // if yes, then we can ignore previously visited nodes
        // if no, then compute it now and revisit previously visited nodes
        // if we have to
        boolean needLeaves = (icInfo != null && icInfo.getLeafCount() == 0);
        HashSet<Integer> visitedNodesLocal = visitedNodes;
        if (needLeaves || visitedNodesLocal == null) {
            // allocate a set to keep track of nodes we've already visited
            // so that we don't revisit them. if we have already computed
            // this node's leaf count then we reuse whatever the caller gave
            // us if non null, else allocate a new one.
            // if we haven't already computed this node's leaf count,
            // allocate a new set to avoid duplications in the traversal for
            // this node
            visitedNodesLocal = new HashSet<Integer>();
        }
        // for inner nodes, recurse
        for (ConcRel child : concept.getChildren()) {
            // if we've already visited a node, then don't bother adding
            // that node's leaves - we already have them
            if (!visitedNodesLocal.contains(child.getNodeIndex())) {
                leaves.addAll(getLeaves(child, leafCache, icInfoMap, cg, w, visitedNodesLocal));
            }
        }
        // add this node to the set of visited nodes so we know not to
        // revisit. This is only of importance if the caller gave us
        // a non-empty set.
        if (visitedNodes != null && visitedNodes != visitedNodesLocal) {
            visitedNodes.add(concept.getNodeIndex());
            visitedNodes.addAll(visitedNodesLocal);
        }
        // update the leaf count if we haven't done so already
        if (needLeaves) {
            icInfo.setLeafCount(leaves.size());
            // output leaves if desired
            if (w != null) {
                w.write(concept.getConceptID());
                w.write("\t");
                w.write(Integer.toString(leaves.size()));
                w.write("\t");
                Iterator<Integer> iter = leaves.iterator();
                while (iter.hasNext()) {
                    w.write(cg.getConceptList().get(iter.next()).getConceptID());
                    w.write(" ");
                }
                w.newLine();
            }
        }
    }
    return leaves;
}

From source file:org.red5.cache.impl.CacheImpl.java

protected void put(String name, ICacheable obj) {
    // set the objects name
    obj.setName(name);//from  w w w .j  av  a  2s.  c om
    // set a registry entry
    registry.put(name, 1);
    // create a soft reference
    SoftReference<ICacheable> value = new SoftReference<ICacheable>(obj);
    // put an object into the cache
    CACHE.put(name, value);
    log.info(name + " has been added to the cache. Current size: " + CACHE.size());
}