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;
}
Aggregations