Skip to content

Commit 00e86e3

Browse files
committed
Add Object allocators #3
1 parent ce59cf8 commit 00e86e3

File tree

4 files changed

+57
-0
lines changed

4 files changed

+57
-0
lines changed
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,21 @@
11
package de.bethibande.serial;
22

3+
import de.bethibande.serial.allocation.ObjectAllocator;
4+
35
public 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
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
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+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
}

core/src/main/java/de/bethibande/serial/impl/AbstractDeserializer.java

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,12 @@
22

33
import de.bethibande.serial.Deserializer;
44
import de.bethibande.serial.Reader;
5+
import de.bethibande.serial.allocation.ObjectAllocator;
56

67
public 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
}

0 commit comments

Comments
 (0)