Skip to content

Commit

Permalink
Start with Tree
Browse files Browse the repository at this point in the history
  • Loading branch information
tomfran committed Oct 1, 2023
1 parent 6590192 commit 281f87d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 7 deletions.
16 changes: 9 additions & 7 deletions src/main/java/com/tomfran/lsm/memtable/Memtable.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,24 @@

public class Memtable {

static final int DEFAULT_SAMPLE_SIZE = 1000;
static final int DEFAULT_SSTABLE_SAMPLE_SIZE = 1 << 10;

SkipList list;


public Memtable() {
list = new SkipList();
}

public Memtable(int numElements) {
list = new SkipList(numElements);
}

public void add(Item item) {
list.add(item);
}

public void get(byte[] key) {
list.get(key);
public Item get(byte[] key) {
return list.get(key);
}

public void remove(byte[] key) {
Expand All @@ -30,9 +33,8 @@ public int size() {
return list.size();
}

public SSTable flush() {
String filename = "sstable-" + System.currentTimeMillis();
return new SSTable(filename, list, DEFAULT_SAMPLE_SIZE, list.size());
public SSTable flush(String filename) {
return new SSTable(filename, list, DEFAULT_SSTABLE_SAMPLE_SIZE, list.size());
}

}
56 changes: 56 additions & 0 deletions src/main/java/com/tomfran/lsm/tree/LSMTree.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.tomfran.lsm.tree;

import com.tomfran.lsm.memtable.Memtable;
import com.tomfran.lsm.sstable.SSTable;
import com.tomfran.lsm.types.Item;

import java.util.LinkedList;

public class LSMTree {

static final int MEMTABLE_MAX_SIZE = 1 << 16;

Memtable mutableMemtable;
LinkedList<Memtable> immutableMemtables;
LinkedList<SSTable> tables;

public LSMTree() {
mutableMemtable = new Memtable(MEMTABLE_MAX_SIZE);
immutableMemtables = new LinkedList<>();
tables = new LinkedList<>();
}

public void add(Item item) {
mutableMemtable.add(item);
checkMemtableSize();
}

public void delete(byte[] key) {
mutableMemtable.remove(key);
checkMemtableSize();
}

private void checkMemtableSize() {
if (mutableMemtable.size() >= MEMTABLE_MAX_SIZE) {
immutableMemtables.add(mutableMemtable);
mutableMemtable = new Memtable(MEMTABLE_MAX_SIZE);
}
}

public Item get(byte[] key) {
Item result;

if ((result = mutableMemtable.get(key)) != null)
return result;

for (Memtable memtable : immutableMemtables)
if ((result = memtable.get(key)) != null)
return result;

for (SSTable table : tables)
if ((result = table.get(key)) != null)
return result;

return null;
}
}

0 comments on commit 281f87d

Please sign in to comment.