Search in sources :

Example 46 with SoftReference

use of java.lang.ref.SoftReference in project joda-time by JodaOrg.

the class ZoneInfoProvider method getZone.

//-----------------------------------------------------------------------
/**
     * If an error is thrown while loading zone data, the exception is logged
     * to system error and null is returned for this and all future requests.
     * 
     * @param id  the id to load
     * @return the loaded zone
     */
public DateTimeZone getZone(String id) {
    if (id == null) {
        return null;
    }
    Object obj = iZoneInfoMap.get(id);
    if (obj == null) {
        return null;
    }
    if (obj instanceof SoftReference<?>) {
        @SuppressWarnings("unchecked") SoftReference<DateTimeZone> ref = (SoftReference<DateTimeZone>) obj;
        DateTimeZone tz = ref.get();
        if (tz != null) {
            return tz;
        }
        // Reference cleared; load data again.
        return loadZoneData(id);
    } else if (id.equals(obj)) {
        // Load zone data for the first time.
        return loadZoneData(id);
    }
    // If this point is reached, mapping must link to another.
    return getZone((String) obj);
}
Also used : SoftReference(java.lang.ref.SoftReference) DateTimeZone(org.joda.time.DateTimeZone)

Example 47 with SoftReference

use of java.lang.ref.SoftReference in project android_frameworks_base by DirtyUnicorns.

the class HeapTest method xxtestSoftRefPartialClean.

public void xxtestSoftRefPartialClean() throws Exception {
    final int NUM_REFS = 128;
    Object[] objects = new Object[NUM_REFS];
    SoftReference<Object>[] refs = new SoftReference[objects.length];
    /* Create a bunch of objects and a parallel array
        * of SoftReferences.
        */
    makeRefs(objects, refs);
    Runtime.getRuntime().gc();
    /* Let go of the hard references to the objects so that
        * the references can be cleared.
        */
    clearRefs(objects);
    /* Start creating a bunch of temporary and permanent objects
        * to drive GC.
        */
    final int NUM_OBJECTS = 64 * 1024;
    Object[] junk = new Object[NUM_OBJECTS];
    Random random = new Random();
    int i = 0;
    int mod = 0;
    int totalSize = 0;
    int cleared = -1;
    while (i < junk.length && totalSize < 8 * 1024 * 1024) {
        int r = random.nextInt(64 * 1024) + 128;
        Object o = (Object) new byte[r];
        if (++mod % 16 == 0) {
            junk[i++] = o;
            totalSize += r * 4;
        }
        cleared = checkRefs(refs, cleared);
    }
}
Also used : SoftReference(java.lang.ref.SoftReference) Random(java.util.Random)

Example 48 with SoftReference

use of java.lang.ref.SoftReference in project android by JetBrains.

the class ImagePool method create.

@VisibleForTesting
@NotNull
ImageImpl create(final int w, final int h, final int type, @Nullable Consumer<BufferedImage> freedCallback) {
    assert !isDisposed : "ImagePool already disposed";
    EvictingQueue<SoftReference<BufferedImage>> queue = getTypeQueue(w, h, type);
    BufferedImage image;
    SoftReference<BufferedImage> imageRef;
    try {
        imageRef = queue.remove();
        while ((image = imageRef.get()) == null) {
            imageRef = queue.remove();
        }
        if (DEBUG) {
            //noinspection UseOfSystemOutOrSystemErr
            System.out.printf("Re-used image %dx%d - %d\n", w, h, type);
        }
        // Clear the image
        Graphics2D g = image.createGraphics();
        g.setComposite(AlphaComposite.Clear);
        g.fillRect(0, 0, w, h);
        g.dispose();
    } catch (NoSuchElementException e) {
        if (DEBUG) {
            //noinspection UseOfSystemOutOrSystemErr
            System.out.printf("New image %dx%d - %d\n", w, h, type);
        }
        //noinspection UndesirableClassUsage
        image = new BufferedImage(w, h, type);
    }
    ImageImpl pooledImage = new ImageImpl(image);
    final BufferedImage imagePointer = image;
    Reference<?> reference = new FinalizablePhantomReference<Image>(pooledImage, myFinalizableReferenceQueue) {

        @Override
        public void finalizeReferent() {
            if (DEBUG) {
                //noinspection UseOfSystemOutOrSystemErr
                System.out.printf("Released image %dx%d - %d\n", w, h, type);
            }
            myReferences.remove(this);
            getTypeQueue(w, h, type).add(new SoftReference<>(imagePointer));
            if (freedCallback != null) {
                freedCallback.accept(imagePointer);
            }
        }
    };
    myReferences.add(reference);
    return pooledImage;
}
Also used : SoftReference(java.lang.ref.SoftReference) FinalizablePhantomReference(com.google.common.base.FinalizablePhantomReference) BufferedImage(java.awt.image.BufferedImage) NoSuchElementException(java.util.NoSuchElementException) VisibleForTesting(com.android.annotations.VisibleForTesting) NotNull(org.jetbrains.annotations.NotNull)

Example 49 with SoftReference

use of java.lang.ref.SoftReference in project jdk8u_jdk by JetBrains.

the class StandardGlyphVector method getGlyphLogicalBounds.

public Shape getGlyphLogicalBounds(int ix) {
    if (ix < 0 || ix >= glyphs.length) {
        throw new IndexOutOfBoundsException("ix = " + ix);
    }
    Shape[] lbcache;
    if (lbcacheRef == null || (lbcache = (Shape[]) lbcacheRef.get()) == null) {
        lbcache = new Shape[glyphs.length];
        lbcacheRef = new SoftReference(lbcache);
    }
    Shape result = lbcache[ix];
    if (result == null) {
        setFRCTX();
        initPositions();
        // !!! ought to return a rectangle2d for simple cases, though the following works for all
        // get the position, the tx offset, and the x,y advance and x,y adl.  The
        // shape is the box formed by adv (width) and adl (height) offset by
        // the position plus the tx offset minus the ascent.
        ADL adl = new ADL();
        GlyphStrike gs = getGlyphStrike(ix);
        gs.getADL(adl);
        Point2D.Float adv = gs.strike.getGlyphMetrics(glyphs[ix]);
        float wx = adv.x;
        float wy = adv.y;
        float hx = adl.descentX + adl.leadingX + adl.ascentX;
        float hy = adl.descentY + adl.leadingY + adl.ascentY;
        float x = positions[ix * 2] + gs.dx - adl.ascentX;
        float y = positions[ix * 2 + 1] + gs.dy - adl.ascentY;
        GeneralPath gp = new GeneralPath();
        gp.moveTo(x, y);
        gp.lineTo(x + wx, y + wy);
        gp.lineTo(x + wx + hx, y + wy + hy);
        gp.lineTo(x + hx, y + hy);
        gp.closePath();
        result = new DelegatingShape(gp);
        lbcache[ix] = result;
    }
    return result;
}
Also used : Shape(java.awt.Shape) SoftReference(java.lang.ref.SoftReference) GeneralPath(java.awt.geom.GeneralPath) Point2D(java.awt.geom.Point2D)

Example 50 with SoftReference

use of java.lang.ref.SoftReference in project jdk8u_jdk by JetBrains.

the class ConnectionAcceptor method checkConnectPermission.

/**
     * Checks if the current caller has sufficient privilege to make
     * a connection to the remote endpoint.
     * @exception SecurityException if caller is not allowed to use this
     * Channel.
     */
private void checkConnectPermission() throws SecurityException {
    SecurityManager security = System.getSecurityManager();
    if (security == null)
        return;
    if (security != cacheSecurityManager) {
        // The security manager changed: flush the cache
        okContext = null;
        authcache = new WeakHashMap<AccessControlContext, Reference<AccessControlContext>>();
        cacheSecurityManager = security;
    }
    AccessControlContext ctx = AccessController.getContext();
    // appears in the cache, bypass the checkConnect.
    if (okContext == null || !(okContext.equals(ctx) || authcache.containsKey(ctx))) {
        security.checkConnect(ep.getHost(), ep.getPort());
        authcache.put(ctx, new SoftReference<AccessControlContext>(ctx));
    // A WeakHashMap is transformed into a SoftHashSet by making
    // each value softly refer to its own key (Peter's idea).
    }
    okContext = ctx;
}
Also used : AccessControlContext(java.security.AccessControlContext) SoftReference(java.lang.ref.SoftReference) Reference(java.lang.ref.Reference)

Aggregations

SoftReference (java.lang.ref.SoftReference)53 ReferenceQueue (java.lang.ref.ReferenceQueue)7 Reference (java.lang.ref.Reference)6 WeakReference (java.lang.ref.WeakReference)6 PhantomReference (java.lang.ref.PhantomReference)5 Random (java.util.Random)5 IOException (java.io.IOException)4 Bitmap (android.graphics.Bitmap)3 Context (android.content.Context)2 BitmapFactory (android.graphics.BitmapFactory)2 Handler (android.os.Handler)2 Message (android.os.Message)2 MetaClass (groovy.lang.MetaClass)2 Shape (java.awt.Shape)2 File (java.io.File)2 InputStream (java.io.InputStream)2 UndeclaredThrowableException (java.lang.reflect.UndeclaredThrowableException)2 PrivilegedAction (java.security.PrivilegedAction)2 PrivilegedActionException (java.security.PrivilegedActionException)2 SecureClassLoader (java.security.SecureClassLoader)2