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:name.livitski.tools.proper2.Configuration.java

/**
 * Reads this object's configuration settings and caches them for future use
 * if caching is enabled.//from  w  w w  . ja v a  2s  . c  om
 * @return configuration settings map
 * @throws ConfigurationException if there was an error reading the
 * settings
 * @see #isCachingEnabled()
 */
public Properties readConfiguration() throws ConfigurationException {
    Properties config = null;
    if (cachingEnabled && null != configCache)
        config = configCache.get();
    if (null == config) {
        config = readConfigurationFromFile();
        if (cachingEnabled)
            configCache = new SoftReference<Properties>(config);
    }
    return config;
}

From source file:com.ritesh.idea.plugin.reviewboard.ReviewDataProvider.java

public List<Repository> repositories() throws Exception {
    if (repositoriesCache == null || repositoriesCache.get() == null) {
        final RBRepository repositories = client.repositories(200);
        List<Repository> result = new ArrayList<>();
        for (RBRepository.Repository repository : repositories.repositories) {
            result.add(new Repository(repository.id, repository.name));
        }// w w  w  . j  ava  2s.  c o m
        repositoriesCache = new SoftReference<>(result);
        return result;
    }
    return repositoriesCache.get();
}

From source file:im.ene.ribbon.BottomNavigationView.java

private void initialize(final Context context, final AttributeSet attrs, final int defStyleAttr,
        final int defStyleRes) {
    typeface = new SoftReference<>(Typeface.DEFAULT);

    TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.BottomNavigationView, defStyleAttr,
            defStyleRes);/*from  w  ww  . ja v  a2  s. c o  m*/
    final int menuResId = array.getResourceId(R.styleable.BottomNavigationView_ribbon_menu, 0);
    if (menuResId == 0) {
        throw new IllegalArgumentException("A valid menu must be set in xml");
    }

    pendingMenu = MenuParser.inflateMenu(context, menuResId);
    badgeProvider = parseBadgeProvider(this, context,
            array.getString(R.styleable.BottomNavigationView_ribbon_badgeProvider));
    array.recycle();

    backgroundColorAnimation = getResources().getInteger(R.integer.ribbon_background_animation_duration);

    defaultSelectedIndex = 0;

    defaultHeight = getResources().getDimensionPixelSize(R.dimen.ribbon_bottom_navigation_height);
    defaultWidth = getResources().getDimensionPixelSize(R.dimen.ribbon_bottom_navigation_width);
    shadowHeight = getResources().getDimensionPixelOffset(R.dimen.ribbon_top_shadow_height);

    // check if the bottom navigation is translucent
    if (!isInEditMode()) {
        final Activity activity = MiscUtils.getActivity(context);
        if (activity != null) {
            final SystemBarTintManager systemBarTintManager = new SystemBarTintManager(activity);
            if (MiscUtils.hasTranslucentNavigationBar(activity) && //
                    systemBarTintManager.getConfig().isNavigationAtBottom() && //
                    systemBarTintManager.getConfig().hasNavigtionBar()) {
                bottomInset = systemBarTintManager.getConfig().getNavigationBarHeight();
            } else {
                bottomInset = 0;
            }
            topInset = systemBarTintManager.getConfig().getStatusBarHeight();
        }
    }

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
    params.topMargin = shadowHeight;
    backgroundOverlay = new View(getContext());
    backgroundOverlay.setLayoutParams(params);
    addView(backgroundOverlay);
}

From source file:com.yineng.ynmessager.cache.ImageCache.java

/**
 * Initialize the cache, providing all parameters.
 *
 * @param cacheParams/*from  w  ww  .  ja v  a 2s .  c  om*/
 *            The cache parameters to initialize the cache
 */
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:com.anrisoftware.prefdialog.spreadsheetimportdialog.dialog.SpreadsheetImportDialogWorker.java

@Override
protected JDialog createDialog() {
    JDialog jdialog = new JDialog(parentWindow, APPLICATION_MODAL);
    jdialog.setLocale(getLocale());/*from  w  ww .  j av  a  2s . c o  m*/
    SpreadsheetImportDialog importDialog;
    importDialog = spreadsheetImportDialogFactory.create(savedProperties);
    importDialog.setParentInjector(parent);
    importDialog.setDialog(jdialog);
    importDialog.createDialog(parentWindow, importerFactory);
    setupSavedProperties(properties, savedProperties);
    importDialog.setPropertiesNoChecks(properties);
    jdialog.pack();
    jdialog.setSize(size);
    jdialog.setTitle(getDialogTitleFromResource());
    jdialog.setLocationRelativeTo(parentWindow);
    insertListeners(importDialog);
    this.importDialog = new SoftReference<SpreadsheetImportDialog>(importDialog);
    return jdialog;
}

From source file:edu.ku.brc.dbsupport.DatabaseDriverInfo.java

/**
 * Reads in the disciplines file (is loaded when the class is loaded).
 * @return Reads in the disciplines file (is loaded when the class is loaded).
 *///from   w w  w .jav  a  2  s .  c om
public static Vector<DatabaseDriverInfo> getDriversList() {
    Vector<DatabaseDriverInfo> list = null;

    if (driverList != null) {
        list = driverList.get();
    }

    if (list == null) {
        driverList = new SoftReference<Vector<DatabaseDriverInfo>>(loadDatabaseDriverInfo());
    }

    return driverList.get();
}

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

public synchronized void updateSecurityScanResult(SecurityScanResult securityCheckResult, boolean errorsOnly) {
    int startCheckIndex = 0;
    if (items.size() > currentCheckEntriesCount) {
        if (currentCheckEntriesCount > 0)
            startCheckIndex = items.size() - currentCheckEntriesCount;
        else//from  w  w w.ja  v a 2s .  c o  m
            startCheckIndex = items.size();
    }
    if (errorsOnly && !securityCheckResult.isHasRequestsWithWarnings()) {
        // remove all entries for the securityCheck that had no warnings
        checkCount--;
        int size = items.size() - 1;
        while (size >= startCheckIndex) {
            items.remove(size);
            results.remove(size);
            size--;
        }
        if (startCheckIndex > 0) {
            fireIntervalRemoved(this, startCheckIndex, size);
        } else {
            fireIntervalRemoved(this, startCheckIndex, size);
        }

    } else {
        SecurityScan securityCheck = securityCheckResult.getSecurityScan();
        securityCheckResult.detectMissingItems();
        StringBuilder outStr = new StringBuilder("SecurityScan ");
        String statusToDisplay = getStatusToDisplay(securityCheckResult.getExecutionProgressStatus());
        outStr.append(checkCount).append(" [").append(securityCheck.getName()).append("] ")
                .append(statusToDisplay).append(", took = ").append(securityCheckResult.getTimeTaken());
        try {
            if (startCheckIndex > 0 && startCheckIndex < maxSize) {
                items.set(startCheckIndex, outStr.toString());
                SoftReference<SecurityResult> checkResultRef = new SoftReference<SecurityResult>(
                        securityCheckResult);
                results.set(startCheckIndex, checkResultRef);
                currentCheckEntriesCount = 0;
                fireContentsChanged(this, startCheckIndex, startCheckIndex);
            }
        } catch (IndexOutOfBoundsException e) {
            // when log max size is exceeded skip updating the raw since it
            // won't be visible anyway
        }

    }
}

From source file:com.gfan.sbbs.utils.images.ImageManager.java

/**
 * Bitmap.//w w  w.  jav  a2 s. c o m
 * 
 * @param filePath
 *            file path
 * @param bitmap
 * @param quality
 *            1~100
 */
public void put(String file, Bitmap bitmap, int quality) {
    synchronized (this) {
        mCache.put(file, new SoftReference<Bitmap>(bitmap));
    }

    writeFile(file, bitmap, quality);
}

From source file:org.atricore.idbus.kernel.main.databinding.JAXBUtils.java

/**
 * Get a JAXBContext for the class//  ww w  .  ja v a  2  s.  c o  m
 *
 * 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 javax.xml.bind.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:www.image.ImageManager.java

/**
 * ?/*  ww  w.  ja v a  2 s  . c  o  m*/
 * @param file file URL/file PATH
 * @param bitmap
 * @param quality
 */
public Bitmap get(String file) {
    SoftReference<Bitmap> ref;
    Bitmap bitmap;
    //?
    synchronized (this) {
        ref = mCache.get(file);
    }
    if (ref != null) {
        bitmap = ref.get();
        if (bitmap != null) {
            return bitmap;
        }
    }
    //?
    // Now try file.
    bitmap = lookupFile(file);

    if (bitmap != null) {
        synchronized (this) {
            //?
            mCache.put(file, new SoftReference<Bitmap>(bitmap));
        }

        return bitmap;
    }
    //
    return mDefaultBitmap;
}