Skip to content

Instantly share code, notes, and snippets.

@givenjazz
Last active April 19, 2016 12:39
Show Gist options
  • Save givenjazz/5626084 to your computer and use it in GitHub Desktop.
Save givenjazz/5626084 to your computer and use it in GitHub Desktop.
It's BitmapCache for ImageLoader.ImageCache of Volley. It rarely use memory through WeakReference. And it's thread-safety.
/*
* Copyright 2013 Hi Zeon
* Copyright 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public class WeakImageCache implements ImageLoader.ImageCache
{
private final static int MAX_SIZE = 4096;
private ConcurrentHashMap<String, WeakReference<Bitmap>> map
= new ConcurrentHashMap<String, WeakReference<Bitmap>>();
@Override
public void putBitmap(String k, Bitmap v){
if(map.size() > MAX_SIZE){
map.clear();
}
map.put(k, new WeakReference<Bitmap>(v));
}
@Override
public Bitmap getBitmap(String key){
WeakReference<Bitmap> ref = map.get(key);
if(ref == null){
return null;
}
return ref.get();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment