Giter VIP home page Giter VIP logo

disk-lru-cache's Introduction

Disk LRU Cache Android Arsenal

Disk LRU (least recently used) cache with persisted journal. This cache has specific capacity and location. Rarely requested files are evicted by actively used.

Lightweight and extremely easy to use.

Cache icon

Add dependency

Step 1. Add the JitPack repository to your build file

allprojects {
	repositories {
		...
		maven { url 'https://jitpack.io' }
	}
}

Step 2. Add the dependency

implementation 'com.github.solkin:disk-lru-cache:1.4'

Create DiskLruCache

long CACHE_SIZE = 500 * 1024; // Size in bytes
DiskLruCache cache = DiskLruCache.create(getCacheDir(), CACHE_SIZE);

Add file into cache

To manage some files by cache you just need to invoke put method like any Map.

Key - any string to request this file from cache.

File - file, that will be moved into cache.

String key = "some-key";
File file = File.createTempFile("random", ".dat");
cache.put(key, file);

Getting file from cache

To get file from cache, just invoke get method. Yes, also like any Map.

Key is the same you put this file into cache

This method will return File you put into cache or null, if file was evicted from cache.

String key = "some-key";
File file = cache.get(key);

Delete file from cache

To delete file from cache, just invoke delete method.

Key is the same you put this file into cache

File will be deleted from cache and from journal.

String key = "some-key";
cache.delete(key);

Clear cache

Sometime you may need to clear whole cache and drop all stored files.

cache().clearCache();

List keys in cache

To get all keys, managed by cache, invoke keySet() method.

This will return Set<String>.

List all keys in cache may be useful to check all files, stored in cache.

Set<String> keys = cache.keySet();

Get cache status information

There are some useful cache status information, that you can request.

cache.getCacheSize(); // Cache size in bytes, that you set up on cache creation.
cache.getUsedSpace(); // Size of all files, stored in cache.
cache.getFreeSpace(); // Free size in cache.
cache.getJournalSize(); // Internal cache journal size in bytes.

License

MIT License

Copyright (c) 2022 Igor Solkin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

disk-lru-cache's People

Contributors

ashishb avatar codacy-badger avatar solkin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

disk-lru-cache's Issues

Streams not being closed

Sorry, I don't know how to do the pull request thing yet, so I thought I would just post the problem and resolution here.

Journal.java

readJournal() and writeJournal() are causing finalizer and "resource failed to call close" warnings. I believe the issue is with the wrapped input/output streams. Anyway, the below changes using auto resource management resolve the issue.

public void writeJournal() {
    try (FileOutputStream fileStream = new FileOutputStream(file)) {
        try (DataOutputStream stream = new DataOutputStream(fileStream)) {
            stream.writeShort(JOURNAL_FORMAT_VERSION);
            stream.writeInt(map.size());
            for (Record record : map.values()) {
                stream.writeUTF(record.getKey());
                stream.writeUTF(record.getName());
                stream.writeLong(record.getTime());
                stream.writeLong(record.getSize());
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

public static Journal readJournal(FileManager fileManager) {
    File file = fileManager.journal();
    log("[.] Start journal reading", file.getName());
    Journal journal = new Journal(file, fileManager);
    try (FileInputStream fileStream = new FileInputStream(file)) {
        try (DataInputStream stream = new DataInputStream(fileStream)) {
            int version = stream.readShort();
            if (version != JOURNAL_FORMAT_VERSION) {
                throw new IllegalArgumentException("Invalid journal format version");
            }
            int count = stream.readInt();
            long totalSize = 0;
            for (int c = 0; c < count; c++) {
                String key = stream.readUTF();
                String name = stream.readUTF();
                long time = stream.readLong();
                long size = stream.readLong();
                totalSize += size;
                Record record = new Record(key, name, time, size);
                journal.put(record);
            }
            journal.setTotalSize(totalSize);
            log("[.] Journal read. Files count is %d and total size is %d", count, totalSize);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return journal;
}

Thanks, jb

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.