PageRenderTime 14ms CodeModel.GetById 2ms app.highlight 7ms RepoModel.GetById 2ms app.codeStats 0ms

/UniversalImageLoader/src/com/nostra13/universalimageloader/cache/disc/impl/LimitedAgeDiscCache.java

https://github.com/rashedulkabir/Android-Universal-Image-Loader
Java | 79 lines | 47 code | 10 blank | 22 comment | 5 complexity | 0ad3da5918af68437ec71387d84eaea9 MD5 | raw file
 1package com.nostra13.universalimageloader.cache.disc.impl;
 2
 3import java.io.File;
 4import java.util.Collections;
 5import java.util.HashMap;
 6import java.util.Map;
 7
 8import com.nostra13.universalimageloader.cache.disc.BaseDiscCache;
 9import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
10import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
11
12/**
13 * Cache which deletes files which were loaded more than defined time. Cache size is unlimited.
14 * 
15 * @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
16 * @see BaseDiscCache
17 */
18public class LimitedAgeDiscCache extends BaseDiscCache {
19
20	private final long maxFileAge;
21
22	private final Map<File, Long> loadingDates = Collections.synchronizedMap(new HashMap<File, Long>());
23
24	/**
25	 * @param cacheDir
26	 *            Directory for file caching
27	 * @param maxAge
28	 *            Max file age (in seconds). If file age will exceed this value then it'll be removed on next treatment
29	 *            (and therefore be reloaded).
30	 */
31	public LimitedAgeDiscCache(File cacheDir, long maxAge) {
32		this(cacheDir, new HashCodeFileNameGenerator(), maxAge);
33	}
34
35	/**
36	 * @param cacheDir
37	 *            Directory for file caching
38	 * @param fileNameGenerator
39	 *            Name generator for cached files
40	 * @param maxAge
41	 *            Max file age (in seconds). If file age will exceed this value then it'll be removed on next treatment
42	 *            (and therefore be reloaded).
43	 */
44	public LimitedAgeDiscCache(File cacheDir, FileNameGenerator fileNameGenerator, long maxAge) {
45		super(cacheDir, fileNameGenerator);
46		this.maxFileAge = maxAge * 1000; // to milliseconds
47		readLoadingDates();
48	}
49
50	private void readLoadingDates() {
51		File[] cachedFiles = getCacheDir().listFiles();
52		for (File cachedFile : cachedFiles) {
53			loadingDates.put(cachedFile, cachedFile.lastModified());
54		}
55	}
56
57	@Override
58	public void put(String key, File file) {
59		long currentTime = System.currentTimeMillis();
60		file.setLastModified(currentTime);
61		loadingDates.put(file, currentTime);
62	}
63
64	@Override
65	public File get(String key) {
66		File file = super.get(key);
67		if (file.exists()) {
68			Long loadingDate = loadingDates.get(file);
69			if (loadingDate == null) {
70				loadingDate = file.lastModified();
71			}
72			if (System.currentTimeMillis() - loadingDate > maxFileAge) {
73				file.delete();
74				loadingDates.remove(file);
75			}
76		}
77		return file;
78	}
79}