Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

storage: cache deserialized values in FileStorage #656

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -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);
}
}