开发者

how can we get images through cache once they are in memory and how to make such a logic

开发者 https://www.devze.com 2022-12-28 06:11 出处:网络
I am making a web applic开发者_如何学Cation, I want to store images in cache. Next time I don\'t want to get images from network. How can I implement using java, using WeakHashmap or Hashmap.Let\'s sa

I am making a web applic开发者_如何学Cation, I want to store images in cache. Next time I don't want to get images from network. How can I implement using java, using WeakHashmap or Hashmap.


Let's say you have class NetworkImageService which fetches image remotely:

class NetworkImageService {

    public Image getImage(name) { ... }

}

Then you can subclass it to have CachedNetworkImageService, like this:

 class CachedNetworkImageService extends NetworkImageService {

    Cache cache = new Cache();

    public Image getImage(name) { ... 
          Image img = cache.get(name);
          if( img == null ) {
                 img = super.getImage(name);
                 cache.put( name, img );
          }
          return img.
    }
}

That's the basic idea of how I do usually (but it's pseudo-code). You can of course improve it and use for instance cache.contains() instead to check against null.

In the most basic case, you can substitute Cache with Hashmap. Otherwise you can improve this and implement various strategies in the cache. You can have an eviction policy that remove image after some time, or following a LIFO scheme.

The code above does not support concurrent access, so you would also need to consider that. The most basic way to make it thread-safe is to synchronize the method getImage().

0

精彩评论

暂无评论...
验证码 换一张
取 消