Search in sources :

Example 36 with SoftReference

use of java.lang.ref.SoftReference in project fastjson by alibaba.

the class ReferenceCodec method deserialze.

@SuppressWarnings({ "unchecked", "rawtypes" })
public <T> T deserialze(DefaultJSONParser parser, Type type, Object fieldName) {
    ParameterizedType paramType = (ParameterizedType) type;
    Type itemType = paramType.getActualTypeArguments()[0];
    Object itemObject = parser.parseObject(itemType);
    Type rawType = paramType.getRawType();
    if (rawType == AtomicReference.class) {
        return (T) new AtomicReference(itemObject);
    }
    if (rawType == WeakReference.class) {
        return (T) new WeakReference(itemObject);
    }
    if (rawType == SoftReference.class) {
        return (T) new SoftReference(itemObject);
    }
    throw new UnsupportedOperationException(rawType.toString());
}
Also used : ParameterizedType(java.lang.reflect.ParameterizedType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) SoftReference(java.lang.ref.SoftReference) WeakReference(java.lang.ref.WeakReference) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 37 with SoftReference

use of java.lang.ref.SoftReference in project StickerCamera by Skykai521.

the class ImageUtils method byteToBitmap.

public static Bitmap byteToBitmap(byte[] imgByte) {
    InputStream input = null;
    Bitmap bitmap = null;
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inSampleSize = 1;
    input = new ByteArrayInputStream(imgByte);
    SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(input, null, options));
    bitmap = (Bitmap) softRef.get();
    if (imgByte != null) {
        imgByte = null;
    }
    try {
        if (input != null) {
            input.close();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bitmap;
}
Also used : Bitmap(android.graphics.Bitmap) SoftReference(java.lang.ref.SoftReference) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) BitmapFactory(android.graphics.BitmapFactory) IOException(java.io.IOException)

Example 38 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 39 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 40 with SoftReference

use of java.lang.ref.SoftReference in project intellij-community by JetBrains.

the class GCUtil method tryGcSoftlyReachableObjects.

/**
   * Try to force VM to collect soft references if possible.
   * Method doesn't guarantee to succeed, and should not be used in the production code.
   * Commits / hours optimized method code: 5 / 3
   */
@TestOnly
public static void tryGcSoftlyReachableObjects() {
    //long started = System.nanoTime();
    ReferenceQueue<Object> q = new ReferenceQueue<Object>();
    SoftReference<Object> ref = new SoftReference<Object>(new Object(), q);
    ArrayList<SoftReference<?>> list = ContainerUtil.newArrayListWithCapacity(100 + useReference(ref));
    System.gc();
    final long freeMemory = Runtime.getRuntime().freeMemory();
    for (int i = 0; i < 100; i++) {
        if (q.poll() != null) {
            break;
        }
        // full gc is caused by allocation of large enough array below, SoftReference will be cleared after two full gc
        int bytes = Math.min((int) (freeMemory * 0.45), Integer.MAX_VALUE / 2);
        list.add(new SoftReference<Object>(new byte[bytes]));
    }
    // use ref is important as to loop to finish with several iterations: long runs of the method (~80 run of PsiModificationTrackerTest)
    // discovered 'ref' being collected and loop iterated 100 times taking a lot of time
    list.ensureCapacity(list.size() + useReference(ref));
    // do not leave a chance for our created SoftReference's content to lie around until next full GC's
    for (SoftReference createdReference : list) createdReference.clear();
//System.out.println("Done gc'ing refs:" + ((System.nanoTime() - started) / 1000000));
}
Also used : ReferenceQueue(java.lang.ref.ReferenceQueue) SoftReference(java.lang.ref.SoftReference) TestOnly(org.jetbrains.annotations.TestOnly)

Aggregations

SoftReference (java.lang.ref.SoftReference)56 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