Skip to content

Instantly share code, notes, and snippets.

@micheljung
Last active April 5, 2020 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save micheljung/7589992f11d503ca92871f68c7d50c2e to your computer and use it in GitHub Desktop.
Save micheljung/7589992f11d503ca92871f68c7d50c2e to your computer and use it in GitHub Desktop.
Demonstrates that a default KeyValueTemplate with a standard MapKeyValueAdapter is not thread safe
import org.junit.Assert;
import org.junit.Test;
import org.springframework.data.annotation.Id;
import org.springframework.data.keyvalue.annotation.KeySpace;
import org.springframework.data.keyvalue.core.KeyValueTemplate;
import org.springframework.data.map.MapKeyValueAdapter;
import java.util.LinkedList;
import java.util.concurrent.CompletableFuture;
import static org.hamcrest.CoreMatchers.is;
public class KeyValueThreadSafety {
@Test
public void test() {
KeyValueTemplate template = new KeyValueTemplate(new MapKeyValueAdapter());
LinkedList<CompletableFuture<Void>> futures = new LinkedList<>();
for (int index = 0; index < 10; index++) {
TestEntity entity = new TestEntity(String.valueOf(index));
futures.add(CompletableFuture.runAsync(() -> template.insert(entity)));
}
futures.forEach(CompletableFuture::join);
Assert.assertThat(template.count(TestEntity.class), is(10L));
}
@KeySpace("test")
public static class TestEntity {
@Id
final String value;
public TestEntity(String value) {
this.value = value;
}
}
}
java.lang.AssertionError:
Expected: is <10L>
but: was <3L>
Expected :is <10L>
Actual :<3L>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment