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:org.jactr.core.chunk.five.DefaultSubsymbolicChunk5.java

/**
 * Gets the Activation attribute of the DefaultSubsymbolicChunk5 object
 * //from   w  ww  .  ja  va2  s  .  c o m
 * @param p
 *          Description of Parameter
 * @return The Activation value
 * @since
 */
public double getActivation(ChunkTypeRequest p) {
    // calculate the usual values..
    refreshActivationValues();

    boolean newPattern = p != _lastPattern.get();
    if (newPattern) {
        setSimilarityActivation(computeSimilarityActivation(p));
        _lastPattern = new SoftReference<ChunkTypeRequest>(p);
    }
    return getActivation() + getSimilarityActivation();
}

From source file:com.rivbird.guichecker.bitmapfun.ImageCache.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  . co m*/
private void init(ImageCacheParams cacheParams) {
    mCacheParams = cacheParams;

    // BEGIN_INCLUDE(init_memory_cache)
    // Set up memory cache
    if (mCacheParams.memoryCacheEnabled) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "Memory cache created (size = " + mCacheParams.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>>());
        }

        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 SoftReference 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;
            }
        };
    }
    // 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.xenei.bloomgraph.SerializableNode.java

/**
 * Gets the node that is wrapped.//from  w  ww . j  av a 2  s. c  om
 * 
 * If the node is already known it is returned otherwise an attempt is made
 * to deserialize the node.
 * 
 * @return The node.
 * @throws IOException
 *             if the node can not be deserialized..
 */
public final Node getNode() throws IOException {
    Node retval = null;
    if (node != null) {
        retval = node.get();
    }
    if (retval == null) {
        retval = extractNode();
        node = new SoftReference<Node>(retval);
    }
    return retval;
}

From source file:org.apache.axis2.jaxws.message.databinding.JAXBUtils.java

/**
 * Get a JAXBContext for the class//from w ww. j  a  v  a  2s  .c  om
 *
 * Note: The contextPackage object is used by multiple threads.  It should be considered immutable
 * and not altered by this method.
 * 
 * @param contextPackage  Set<Package> 
 * @param contructionType (output value that indicates how the context was constructed)
 * @param forceArrays (forces the returned JAXBContext to include the array types)
 * @param cacheKey ClassLoader
 * @return JAXBContext
 * @throws JAXBException
 */
public static JAXBContext getJAXBContext(TreeSet<String> contextPackages,
        Holder<CONSTRUCTION_TYPE> constructionType, boolean forceArrays, String key, ClassLoader cacheKey,
        Map<String, ?> properties) throws JAXBException {
    // JAXBContexts for the same class can be reused and are supposed to be thread-safe
    if (log.isDebugEnabled()) {
        log.debug("Following packages are in this batch of getJAXBContext() :");
        for (String pkg : contextPackages) {
            log.debug(pkg);
        }
    }
    if (JAXBUtilsMonitor.isMonitoring()) {
        JAXBUtilsMonitor.addPackageKey(contextPackages.toString());
    }

    // Get or Create The InnerMap using the package key
    ConcurrentHashMap<ClassLoader, JAXBContextValue> innerMap = null;
    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef = jaxbMap.get(key);

    if (softRef != null) {
        innerMap = softRef.get();
    }

    if (innerMap == null) {
        synchronized (jaxbMap) {
            softRef = jaxbMap.get(key);
            if (softRef != null) {
                innerMap = softRef.get();
            }
            if (innerMap == null) {
                innerMap = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                softRef = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(innerMap);
                jaxbMap.put(key, softRef);
            }
        }
    }

    // Now get the contextValue using either the classloader key or 
    // the current Classloader
    ClassLoader cl = getContextClassLoader();
    JAXBContextValue contextValue = null;
    if (cacheKey != null) {
        if (log.isDebugEnabled()) {
            log.debug("Using supplied classloader to retrieve JAXBContext: " + cacheKey);
        }
        contextValue = innerMap.get(cacheKey);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Using classloader from Thread to retrieve JAXBContext: " + cl);
        }
        contextValue = innerMap.get(cl);
    }

    // If the context value is found, but the caller requested that the JAXBContext
    // contain arrays, then rebuild the JAXBContext value
    if (forceArrays && contextValue != null
            && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
        if (log.isDebugEnabled()) {
            log.debug("Found a JAXBContextValue with constructionType=" + contextValue.constructionType
                    + "  but the caller requested a JAXBContext "
                    + " that includes arrays.  A new JAXBContext will be built");
        }
        contextValue = null;
    }

    if (contextPackages == null) {
        contextPackages = new TreeSet<String>();
    }
    if (contextValue == null) {
        synchronized (innerMap) {
            // Try to get the contextValue once more since sync was temporarily exited.
            ClassLoader clKey = (cacheKey != null) ? cacheKey : cl;
            contextValue = innerMap.get(clKey);
            adjustPoolSize(innerMap);
            if (forceArrays && contextValue != null
                    && contextValue.constructionType != JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY_PLUS_ARRAYS) {
                contextValue = null;
            }
            if (contextValue == null) {
                // Create a copy of the contextPackages.  This new TreeSet will
                // contain only the valid contextPackages.
                // Note: The original contextPackage set is accessed by multiple 
                // threads and should not be altered.

                TreeSet<String> validContextPackages = new TreeSet<String>(contextPackages);

                List<String> classRefs = pruneDirectives(validContextPackages);

                int numPackages = validContextPackages.size();

                contextValue = createJAXBContextValue(validContextPackages, clKey, forceArrays, properties,
                        classRefs);

                synchronized (jaxbMap) {
                    // Add the context value with the original package set
                    ConcurrentHashMap<ClassLoader, JAXBContextValue> map1 = null;
                    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef1 = jaxbMap.get(key);
                    if (softRef1 != null) {
                        map1 = softRef1.get();
                    }
                    if (map1 == null) {
                        map1 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                        softRef1 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map1);
                        jaxbMap.put(key, softRef1);
                    }
                    map1.put(clKey, contextValue);

                    String validPackagesKey = validContextPackages.toString();

                    // Add the context value with the new package set
                    ConcurrentHashMap<ClassLoader, JAXBContextValue> map2 = null;
                    SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>> softRef2 = jaxbMap
                            .get(validPackagesKey);
                    if (softRef2 != null) {
                        map2 = softRef2.get();
                    }
                    if (map2 == null) {
                        map2 = new ConcurrentHashMap<ClassLoader, JAXBContextValue>();
                        softRef2 = new SoftReference<ConcurrentHashMap<ClassLoader, JAXBContextValue>>(map2);
                        jaxbMap.put(validPackagesKey, softRef2);
                    }
                    map2.put(clKey, contextValue);

                    if (log.isDebugEnabled()) {
                        log.debug("JAXBContext [created] for " + key);
                        log.debug("JAXBContext also stored by the list of valid packages:" + validPackagesKey);
                    }
                }
            }
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("JAXBContext [from pool] for " + key);
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("JAXBContext constructionType= " + contextValue.constructionType);
        log.debug("JAXBContextValue = " + JavaUtils.getObjectIdentity(contextValue));
        log.debug("JAXBContext = " + JavaUtils.getObjectIdentity(contextValue.jaxbContext));
    }
    constructionType.value = contextValue.constructionType;
    return contextValue.jaxbContext;
}

From source file:com.eviware.soapui.security.log.SecurityTestLogModel.java

public synchronized void addSecurityScanRequestResult(SecurityScanRequestResult securityCheckRequestResult) {
    int size = items.size();
    requestCount++;//w  w  w  .  j a  v a2s  .  c  o  m

    SoftReference<SecurityResult> checkReqResultRef = new SoftReference<SecurityResult>(
            securityCheckRequestResult);

    items.add(securityCheckRequestResult.getChangedParamsInfo(requestCount));
    results.add(checkReqResultRef);
    currentCheckEntriesCount++;
    currentStepEntriesCount++;

    for (String msg : securityCheckRequestResult.getMessages()) {
        items.add(" -> " + msg);
        results.add(checkReqResultRef);
        currentCheckEntriesCount++;
        currentStepEntriesCount++;
    }

    fireIntervalAdded(this, size, items.size() - 1);
    enforceMaxSize();
}

From source file:edu.stanford.muse.webapp.Sessions.java

/** gets the shared/global/server-side session map that correspond to the specified session file.
 *  if the session map has never been loaded or its loaded soft reference has been released, will (re)load the file.
 * @throws IOException /*  w w  w .  j  av a 2  s .c  o  m*/
 * @throws LockObtainFailedException 
 * @throws CorruptIndexException 
 */
private static Map<String, Object> getGlobalSession(String session_filename, String baseDir)
        throws IOException {
    Map<String, Object> map = null;
    synchronized (globalSessions) {
        try {
            map = globalSessions.get(session_filename).get();
        } catch (NullPointerException e) {
            // globalSessions.get(session_filename) is null
            log.warn("Archive " + session_filename + " may be inappropriately loaded/cleaned up previously");
            // be lenient and create a place holder for it.
            globalSessions.put(session_filename, new SoftReference<Map<String, Object>>(null));
        }
    }

    if (map == null) {
        // GCed, reload and it will be temporarily pinned by normal ref
        synchronized (loadPendingSet) {
            if (loadPendingSet.contains(session_filename)) {
                try {
                    do {
                        log.info("Waiting for pending load of " + session_filename);
                        loadPendingSet.wait();
                    } while (loadPendingSet.contains(session_filename));
                } catch (InterruptedException e) {
                    log.info("Exception: " + e + " : " + Util.stackTrace());
                }
                log.info("Pending load of " + session_filename
                        + " finished. Using its result without duplicated loading.");
                return getGlobalSession(session_filename, baseDir); // retry
            } else {
                loadPendingSet.add(session_filename);
            }
        }

        boolean succeeded = false;
        try {
            map = SimpleSessions.loadSessionAsMap(session_filename, baseDir, true /* readOnly */); // not done in synchronized(globalSessions) for performance

            synchronized (globalSessions) {
                Map<String, Object> map_global = globalSessions.get(session_filename).get(); // should not throw NullPointerException again
                if (map_global == null) {
                    log.info("Loaded/reloaded " + session_filename + " into global session");
                    globalSessions.put(session_filename, new SoftReference<Map<String, Object>>(map));
                } else {
                    // may be concurrently put in by other user loading the same archive
                    log.info("Redundant load discarded");
                    map = map_global;
                }
            }

            succeeded = true;
        } finally {
            // release lock even if there is exception
            synchronized (loadPendingSet) {
                loadPendingSet.remove(session_filename);
                loadPendingSet.notifyAll();
            }
            if (!succeeded)
                log.warn("Failed to load " + session_filename);
        }
    }

    return map;
}

From source file:com.amalto.commons.core.utils.xpath.ri.JXPathContextReferenceImpl.java

/**
 * Compile the given expression./*  ww w  .  j  a v a  2  s.  c  om*/
 * @param xpath to compile
 * @return Expression
 */
private Expression compileExpression(String xpath) {
    Expression expr;

    synchronized (compiled) {
        if (USE_SOFT_CACHE) {
            expr = null;
            SoftReference ref = (SoftReference) compiled.get(xpath);
            if (ref != null) {
                expr = (Expression) ref.get();
            }
        } else {
            expr = (Expression) compiled.get(xpath);
        }
    }

    if (expr != null) {
        return expr;
    }

    expr = (Expression) Parser.parseExpression(xpath, getCompiler());

    synchronized (compiled) {
        if (USE_SOFT_CACHE) {
            if (cleanupCount++ >= CLEANUP_THRESHOLD) {
                Iterator it = compiled.entrySet().iterator();
                while (it.hasNext()) {
                    Entry me = (Entry) it.next();
                    if (((SoftReference) me.getValue()).get() == null) {
                        it.remove();
                    }
                }
                cleanupCount = 0;
            }
            compiled.put(xpath, new SoftReference(expr));
        } else {
            compiled.put(xpath, expr);
        }
    }

    return expr;
}

From source file:org.teiid.olingo.web.ODataFilter.java

public void internalDoFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException, TeiidProcessingException {

    HttpServletRequest httpRequest = (HttpServletRequest) request;

    String proxyURI = this.proxyBaseURI;
    if (proxyURI != null) {
        httpRequest = new ProxyHttpServletRequest(httpRequest, proxyURI);
    }//from   w  ww. java  2 s  . c o m

    VDBKey key = null;
    String vdbName = null;
    String version = null;
    String modelName = null;

    String uri = ((HttpServletRequest) request).getRequestURI().toString();
    String fullURL = ((HttpServletRequest) request).getRequestURL().toString();
    if (uri.startsWith("/odata4/static/") || uri.startsWith("/odata4/keycloak/")) { //$NON-NLS-1$ //$NON-NLS-2$
        chain.doFilter(httpRequest, response);
        return;
    }

    String contextPath = httpRequest.getContextPath();
    String baseURI = fullURL.substring(0, fullURL.indexOf(contextPath));

    int endIdx = uri.indexOf('/', contextPath.length() + 1);
    int beginIdx = contextPath.length() + 1;

    if (contextPath.equals("/odata4")) { //$NON-NLS-1$
        if (endIdx == -1) {
            throw new TeiidProcessingException(ODataPlugin.Event.TEIID16020,
                    ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16020));
        }
        baseURI = baseURI + "/odata4"; //$NON-NLS-1$
        vdbName = uri.substring(beginIdx, endIdx);
        int modelIdx = uri.indexOf('/', endIdx + 1);
        if (modelIdx == -1) {
            modelName = uri.substring(endIdx + 1).trim();
            if (modelName.isEmpty()) {
                throw new TeiidProcessingException(ODataPlugin.Event.TEIID16019,
                        ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16019));
            }
        } else {
            modelName = uri.substring(endIdx + 1, modelIdx);
        }

        contextPath = contextPath + "/" + vdbName + "/" + modelName; //$NON-NLS-1$ //$NON-NLS-2$

        vdbName = vdbName.trim();
        if (vdbName.isEmpty()) {
            throw new TeiidProcessingException(ODataPlugin.Event.TEIID16008,
                    ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16008));
        }

    } else {
        if (this.initProperties.getProperty("vdb-name") == null) { //$NON-NLS-1$ 
            throw new TeiidProcessingException(ODataPlugin.Event.TEIID16018,
                    ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16018));
        }

        vdbName = this.initProperties.getProperty("vdb-name"); //$NON-NLS-1$
        version = this.initProperties.getProperty("vdb-version"); //$NON-NLS-1$

        if (endIdx == -1) {
            modelName = uri.substring(beginIdx).trim();
            if (modelName.isEmpty()) {
                throw new TeiidProcessingException(ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16021));
            }
        } else {
            modelName = uri.substring(beginIdx, endIdx);
        }

        contextPath = contextPath + "/" + modelName; //$NON-NLS-1$
    }

    ContextAwareHttpSerlvetRequest contextAwareRequest = new ContextAwareHttpSerlvetRequest(httpRequest);
    contextAwareRequest.setContextPath(contextPath);
    httpRequest = contextAwareRequest;

    key = new VDBKey(vdbName, version);
    if (key.isAtMost()) {
        if (key.getVersion() != null) {
            throw new TeiidProcessingException(ODataPlugin.Event.TEIID16044,
                    ODataPlugin.Util.gs(ODataPlugin.Event.TEIID16044, key));
        }
        key = new VDBKey(vdbName, "1"); //$NON-NLS-1$ //legacy behavior, default to version 1
    }

    SoftReference<OlingoBridge> ref = this.contextMap.get(key);
    OlingoBridge context = null;
    if (ref != null) {
        context = ref.get();
    }

    if (context == null) {
        context = new OlingoBridge();
        ref = new SoftReference<OlingoBridge>(context);
        this.contextMap.put(key, ref);
    }

    Client client = buildClient(key.getName(), key.getVersion(), this.initProperties);
    try {
        Connection connection = client.open();
        registerVDBListener(client, connection);
        ODataHttpHandler handler = context.getHandler(baseURI, client, modelName);
        httpRequest.setAttribute(ODataHttpHandler.class.getName(), handler);
        httpRequest.setAttribute(Client.class.getName(), client);
        chain.doFilter(httpRequest, response);
    } catch (SQLException e) {
        throw new TeiidProcessingException(e);
    } finally {
        try {
            client.close();
        } catch (SQLException e) {
            //ignore
        }
    }
}

From source file:org.apache.axis2.wsdl.util.WSDLWrapperReloadImpl.java

/**
 * Store the cached type.  Since this is a SOFT reference,
 * the gc may remove it./*from   w w  w .ja va 2 s.c  om*/
 * @param types
 */
private void setCachedTypes(Types types) {
    if (USE_SOFT_REFERENCES) {
        if (softTypes == null || softTypes.get() == null) {
            if (types != null) {
                softTypes = new SoftReference(types);
            } else {
                // The wsdl has no types
                softTypes = new SoftReference(Boolean.FALSE);
            }
        }
    }
}

From source file:org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject.java

/**
 * {@inheritDoc}/*  w  w  w . ja  va  2  s .  c o  m*/
 * The returned images are cached via a SoftReference.
 */
@Override
public BufferedImage getImage() throws IOException {
    if (cachedImage != null) {
        BufferedImage cached = cachedImage.get();
        if (cached != null) {
            return cached;
        }
    }

    // get image as RGB
    BufferedImage image = SampledImageReader.getRGBImage(this, getColorKeyMask());

    // soft mask (overrides explicit mask)
    PDImageXObject softMask = getSoftMask();
    if (softMask != null) {
        image = applyMask(image, softMask.getOpaqueImage(), true);
    } else {
        // explicit mask
        PDImageXObject mask = getMask();
        if (mask != null) {
            image = applyMask(image, mask.getOpaqueImage(), false);
        }
    }

    cachedImage = new SoftReference<BufferedImage>(image);
    return image;
}