Search in sources :

Example 1 with FinalizablePhantomReference

use of com.google.common.base.FinalizablePhantomReference 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)

Aggregations

VisibleForTesting (com.android.annotations.VisibleForTesting)1 FinalizablePhantomReference (com.google.common.base.FinalizablePhantomReference)1 BufferedImage (java.awt.image.BufferedImage)1 SoftReference (java.lang.ref.SoftReference)1 NoSuchElementException (java.util.NoSuchElementException)1 NotNull (org.jetbrains.annotations.NotNull)1