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:com.astamuse.asta4d.web.builtin.StaticResourceHandler.java

private StaticFileInfo createInfo(final ServletContext servletContext, Locale locale, String path)
        throws FileNotFoundException, IOException {

    MultiSearchPathResourceLoader<Pair<String, InputStream>> loader = new MultiSearchPathResourceLoader<Pair<String, InputStream>>() {
        @Override//w w  w.  j a v a  2s. co m
        protected Pair<String, InputStream> loadResource(String name) {
            InputStream is = BinaryDataUtil.retrieveInputStreamByPath(servletContext,
                    this.getClass().getClassLoader(), name);
            if (is != null) {
                return Pair.of(name, is);
            } else {
                return null;
            }
        }
    };

    Pair<String, InputStream> foundResource = loader.searchResource("/",
            LocalizeUtil.getCandidatePaths(path, locale));

    if (foundResource == null) {
        return null;
    }

    StaticFileInfo info = new StaticFileInfo();
    info.contentType = judgContentType(path);
    info.actualPath = foundResource.getLeft();
    info.lastModified = getLastModifiedTime(path);

    // cut the milliseconds
    info.lastModified = info.lastModified / 1000 * 1000;

    info.cacheLimit = getContentCacheSizeLimit(path);

    if (info.cacheLimit == 0) {// don't cache
        info.content = null;
        // we will use the retrieved input stream at the first time for performance reason
        info.firstTimeInput = foundResource.getRight();
    } else {
        byte[] contentData = retrieveBytesFromInputStream(foundResource.getRight(), info.cacheLimit);
        if (contentData == null) {// we cannot cache it due to over limited size
            // fallback to no cache case
            info.content = null;
            info.firstTimeInput = null;
        } else {
            try {
                info.content = new SoftReference<byte[]>(contentData);
            } finally {
                foundResource.getRight().close();
            }
            info.firstTimeInput = null;
        }
    }
    return info;
}

From source file:com.googlecode.fightinglayoutbugs.WebPage.java

/**
 * Returns a two dimensional array <tt>a</tt>, whereby <tt>a[x][y]</tt> is <tt>true</tt>
 * if the pixel with the coordinates x,y in a {@link #getScreenshot screenshot} of this web page
 * belongs to a horizontal edge, otherwise <tt>a[x][y]</tt> is <tt>false</tt>.
 *//*from   w ww .  j a  v  a2 s .c o  m*/
public boolean[][] getHorizontalEdges() {
    boolean[][] horizontalEdges;
    if (_horizontalEdges == null) {
        if (_edgeDetector == null) {
            _edgeDetector = new SimpleEdgeDetector();
        }
        horizontalEdges = _edgeDetector.detectHorizontalEdgesIn(this);
        _horizontalEdges = new SoftReference<boolean[][]>(horizontalEdges);
    } else {
        horizontalEdges = _textPixels.get();
        if (horizontalEdges == null) {
            LOG.warn(
                    "Cached result of horizontal edge detection was garbage collected, running horizontal edge detection again -- give the JVM more heap memory to speed up layout bug detection.");
            _horizontalEdges = null;
            return getHorizontalEdges();
        }
    }
    return horizontalEdges;
}

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

/**
 * Store the cached document element.  Since this is a SOFT reference,
 * the gc may remove it.//from   w ww.  j  a v  a2  s.  c o m
 * @param e Element
 */
private void setCachedDocElement(Element e) {
    if (USE_SOFT_REFERENCES) {
        if (softDocElement == null || softDocElement.get() == null) {
            if (e != null) {
                softDocElement = new SoftReference(e);
            } else {
                // The wsdl has no document element
                softDocElement = new SoftReference(Boolean.FALSE);
            }
        }
    }
}

From source file:org.wso2.carbon.feature.mgt.core.util.IUPropertyUtils.java

/**
 * Collects the installable unit fragments that contain locale data for the given locales.
 *//*from   w w  w.jav a 2  s. c  o  m*/
private static synchronized Collection getLocalizationFragments(Locale locale, List localeVariants) {
    SoftReference collectorRef = (SoftReference) LocaleCollectionCache.get(locale);
    if (collectorRef != null) {
        Collection cached = (Collection) collectorRef.get();
        if (cached != null) {
            return cached;
        }
    }

    final List locales = localeVariants;

    Collector localeFragmentCollector = new Collector() {
        public boolean accept(Object object) {
            boolean haveLocale = false;
            if (object instanceof IInstallableUnitFragment) {
                IInstallableUnitFragment fragment = (IInstallableUnitFragment) object;
                Collection<IProvidedCapability> providedCapabilities = fragment.getProvidedCapabilities();
                for (IProvidedCapability providedCapability : providedCapabilities) {
                    IProvidedCapability nextProvide = providedCapability;
                    if (NAMESPACE_IU_LOCALIZATION.equals(nextProvide.getNamespace())) {
                        String providedLocale = nextProvide.getName();
                        if (providedLocale != null) {
                            for (Iterator iter = locales.iterator(); iter.hasNext();) {
                                if (providedLocale.equals(iter.next())) {
                                    haveLocale = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            return (haveLocale ? super.accept(object) : true);
        }
    };

    //Due to performance problems we restrict locale lookup to the current profile (see bug 233958)
    IProfileRegistry profileRegistry = null;
    try {
        profileRegistry = (IProfileRegistry) ServiceHolder.getProfileRegistry();
    } catch (ProvisioningException e) {
        log.warn("Profile registry unavailable. Default language will be used.");
        return Collections.emptySet();
    }

    IProfile profile = profileRegistry.getProfile(IProfileRegistry.SELF);
    if (profile == null) {
        log.warn("Profile unavailable. Default language will be used.");
        return Collections.emptySet();
    }
    Collection collection = profile
            .query(QueryUtil.createIUPropertyQuery(
                    MetadataFactory.InstallableUnitDescription.PROP_TYPE_FRAGMENT, "true"), null)
            .toUnmodifiableSet();
    LocaleCollectionCache.put(locale, new SoftReference(collection));
    return collection;
}

From source file:com.android.leanlauncher.WidgetPreviewLoader.java

public void recycleBitmap(Object o, Bitmap bitmapToRecycle) {
    String name = getObjectName(o);
    synchronized (mLoadedPreviews) {
        if (mLoadedPreviews.containsKey(name)) {
            Bitmap b = mLoadedPreviews.get(name).get();
            if (b == bitmapToRecycle) {
                mLoadedPreviews.remove(name);
                if (bitmapToRecycle.isMutable()) {
                    synchronized (mUnusedBitmaps) {
                        mUnusedBitmaps.add(new SoftReference<Bitmap>(b));
                    }// ww  w.  j  a va2 s .c  o m
                }
            } else {
                throw new RuntimeException("Bitmap passed in doesn't match up");
            }
        }
    }
}

From source file:org.apache.sysml.runtime.controlprogram.caching.MatrixObject.java

/**
 * NOTE: for reading matrix partitions, we could cache (in its real sense) the read block
 * with soft references (no need for eviction, as partitioning only applied for read-only matrices).
 * However, since we currently only support row- and column-wise partitioning caching is not applied yet.
 * This could be changed once we also support column-block-wise and row-block-wise. Furthermore,
 * as we reject to partition vectors and support only full row or column indexing, no metadata (apart from
 * the partition flag) is required.  /*from   w w w .ja v  a2 s .  co m*/
 * 
 * @param pred index range
 * @return matrix block
 * @throws CacheException if CacheException occurs
 */
public synchronized MatrixBlock readMatrixPartition(IndexRange pred) throws CacheException {
    if (LOG.isTraceEnabled())
        LOG.trace("Acquire partition " + getVarName() + " " + pred);
    long t0 = DMLScript.STATISTICS ? System.nanoTime() : 0;

    if (!_partitioned)
        throw new CacheException("MatrixObject not available to indexed read.");

    //return static partition of set from outside of the program
    if (_partitionInMemory != null)
        return _partitionInMemory;

    MatrixBlock mb = null;

    try {
        boolean blockwise = (_partitionFormat == PDataPartitionFormat.ROW_BLOCK_WISE
                || _partitionFormat == PDataPartitionFormat.COLUMN_BLOCK_WISE);

        //preparations for block wise access
        MatrixFormatMetaData iimd = (MatrixFormatMetaData) _metaData;
        MatrixCharacteristics mc = iimd.getMatrixCharacteristics();
        int brlen = mc.getRowsPerBlock();
        int bclen = mc.getColsPerBlock();

        //get filename depending on format
        String fname = getPartitionFileName(pred, brlen, bclen);

        //probe cache
        if (blockwise && _partitionCacheName != null && _partitionCacheName.equals(fname)) {
            mb = _cache.get(); //try getting block from cache
        }

        if (mb == null) //block not in cache
        {
            //get rows and cols
            long rows = -1;
            long cols = -1;
            switch (_partitionFormat) {
            case ROW_WISE:
                rows = 1;
                cols = mc.getCols();
                break;
            case ROW_BLOCK_WISE:
                rows = brlen;
                cols = mc.getCols();
                break;
            case COLUMN_WISE:
                rows = mc.getRows();
                cols = 1;
                break;
            case COLUMN_BLOCK_WISE:
                rows = mc.getRows();
                cols = bclen;
                break;
            default:
                throw new CacheException("Unsupported partition format: " + _partitionFormat);
            }

            //read the 
            if (MapReduceTool.existsFileOnHDFS(fname))
                mb = readBlobFromHDFS(fname, rows, cols);
            else {
                mb = new MatrixBlock((int) rows, (int) cols, true);
                LOG.warn("Reading empty matrix partition " + fname);
            }
        }

        //post processing
        if (blockwise) {
            //put block into cache
            _partitionCacheName = fname;
            _cache = new SoftReference<MatrixBlock>(mb);

            if (_partitionFormat == PDataPartitionFormat.ROW_BLOCK_WISE) {
                int rix = (int) ((pred.rowStart - 1) % brlen);
                mb = mb.sliceOperations(rix, rix, (int) (pred.colStart - 1), (int) (pred.colEnd - 1),
                        new MatrixBlock());
            }
            if (_partitionFormat == PDataPartitionFormat.COLUMN_BLOCK_WISE) {
                int cix = (int) ((pred.colStart - 1) % bclen);
                mb = mb.sliceOperations((int) (pred.rowStart - 1), (int) (pred.rowEnd - 1), cix, cix,
                        new MatrixBlock());
            }
        }

        //NOTE: currently no special treatment of non-existing partitions necessary 
        //      because empty blocks are written anyway
    } catch (Exception ex) {
        throw new CacheException(ex);
    }

    if (DMLScript.STATISTICS) {
        long t1 = System.nanoTime();
        CacheStatistics.incrementAcquireRTime(t1 - t0);
    }

    return mb;
}

From source file:com.afrozaar.jazzfestreporting.util.ImageCache.java

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

    // 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, then
        if (Utils.hasHoneycomb()) {
            mReusableBitmaps = 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.googlecode.fightinglayoutbugs.WebPage.java

/**
 * Returns a two dimensional array <tt>a</tt>, whereby <tt>a[x][y]</tt> is <tt>true</tt>
 * if the pixel with the coordinates x,y in a {@link #getScreenshot screenshot} of this web page
 * belongs to a vertical edge, otherwise <tt>a[x][y]</tt> is <tt>false</tt>.
 *//* w  w  w.ja v  a2 s . co m*/
public boolean[][] getVerticalEdges() {
    boolean[][] verticalEdges;
    if (_verticalEdges == null) {
        if (_edgeDetector == null) {
            _edgeDetector = new SimpleEdgeDetector();
        }
        verticalEdges = _edgeDetector.detectVerticalEdgesIn(this);
        _verticalEdges = new SoftReference<boolean[][]>(verticalEdges);
    } else {
        verticalEdges = _textPixels.get();
        if (verticalEdges == null) {
            LOG.warn(
                    "Cached result of vertical edge detection was garbage collected, running vertical edge detection again -- give the JVM more heap memory to speed up layout bug detection.");
            _verticalEdges = null;
            return getVerticalEdges();
        }
    }
    return verticalEdges;
}

From source file:Utilities.java

/** Initialization of the names and values
* @return array of two hashmaps first maps
*   allowed key names to their values (String, Integer)
*  and second// w  w  w.  j a va  2s.c o  m
* hashtable for mapping of values to their names (Integer, String)
*/
private static synchronized HashMap[] initNameAndValues() {
    if (namesAndValues != null) {
        HashMap[] arr = (HashMap[]) namesAndValues.get();

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

    Field[] fields;
    // JW - fix Issue #353-swingx: play nicer inside sandbox.
    try {
        fields = KeyEvent.class.getDeclaredFields();
        //           fields = KeyEvent.class.getFields();
    } catch (SecurityException e) {
        // JW: need to do better? What are the use-cases where we don't have
        // any access to the fields?
        fields = new Field[0];
    }

    HashMap<String, Integer> names = new HashMap<String, Integer>(((fields.length * 4) / 3) + 5, 0.75f);
    HashMap<Integer, String> values = new HashMap<Integer, String>(((fields.length * 4) / 3) + 5, 0.75f);

    for (int i = 0; i < fields.length; i++) {
        if (Modifier.isStatic(fields[i].getModifiers())) {
            String name = fields[i].getName();

            if (name.startsWith("VK_")) { // NOI18N

                // exclude VK
                name = name.substring(3);

                try {
                    int numb = fields[i].getInt(null);
                    Integer value = new Integer(numb);
                    names.put(name, value);
                    values.put(value, name);
                } catch (IllegalArgumentException ex) {
                } catch (IllegalAccessException ex) {
                }
            }
        }
    }

    if (names.get("CONTEXT_MENU") == null) { // NOI18N

        Integer n = new Integer(0x20C);
        names.put("CONTEXT_MENU", n); // NOI18N
        values.put(n, "CONTEXT_MENU"); // NOI18N

        n = new Integer(0x20D);
        names.put("WINDOWS", n); // NOI18N
        values.put(n, "WINDOWS"); // NOI18N
    }

    HashMap[] arr = { names, values };

    namesAndValues = new SoftReference<Object>(arr);

    return arr;
}

From source file:ma.glasnost.orika.test.perf.MultiThreadedTestCase.java

/**
 * Since the contract for SoftReference states that all soft references will
 * be cleared by the garbage collector before OOME is thrown, we allocate
 * dummy bytes until we reach OOME.//from  ww  w  .ja  va  2 s .  c  om
 */
private void forceClearSoftAndWeakReferences() {

    SoftReference<Object> checkReference = new SoftReference<Object>(new Object());
    Assert.assertNotNull(checkReference.get());
    try {
        List<byte[]> byteBucket = new ArrayList<byte[]>();
        for (int i = 0; i < Integer.MAX_VALUE; ++i) {
            int available = (int) Math.min((long) Integer.MAX_VALUE, Runtime.getRuntime().maxMemory());
            byteBucket.add(new byte[available]);
        }
    } catch (Throwable e) {
        // Ignore OME; soft references should now have been cleared
        Assert.assertNull(checkReference.get());
    }

}