File tree Expand file tree Collapse file tree 4 files changed +57
-0
lines changed
core/src/main/java/de/bethibande/serial Expand file tree Collapse file tree 4 files changed +57
-0
lines changed Original file line number Diff line number Diff line change 11package de .bethibande .serial ;
22
3+ import de .bethibande .serial .allocation .ObjectAllocator ;
4+
35public interface Deserializer <T > {
46
57 boolean isBound ();
68
79 Deserializer <T > bind (final Reader reader );
810
11+ Deserializer <T > withAllocator (final ObjectAllocator <T > allocator );
12+
13+ ObjectAllocator <T > allocator ();
14+
15+ default T read () {
16+ return read (allocator ().allocate ());
17+ }
18+
919 T read (final T target );
1020
1121}
Original file line number Diff line number Diff line change 1+ package de .bethibande .serial .allocation ;
2+
3+ @ FunctionalInterface
4+ public interface ObjectAllocator <T > {
5+
6+ static <T > ObjectAllocator <T > ofStaticValue (final T instance ) {
7+ return () -> instance ;
8+ }
9+
10+ T allocate ();
11+
12+ }
Original file line number Diff line number Diff line change 1+ package de .bethibande .serial .allocation ;
2+
3+ /**
4+ * A thread-safe object allocator implementation that uses {@link ThreadLocal} to provide
5+ * a unique instance of the allocated object per thread.
6+ *
7+ * @param <T> the type of object to be allocated
8+ */
9+ public class ThreadLocalObjectAllocator <T > implements ObjectAllocator <T > {
10+
11+ private final ThreadLocal <T > holder ;
12+
13+ public ThreadLocalObjectAllocator (final ObjectAllocator <T > allocator ) {
14+ this .holder = ThreadLocal .withInitial (allocator ::allocate );
15+ }
16+
17+ @ Override
18+ public T allocate () {
19+ return holder .get ();
20+ }
21+
22+ }
Original file line number Diff line number Diff line change 22
33import de .bethibande .serial .Deserializer ;
44import de .bethibande .serial .Reader ;
5+ import de .bethibande .serial .allocation .ObjectAllocator ;
56
67public abstract class AbstractDeserializer <T > implements Deserializer <T > {
78
89 protected Reader reader ;
10+ protected ObjectAllocator <T > allocator ;
911
1012 @ Override
1113 public boolean isBound () {
@@ -17,4 +19,15 @@ public Deserializer<T> bind(final Reader reader) {
1719 this .reader = reader ;
1820 return this ;
1921 }
22+
23+ @ Override
24+ public Deserializer <T > withAllocator (final ObjectAllocator <T > allocator ) {
25+ this .allocator = allocator ;
26+ return this ;
27+ }
28+
29+ @ Override
30+ public ObjectAllocator <T > allocator () {
31+ return allocator ;
32+ }
2033}
You can’t perform that action at this time.
0 commit comments