I have a servlet that acts as a proxy for fetching images by reading the images as bytes off a HttpURLConnection input stream and then writing the bytes to the response output stream. Here’s the relevant code snippet:
HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); InputStream in = connection.getInputStream(); OutputStream out = resp.getOutputStream(); byte[] buf = new byte[1024]; int count = 0; while ((count = in.read(buf)) >= 0) { out.write(buf, 0, count); }
I would like to start caching the image in the proxy servlet. I’m considering wrapping the byte array and storing in a Map but I suspect there is a better way. I’ve noticed the javax.imagio package but I have no experience with it and not sure if its relevant here. Specifically, I am looking for thoughts on how to store the image and not so much the mechanics of caching.
If you are only caching the images, I would recommend keeping the image as a byte array, not as an image. Using imageio to read the image would uncompress the images and they would take much more memory space.
The class WeekHashMap is probably the easiest way to cache things but you have little control on the way entries are evicted from it.