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:de.dal33t.powerfolder.util.ByteSerializer.java

/**
 * Serialize an object. This method is non-static an re-uses the internal
 * byteoutputstream/*  ww w. j a va 2  s.c  o m*/
 *
 * @param target
 *            The object to be serialized
 * @param compress
 *            true if serialization should compress.
 * @param padToSize
 *            the size to pad the output buffer to. number below 0 means no
 *            padding.
 * @return The serialized object
 * @throws IOException
 *             In case the object cannot be serialized
 */
public byte[] serialize(Serializable target, boolean compress, int padToSize) throws IOException {
    long start = System.currentTimeMillis();
    ByteArrayOutputStream byteOut;
    // Reset buffer
    if (outBufferRef != null && outBufferRef.get() != null) {
        // Reuse old buffer
        byteOut = outBufferRef.get();
        byteOut.reset();
    } else {
        // logFiner("Creating send buffer (512bytes)");
        // Create new bytearray output, 512b buffer
        byteOut = new ByteArrayOutputStream(512);
        if (CACHE_OUT_BUFFER) {
            // Chache outgoing buffer
            outBufferRef = new SoftReference<ByteArrayOutputStream>(byteOut);
        }
    }

    OutputStream targetOut;
    // Serialize....
    if (compress) {
        PFZIPOutputStream zipOut = new PFZIPOutputStream(byteOut);
        targetOut = zipOut;
    } else {
        targetOut = byteOut;
    }
    ObjectOutputStream objOut = new ObjectOutputStream(targetOut);

    // Write
    try {
        objOut.writeUnshared(target);
    } catch (StreamCorruptedException e) {
        LOG.log(Level.WARNING, "Problem while serializing: " + e, e);
        throw e;
    } catch (InvalidClassException e) {
        LOG.log(Level.WARNING, "Problem while serializing: " + target + ": " + e, e);
        throw e;
    }

    objOut.close();

    if (padToSize > 0) {
        int modulo = byteOut.size() % padToSize;
        if (modulo != 0) {
            int additionalBytesRequired = padToSize - (modulo);
            // LOG.warn("Buffersize: " + byteOut.size()
            // + ", Additonal bytes required: " + additionalBytesRequired);
            for (int i = 0; i < additionalBytesRequired; i++) {
                byteOut.write(0);
            }
        }
    }
    byteOut.flush();
    byteOut.close();

    if (byteOut.size() >= 256 * 1024) {
        logWarning("Send buffer exceeds 256KB! " + Format.formatBytes(byteOut.size()) + ". Message: " + target);
    }

    byte[] buf = byteOut.toByteArray();
    if (BENCHMARK) {
        totalObjects++;
        totalTime += System.currentTimeMillis() - start;
        int count = 0;
        if (CLASS_STATS.containsKey(target.getClass())) {
            count = CLASS_STATS.get(target.getClass());
        }
        count++;
        CLASS_STATS.put(target.getClass(), count);
    }
    return buf;
}

From source file:org.jactr.eclipse.runtime.debug.elements.ASTVariable.java

public IVariable[] getVariables() throws DebugException {
    IVariable[] children = _children.get();
    if (children == null) {
        ArrayList<IVariable> variables = new ArrayList<IVariable>();
        for (CommonTree child : Support.getVisibleChildren(_ast))
            variables.add(new ASTVariable(child, _target));

        children = variables.toArray(new IVariable[variables.size()]);
        _children = new SoftReference<IVariable[]>(children);
    }/*w w w  .j  a  va 2  s .  c  o m*/

    return children;
}

From source file:org.jactr.core.utils.collections.CachedCollection.java

synchronized public Collection<I> getCachedValues() {
    Collection<I> rtn = null;
    if (_cachedCollectionReference == null || (rtn = _cachedCollectionReference.get()) == null) {
        rtn = Collections.unmodifiableCollection(new FastList<I>(_backingCollection));
        _cachedCollectionReference = new SoftReference<Collection<I>>(rtn);
    }/*w  w w.  j a va 2 s .  c  o m*/
    return rtn;
}

From source file:cn.dreamtobe.touchgallery.BaseGalleryPagerAdapter.java

@Override
public Bitmap loadCache(final String key) {
    Bitmap bm = null;/* w  w w . ja v a  2  s. c om*/
    if (mMapCache != null) {
        bm = mMapCache.get(key);
    }

    if (bm != null) {
        if (!bm.isRecycled()) {
            return bm;
        } else {
            mMapCache.remove(key);
        }
    }

    if (mLruCache != null) {
        Object o = mLruCache.get(key);
        if (o != null && o instanceof Bitmap) {
            bm = (Bitmap) o;
            mLruCache.remove(key);
            if (!bm.isRecycled()) {
                mLruCache.put(key, bm);
                return bm;
            }
        }
    }

    if (mLruSoftCache != null && mLruSoftCache.get(key) != null) {
        Object o = mLruSoftCache.get(key).get();
        if (o != null && o instanceof Bitmap) {
            bm = (Bitmap) o;
            mLruSoftCache.remove(key);
            if (!bm.isRecycled()) {
                mLruSoftCache.put(key, new SoftReference<Object>(bm));
                return bm;
            }
        }
    }

    return null;
}

From source file:com.cm.beer.util.ContentManager.java

/**
 * //from   ww w . j a v  a2 s  . co m
 * @param urlString
 * @return
 */
public String fetchContent(String urlString) {
    if (mContentCache.containsKey(urlString)) {
        if (Logger.isLogEnabled())
            Logger.log("Returning Content from Cache:" + urlString);
        SoftReference<String> softReference = mContentCache.get(urlString);
        if ((softReference == null) || (softReference.get() == null)) {
            mContentCache.remove(urlString);
            if (Logger.isLogEnabled())
                Logger.log("fetchContent():Soft Reference has been Garbage Collected:" + urlString);
        } else {
            return softReference.get();
        }
    }

    if (Logger.isLogEnabled())
        Logger.log("url:" + urlString);
    try {
        // prevents multithreaded fetches for the same url
        mLockCache.put(urlString, urlString);
        if (Logger.isLogEnabled())
            Logger.log("Begin Downloading:" + urlString);
        InputStream is = fetch(urlString);
        if (Logger.isLogEnabled())
            Logger.log("End Downloading:" + urlString);

        String result = Util.convertStreamToString(is, "UTF-8");

        mContentCache.put(urlString, new SoftReference<String>(result));
        mLockCache.remove(urlString);

        if (Logger.isLogEnabled())
            Logger.log(result);

        return result;
    } catch (Throwable e) {
        Log.e(this.getClass().getName(), "fetchDrawable failed", e);
        return null;
    }
}

From source file:pl.otros.logview.api.gui.LogViewPanelWrapper.java

public LogViewPanelWrapper(final String name, final Stoppable stoppable, final TableColumns[] visibleColumns,
        final LogDataTableModel logDataTableModel, final DataConfiguration configuration,
        final OtrosApplication otrosApplication) {

    this.name = name;
    this.configuration = configuration;
    this.otrosApplication = otrosApplication;
    logLoader = otrosApplication.getLogLoader();
    this.addHierarchyListener(e -> {
        if (e.getChangeFlags() == 1 && e.getChanged().getParent() == null) {
            closing();/*  www . j ava 2  s.  co m*/
        }
    });
    final TableColumns[] columns = (visibleColumns == null) ? TableColumns.ALL_WITHOUT_LOG_SOURCE
            : visibleColumns;

    fillDefaultConfiguration();

    SoftReference<Stoppable> stoppableReference = new SoftReference<>(stoppable);
    // this.statusObserver = statusObserver;
    dataTableModel = logDataTableModel == null ? new LogDataTableModel() : logDataTableModel;
    logViewPanel = new LogViewPanel(dataTableModel, columns, otrosApplication);

    cardLayout = new CardLayout();
    GridBagConstraints c = new GridBagConstraints();
    c.insets = new Insets(10, 10, 10, 10);
    c.anchor = GridBagConstraints.PAGE_START;
    c.fill = GridBagConstraints.HORIZONTAL;
    c.gridx = 0;
    c.gridy = 0;
    c.ipadx = 1;
    c.ipady = 1;
    c.weightx = 10;
    c.weighty = 1;

    c.gridy++;
    c.weighty = 3;
    loadingProgressBar = new JProgressBar();
    loadingProgressBar.setIndeterminate(false);
    loadingProgressBar.setStringPainted(true);
    loadingProgressBar.setString("Connecting...");

    c.gridy++;
    c.weighty = 1;
    c.weightx = 2;
    c.gridy++;
    c.weightx = 1;
    JButton stopButton = new JButton("Stop, you have imported already enough!");
    stopButton.addActionListener(e -> {
        Stoppable stoppable1 = stoppableReference.get();
        if (stoppable1 != null) {
            stoppable1.stop();
        }
    });

    setLayout(cardLayout);
    add(logViewPanel, CARD_LAYOUT_CONTENT);
    cardLayout.show(this, CARD_LAYOUT_LOADING);

}

From source file:com.cm.beer.util.DrawableManager.java

/**
 * //from   w  w  w . ja  v  a2s .  c  o m
 * @param urlString
 * @return
 */
public Drawable fetchDrawable(String urlString) {
    if (mDrawableCache.containsKey(urlString)) {
        if (Logger.isLogEnabled())
            Logger.log("Returning Drawable from Cache:" + urlString);
        SoftReference<Drawable> softReference = mDrawableCache.get(urlString);
        if ((softReference == null) || (softReference.get() == null)) {
            mDrawableCache.remove(urlString);
            if (Logger.isLogEnabled())
                Logger.log("fetchDrawable():Soft Reference has been Garbage Collected:" + urlString);
        } else {
            return softReference.get();
        }
    }

    if (Logger.isLogEnabled())
        Logger.log("image url:" + urlString);
    try {
        // prevents multithreaded fetches for the same image
        mLockCache.put(urlString, urlString);
        if (Logger.isLogEnabled())
            Logger.log("Begin Downloading:" + urlString);
        InputStream is = fetch(urlString);
        if (Logger.isLogEnabled())
            Logger.log("End Downloading:" + urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");
        mDrawableCache.put(urlString, new SoftReference<Drawable>(drawable));
        mLockCache.remove(urlString);
        if (Logger.isLogEnabled())
            Logger.log("got a thumbnail drawable: " + drawable.getBounds() + ", "
                    + drawable.getIntrinsicHeight() + "," + drawable.getIntrinsicWidth() + ", "
                    + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
        return drawable;
    } catch (Throwable e) {
        Log.e(this.getClass().getName(), "fetchDrawable failed", e);
        return null;
    }
}

From source file:com.hunch.ImageManager.java

protected void addToMemoryCache(Bitmap d, URL url) {
    //Log.v( Const.TAG, "adding bitmap to memory cache (" + url +  ")" );
    // add by soft reference to the level one cache (in memory)
    drawableMap.put(url, new SoftReference<Bitmap>(d));
}

From source file:org.jinzora.util.DrawableManager.java

public Drawable fetchDrawable(String urlString) {
    if (drawableMap.containsKey(urlString)) {
        SoftReference<Drawable> reference = drawableMap.get(urlString);
        Drawable drawable = reference.get();
        if (drawable != null) {
            if (DBG)
                Log.d(TAG, "Using cached image");
            return drawable;
        } else {/*from ww  w  .j av a  2 s.c  om*/
            if (DBG)
                Log.d(TAG, "Soft reference cleared.");
            drawableMap.remove(urlString);
        }
    }

    if (DBG)
        Log.d(TAG, "Fetching image");
    try {
        InputStream is = fetch(urlString);
        Drawable drawable = Drawable.createFromStream(is, "src");

        if (drawable != null) {
            drawableMap.put(urlString, new SoftReference<Drawable>(drawable));
        } else {
            Log.w(this.getClass().getSimpleName(), "could not get thumbnail for " + urlString);
        }

        return drawable;
    } catch (MalformedURLException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    } catch (IOException e) {
        Log.e(this.getClass().getSimpleName(), "fetchDrawable failed", e);
        return null;
    }
}

From source file:org.codehaus.groovy.grails.commons.metaclass.WeakGenericDynamicProperty.java

public void set(Object object, Object newValue) {
    if (!readyOnly) {
        if (this.type.isInstance(newValue))
            propertyToInstanceMap.put(String.valueOf(System.identityHashCode(object)) + getPropertyName(),
                    new SoftReference<Object>(newValue));
        else if (newValue != null)
            throw new MissingPropertyException(
                    "Property '" + this.getPropertyName() + "' for object '" + object.getClass()
                            + "' cannot be set with value '" + newValue + "'. Incorrect type.",
                    object.getClass());/*from   ww w .  j  a  va2 s. c  o  m*/
    } else {
        throw new MissingPropertyException("Property '" + this.getPropertyName() + "' for object '"
                + object.getClass() + "' is read-only!", object.getClass());
    }
}