Skip to content
Permalink
Browse files
storage: cache deserialized values in FileStorage
Reviewed-by: rwestberg
  • Loading branch information
edvbld committed Jun 12, 2020
1 parent e4fbefa commit 74c4eda7b177c8c8440ee57d8801c35726f1e463
Showing with 54 additions and 1 deletion.
  1. +7 −1 storage/src/main/java/org/openjdk/skara/storage/FileStorage.java
  2. +47 −0 storage/src/test/java/org/openjdk/skara/storage/FileStorageTests.java
@@ -29,7 +29,9 @@

class FileStorage<T> implements Storage<T> {
private final Path file;
private String old;
private String current;
private Set<T> deserialized;
private StorageSerializer<T> serializer;
private StorageDeserializer<T> deserializer;

@@ -48,7 +50,11 @@ public Set<T> current() {
current = "";
}
}
return Collections.unmodifiableSet(deserializer.deserialize(current));
if (old != current) {
deserialized = Collections.unmodifiableSet(deserializer.deserialize(current));
old = current;
}
return deserialized;
}

@Override
@@ -79,4 +79,51 @@ void retained() throws IOException {

Files.delete(tmpFile);
}

private static class CountingDeserializer implements StorageDeserializer<String> {
private int counter = 0;

CountingDeserializer() {
}

int counter() {
return counter;
}

@Override
public Set<String> deserialize(String serialized) {
counter++;
return Arrays.stream(serialized.split(";"))
.filter(str -> !str.isEmpty())
.collect(Collectors.toSet());
}
}

@Test
void cached() throws IOException {
var tmpFile = Files.createTempFile("filestorage", ".txt");
var deserializer = new CountingDeserializer();
var storage = new FileStorage<String>(tmpFile,
(added, cur) -> Stream.concat(cur.stream(), added.stream())
.sorted()
.collect(Collectors.joining(";")),
deserializer);
assertEquals(Set.of(), storage.current());
assertEquals(1, deserializer.counter());

// Another call to current() should not cause deseralization
storage.current();
assertEquals(1, deserializer.counter());

// Updated content should cause deseralization
storage.put("hello there");
assertEquals(Set.of("hello there"), storage.current());
assertEquals(2, deserializer.counter());

// Another call to current() should not cause deseralization
assertEquals(Set.of("hello there"), storage.current());
assertEquals(2, deserializer.counter());

Files.delete(tmpFile);
}
}

0 comments on commit 74c4eda

Please sign in to comment.