1 /*
   2  * Copyright (c) 2011, 2014, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.awt.image;
  27 
  28 import java.awt.*;
  29 import java.lang.ref.*;
  30 import java.util.*;
  31 import java.util.concurrent.locks.*;
  32 import sun.awt.AppContext;
  33 
  34 /**
  35  * ImageCache - A fixed pixel count sized cache of Images keyed by arbitrary
  36  * set of arguments. All images are held with SoftReferences so they will be
  37  * dropped by the GC if heap memory gets tight. When our size hits max pixel
  38  * count least recently requested images are removed first.
  39  *
  40  * The ImageCache must be used from the thread with an AppContext only.
  41  *
  42  */
  43 final public class ImageCache {
  44 
  45     // Ordered Map keyed by args hash, ordered by most recent accessed entry.
  46     private final LinkedHashMap<PixelsKey, ImageSoftReference> map
  47             = new LinkedHashMap<>(16, 0.75f, true);
  48 
  49     // Maximum number of pixels to cache, this is used if maxCount
  50     private final int maxPixelCount;
  51     // The current number of pixels stored in the cache
  52     private int currentPixelCount = 0;
  53 
  54     // Lock for concurrent access to map
  55     private final ReadWriteLock lock = new ReentrantReadWriteLock();
  56     // Reference queue for tracking lost softreferences to images in the cache
  57     private final ReferenceQueue<Image> referenceQueue = new ReferenceQueue<>();
  58 
  59     public static ImageCache getInstance() {
  60         return AppContext.getSoftReferenceValue(ImageCache.class,
  61                 () -> new ImageCache());
  62     }
  63 
  64     ImageCache(final int maxPixelCount) {
  65         this.maxPixelCount = maxPixelCount;
  66     }
  67 
  68     ImageCache() {
  69         this((8 * 1024 * 1024) / 4); // 8Mb of pixels
  70     }
  71 
  72     public void flush() {
  73         lock.writeLock().lock();
  74         try {
  75             map.clear();
  76         } finally {
  77             lock.writeLock().unlock();
  78         }
  79     }
  80 
  81     public Image getImage(final PixelsKey key){
  82         final ImageSoftReference ref;
  83         lock.readLock().lock();
  84         try {
  85             ref = map.get(key);
  86         } finally {
  87             lock.readLock().unlock();
  88         }
  89         return ref == null ? null : ref.get();
  90     }
  91 
  92     /**
  93      * Sets the cached image for the specified constraints.
  94      *
  95      * @param key The key with which the specified image is to be associated
  96      * @param image  The image to store in cache
  97      */
  98     public void setImage(final PixelsKey key, final Image image) {
  99 
 100         lock.writeLock().lock();
 101         try {
 102             ImageSoftReference ref = map.get(key);
 103 
 104             // check if currently in map
 105             if (ref != null) {
 106                 if (ref.get() != null) {
 107                     return;
 108                 }
 109                 // soft image has been removed
 110                 currentPixelCount -= key.getPixelCount();
 111                 map.remove(key);
 112             };
 113 
 114 
 115             // add new image to pixel count
 116             final int newPixelCount = key.getPixelCount();
 117             currentPixelCount += newPixelCount;
 118             // clean out lost references if not enough space
 119             if (currentPixelCount > maxPixelCount) {
 120                 while ((ref = (ImageSoftReference)referenceQueue.poll()) != null) {
 121                     //reference lost
 122                     map.remove(ref.key);
 123                     currentPixelCount -= ref.key.getPixelCount();
 124                 }
 125             }
 126 
 127             // remove old items till there is enough free space
 128             if (currentPixelCount > maxPixelCount) {
 129                 final Iterator<Map.Entry<PixelsKey, ImageSoftReference>>
 130                         mapIter = map.entrySet().iterator();
 131                 while ((currentPixelCount > maxPixelCount) && mapIter.hasNext()) {
 132                     final Map.Entry<PixelsKey, ImageSoftReference> entry =
 133                             mapIter.next();
 134                     mapIter.remove();
 135                     final Image img = entry.getValue().get();
 136                     if (img != null) img.flush();
 137                     currentPixelCount -= entry.getValue().key.getPixelCount();
 138                 }
 139             }
 140 
 141             // finally put new in map
 142             map.put(key, new ImageSoftReference(key, image, referenceQueue));
 143         } finally {
 144             lock.writeLock().unlock();
 145         }
 146     }
 147 
 148     public interface PixelsKey {
 149 
 150         int getPixelCount();
 151     }
 152 
 153     private static class ImageSoftReference extends SoftReference<Image> {
 154 
 155         final PixelsKey key;
 156 
 157         ImageSoftReference(final PixelsKey key, final Image referent,
 158                 final ReferenceQueue<? super Image> q) {
 159             super(referent, q);
 160             this.key = key;
 161         }
 162     }
 163 }