您好,登錄后才能下訂單哦!
這篇文章主要介紹“java中BitCaskKeyDir的用法”,在日常操作中,相信很多人在java中BitCaskKeyDir的用法問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”java中BitCaskKeyDir的用法”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
本文主要研究一下BitCaskKeyDir
bitcask-java/src/main/java/com/trifork/bitcask/BitCaskKeyDir.java
public class BitCaskKeyDir { Map<ByteString, BitCaskEntry> map = new HashMap<ByteString, BitCaskEntry>(); ReadWriteLock rwl = new ReentrantReadWriteLock(); private boolean is_ready; public boolean put(ByteString key, BitCaskEntry ent) { Lock writeLock = rwl.writeLock(); writeLock.lock(); try { BitCaskEntry old = map.get(key); if (old == null) { map.put(key, ent); return true; } else if (ent.is_newer_than(old)) { map.put(key, ent); return true; } else { return false; } } finally { writeLock.unlock(); } } public BitCaskEntry get(ByteString key) { Lock readLock = rwl.readLock(); readLock.lock(); try { return map.get(key); } finally { readLock.unlock(); } } //...... }
BitCaskKeyDir提供了map來存放BitCaskEntry;其put方法使用writeLock.lock(),對于old值為null的或者新值大于old值的才put進去,否則返回false,最后writeLock.unlock();其get方法使用readLock.lock()從map讀取指定key的值,最后readLock.unlock()
bitcask-java/src/main/java/com/trifork/bitcask/BitCaskKeyDir.java
public class BitCaskKeyDir { public static Map<File,BitCaskKeyDir> key_dirs = new HashMap<File, BitCaskKeyDir>(); public static Lock keydir_lock = new ReentrantLock(); public static BitCaskKeyDir keydir_new(File dirname, int openTimeoutSecs) throws IOException { File abs_name = dirname.getAbsoluteFile(); BitCaskKeyDir dir; keydir_lock.lock(); try { dir = key_dirs.get(abs_name); if (dir == null) { dir = new BitCaskKeyDir(); key_dirs.put(abs_name, dir); return dir; } } finally { keydir_lock.unlock(); } if (dir.wait_for_ready(openTimeoutSecs)) { return dir; } else { throw new IOException("timeout while waiting for keydir"); } } public synchronized boolean is_ready() { return is_ready; } public synchronized void mark_ready() { is_ready = true; this.notifyAll(); } public synchronized boolean wait_for_ready(int timeout_secs) { long now = System.currentTimeMillis(); long abs_timeout = now + (timeout_secs * 1000); while (!is_ready && now < abs_timeout) { try { wait(); } catch (InterruptedException e) { // ignore } now = System.currentTimeMillis(); } return is_ready; } }
BitCaskKeyDir定義了static的key_dirs,用于存放指定File的BitCaskKeyDir;其keydir_new會針對不存在的BitCaskKeyDir進行創建,最后通過dir.wait_for_ready(openTimeoutSecs)等待ready
BitCaskKeyDir提供了map來存放BitCaskEntry;其put方法使用writeLock.lock(),對于old值為null的或者新值大于old值的才put進去,否則返回false,最后writeLock.unlock();其get方法使用readLock.lock()從map讀取指定key的值,最后readLock.unlock()
到此,關于“java中BitCaskKeyDir的用法”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。