@NotThreadSafe public class SharedObjectsExtension extends Object implements org.junit.jupiter.api.extension.BeforeEachCallback, org.junit.jupiter.api.extension.AfterEachCallback
SharedReference
s. Usage:
@RegisterExtension
public final SharedObjectsExtension sharedObjects = SharedObjectsExtension.create();
@Test
public void test() throws Exception {
StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
SharedReference<Queue<Long>> listRef = sharedObjects.add(new ConcurrentLinkedQueue<>());
int n = 10000;
env.setParallelism(100);
env.fromSequence(0, n).map(i -> listRef.get().add(i));
env.execute();
assertEquals(n + 1, listRef.get().size());
assertEquals(
LongStream.rangeClosed(0, n).boxed().collect(Collectors.toList()),
listRef.get().stream().sorted().collect(Collectors.toList()));
}
The main idea is that shared objects are bound to the scope of a test case instead of a class. That allows us to:
Note that since the shared objects are accessed through multiple threads, they need to be thread-safe or accessed in a thread-safe manner.
Modifier and Type | Method and Description |
---|---|
<T> SharedReference<T> |
add(T object)
Adds a new object to this
SharedObjects . |
void |
afterEach(org.junit.jupiter.api.extension.ExtensionContext context) |
void |
beforeEach(org.junit.jupiter.api.extension.ExtensionContext context) |
static SharedObjectsExtension |
create()
Creates a new instance.
|
boolean |
equals(Object o) |
int |
hashCode() |
public static SharedObjectsExtension create()
Rule
.public <T> SharedReference<T> add(T object)
SharedObjects
. Although not necessary, it is recommended to
only access the object through the returned SharedReference
.public void beforeEach(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception
beforeEach
in interface org.junit.jupiter.api.extension.BeforeEachCallback
Exception
public void afterEach(org.junit.jupiter.api.extension.ExtensionContext context) throws Exception
afterEach
in interface org.junit.jupiter.api.extension.AfterEachCallback
Exception
Copyright © 2014–2024 The Apache Software Foundation. All rights reserved.