use of java.util.function.Supplier in project javaslang by javaslang.
the class Lazy method val.
/**
* Creates a real _lazy value_ of type {@code T}, backed by a {@linkplain java.lang.reflect.Proxy} which delegates
* to a {@code Lazy} instance.
*
* @param supplier A supplier
* @param type An interface
* @param <T> type of the lazy value
* @return A new instance of T
*/
@GwtIncompatible("reflection is not supported")
@SuppressWarnings("unchecked")
public static <T> T val(Supplier<? extends T> supplier, Class<T> type) {
Objects.requireNonNull(supplier, "supplier is null");
Objects.requireNonNull(type, "type is null");
if (!type.isInterface()) {
throw new IllegalArgumentException("type has to be an interface");
}
final Lazy<T> lazy = Lazy.of(supplier);
final InvocationHandler handler = (proxy, method, args) -> method.invoke(lazy.get(), args);
return (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[] { type }, handler);
}
use of java.util.function.Supplier in project neo4j by neo4j.
the class StoreStatementTest method shouldCloseOpenedLabelScanReader.
@Test
public void shouldCloseOpenedLabelScanReader() throws Exception {
// given
Supplier<LabelScanReader> scanStore = mock(Supplier.class);
LabelScanReader scanReader = mock(LabelScanReader.class);
when(scanStore.get()).thenReturn(scanReader);
StoreStatement statement = new StoreStatement(MockedNeoStores.basicMockedNeoStores(), mock(Supplier.class), scanStore, LockService.NO_LOCK_SERVICE);
statement.acquire();
// when
LabelScanReader actualReader = statement.getLabelScanReader();
// then
assertEquals(scanReader, actualReader);
// when
statement.close();
// then
verify(scanStore).get();
verifyNoMoreInteractions(scanStore);
verify(scanReader).close();
verifyNoMoreInteractions(scanReader);
}
use of java.util.function.Supplier in project neo4j by neo4j.
the class DelayedBufferTest method shouldHandleTheWholeWorkloadShebang.
@Test
public void shouldHandleTheWholeWorkloadShebang() throws Throwable {
// GIVEN
final int size = 1_000;
final long bufferTime = 3;
VerifyingConsumer consumer = new VerifyingConsumer(size);
final Clock clock = Clocks.systemClock();
Supplier<Long> chunkThreshold = clock::millis;
Predicate<Long> safeThreshold = time -> clock.millis() - bufferTime >= time;
final DelayedBuffer<Long> buffer = new DelayedBuffer<>(chunkThreshold, safeThreshold, 10, consumer);
MaintenanceThread maintenance = new MaintenanceThread(buffer, 5);
Race adders = new Race();
final int numberOfAdders = 20;
final byte[] offeredIds = new byte[size];
for (int i = 0; i < numberOfAdders; i++) {
final int finalI = i;
adders.addContestant(new Runnable() {
@Override
public void run() {
for (int j = 0; j < size; j++) {
if (j % numberOfAdders == finalI) {
buffer.offer(j);
offeredIds[j] = 1;
parkNanos(MILLISECONDS.toNanos(current().nextInt(2)));
}
}
}
});
}
// WHEN (multi-threadded) offering of ids
adders.go();
// ... ensuring the test is sane itself (did we really offer all these IDs?)
for (int i = 0; i < size; i++) {
assertEquals("ID " + i, (byte) 1, offeredIds[i]);
}
maintenance.halt();
buffer.close();
// THEN
consumer.assertHaveOnlySeenRange(0, size - 1);
}
use of java.util.function.Supplier in project neo4j by neo4j.
the class GraphDatabaseFacadeFactoryTest method newFaultyGraphDatabaseFacadeFactory.
private GraphDatabaseFacadeFactory newFaultyGraphDatabaseFacadeFactory(final RuntimeException startupError) {
return new GraphDatabaseFacadeFactory(DatabaseInfo.UNKNOWN, (p) -> Mockito.mock(EditionModule.class, Mockito.RETURNS_DEEP_STUBS)) {
@Override
protected PlatformModule createPlatform(File storeDir, Config config, Dependencies dependencies, GraphDatabaseFacade graphDatabaseFacade) {
final LifeSupport lifeMock = mock(LifeSupport.class);
doThrow(startupError).when(lifeMock).start();
doAnswer(invocation -> invocation.getArguments()[0]).when(lifeMock).add(any(Lifecycle.class));
return new PlatformModule(storeDir, config, databaseInfo, dependencies, graphDatabaseFacade) {
@Override
public LifeSupport createLife() {
return lifeMock;
}
};
}
@Override
protected DataSourceModule createDataSource(PlatformModule platformModule, EditionModule editionModule, Supplier<QueryExecutionEngine> queryExecutionEngineSupplier) {
return mock(DataSourceModule.class);
}
};
}
use of java.util.function.Supplier in project neo4j by neo4j.
the class ConstraintIndexConcurrencyTest method shouldNotAllowConcurrentViolationOfConstraint.
@Test
public void shouldNotAllowConcurrentViolationOfConstraint() throws Exception {
// Given
GraphDatabaseAPI graphDb = db.getGraphDatabaseAPI();
Supplier<Statement> statementSupplier = graphDb.getDependencyResolver().resolveDependency(ThreadToStatementContextBridge.class);
Label label = label("Foo");
String propertyKey = "bar";
String conflictingValue = "baz";
// a constraint
try (Transaction tx = graphDb.beginTx()) {
graphDb.schema().constraintFor(label).assertPropertyIsUnique(propertyKey).create();
tx.success();
}
// When
try (Transaction tx = graphDb.beginTx()) {
// create a statement and perform a lookup
Statement statement = statementSupplier.get();
int labelId = statement.readOperations().labelGetForName(label.name());
int propertyKeyId = statement.readOperations().propertyKeyGetForName(propertyKey);
NewIndexDescriptor index = NewIndexDescriptorFactory.uniqueForLabel(labelId, propertyKeyId);
statement.readOperations().indexQuery(index, IndexQuery.exact(index.schema().getPropertyId(), "The value is irrelevant, we just want to perform some sort of lookup against this index"));
// then let another thread come in and create a node
threads.execute(db -> {
try (Transaction transaction = db.beginTx()) {
db.createNode(label).setProperty(propertyKey, conflictingValue);
transaction.success();
}
return null;
}, graphDb).get();
// before we create a node with the same property ourselves - using the same statement that we have
// already used for lookup against that very same index
long node = statement.dataWriteOperations().nodeCreate();
statement.dataWriteOperations().nodeAddLabel(node, labelId);
try {
statement.dataWriteOperations().nodeSetProperty(node, property(propertyKeyId, conflictingValue));
fail("exception expected");
}// Then
catch (UniquePropertyValueValidationException e) {
assertEquals(ConstraintDescriptorFactory.uniqueForLabel(labelId, propertyKeyId), e.constraint());
IndexEntryConflictException conflict = Iterators.single(e.conflicts().iterator());
assertEquals(conflictingValue, conflict.getSinglePropertyValue());
}
tx.success();
}
}
Aggregations