Search in sources :

Example 11 with Barrier

use of org.neo4j.test.Barrier in project neo4j by neo4j.

the class GraphDatabaseServiceTest method givenDatabaseAndStartedTxWhenShutdownThenWaitForTxToFinish.

@Test
public void givenDatabaseAndStartedTxWhenShutdownThenWaitForTxToFinish() throws Exception {
    // Given
    final GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
    // When
    Barrier.Control barrier = new Barrier.Control();
    Future<Object> txFuture = t2.execute(state -> {
        try (Transaction tx = db.beginTx()) {
            barrier.reached();
            db.createNode();
            tx.success();
        }
        return null;
    });
    // i.e. wait for transaction to start
    barrier.await();
    // now there's a transaction open, blocked on continueTxSignal
    Future<Object> shutdownFuture = t3.execute(state -> {
        db.shutdown();
        return null;
    });
    t3.get().waitUntilWaiting(location -> location.isAt(DatabaseAvailability.class, "stop"));
    barrier.release();
    try {
        txFuture.get();
    } catch (ExecutionException e) {
    // expected
    }
    shutdownFuture.get();
}
Also used : TestGraphDatabaseFactory(org.neo4j.test.TestGraphDatabaseFactory) Barrier(org.neo4j.test.Barrier) DatabaseAvailability(org.neo4j.kernel.DatabaseAvailability) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 12 with Barrier

use of org.neo4j.test.Barrier in project neo4j by neo4j.

the class GraphDatabaseServiceTest method givenDatabaseAndStartedTxWhenShutdownAndStartNewTxThenBeginTxTimesOut.

@Test
public void givenDatabaseAndStartedTxWhenShutdownAndStartNewTxThenBeginTxTimesOut() throws Exception {
    // Given
    GraphDatabaseService db = new TestGraphDatabaseFactory().newImpermanentDatabase();
    // When
    Barrier.Control barrier = new Barrier.Control();
    t2.execute(state -> {
        try (Transaction tx = db.beginTx()) {
            barrier.reached();
        }
        return null;
    });
    barrier.await();
    Future<Object> shutdownFuture = t3.execute(state -> {
        db.shutdown();
        return null;
    });
    t3.get().waitUntilWaiting(location -> location.isAt(DatabaseAvailability.class, "stop"));
    // <-- this triggers t2 to continue its transaction
    barrier.release();
    shutdownFuture.get();
    try {
        db.beginTx();
        fail("Should fail");
    } catch (DatabaseShutdownException e) {
    //THEN good
    }
}
Also used : TestGraphDatabaseFactory(org.neo4j.test.TestGraphDatabaseFactory) Barrier(org.neo4j.test.Barrier) DatabaseAvailability(org.neo4j.kernel.DatabaseAvailability) Test(org.junit.Test)

Example 13 with Barrier

use of org.neo4j.test.Barrier in project neo4j by neo4j.

the class RelationshipCountsTest method shouldNotCountRelationshipsCreatedInOtherTransaction.

@Test
public void shouldNotCountRelationshipsCreatedInOtherTransaction() throws Exception {
    // given
    GraphDatabaseService graphDb = db.getGraphDatabaseAPI();
    final Barrier.Control barrier = new Barrier.Control();
    long before = numberOfRelationships();
    Future<Long> tx = threading.execute(new NamedFunction<GraphDatabaseService, Long>("create-relationships") {

        @Override
        public Long apply(GraphDatabaseService graphDb) {
            try (Transaction tx = graphDb.beginTx()) {
                Node node = graphDb.createNode();
                node.createRelationshipTo(graphDb.createNode(), withName("KNOWS"));
                node.createRelationshipTo(graphDb.createNode(), withName("KNOWS"));
                long whatThisThreadSees = countsForRelationship(null, null, null);
                barrier.reached();
                tx.success();
                return whatThisThreadSees;
            }
        }
    }, graphDb);
    barrier.await();
    // when
    long during = numberOfRelationships();
    barrier.release();
    long whatOtherThreadSees = tx.get();
    long after = numberOfRelationships();
    // then
    assertEquals(0, before);
    assertEquals(0, during);
    assertEquals(2, after);
    assertEquals(after, whatOtherThreadSees);
}
Also used : GraphDatabaseService(org.neo4j.graphdb.GraphDatabaseService) Transaction(org.neo4j.graphdb.Transaction) Node(org.neo4j.graphdb.Node) Barrier(org.neo4j.test.Barrier) Test(org.junit.Test)

Example 14 with Barrier

use of org.neo4j.test.Barrier in project neo4j by neo4j.

the class CountsTrackerTest method shouldBeAbleToReadUpToDateValueWhileAnotherThreadIsPerformingRotation.

@Test
public void shouldBeAbleToReadUpToDateValueWhileAnotherThreadIsPerformingRotation() throws Exception {
    // given
    CountsOracle oracle = someData();
    final int firstTransaction = 2, secondTransaction = 3;
    try (Lifespan life = new Lifespan()) {
        CountsTracker tracker = life.add(newTracker());
        oracle.update(tracker, firstTransaction);
        tracker.rotate(firstTransaction);
    }
    // when
    final CountsOracle delta = new CountsOracle();
    {
        CountsOracle.Node n1 = delta.node(1);
        // Label 4 has not been used before...
        CountsOracle.Node n2 = delta.node(1, 4);
        delta.relationship(n1, 1, n2);
        // relationshipType 2 has not been used before...
        delta.relationship(n2, 2, n1);
    }
    delta.update(oracle);
    try (Lifespan life = new Lifespan()) {
        final Barrier.Control barrier = new Barrier.Control();
        CountsTracker tracker = life.add(new CountsTracker(resourceManager.logProvider(), resourceManager.fileSystem(), resourceManager.pageCache(), Config.empty(), resourceManager.testPath()) {

            @Override
            protected boolean include(CountsKey countsKey, ReadableBuffer value) {
                barrier.reached();
                return super.include(countsKey, value);
            }
        });
        Future<Void> task = threading.execute((ThrowingFunction<CountsTracker, Void, RuntimeException>) t -> {
            try {
                delta.update(t, secondTransaction);
                t.rotate(secondTransaction);
            } catch (IOException e) {
                throw new AssertionError(e);
            }
            return null;
        }, tracker);
        // then
        barrier.await();
        oracle.verify(tracker);
        barrier.release();
        task.get();
        oracle.verify(tracker);
    }
}
Also used : CountsKey(org.neo4j.kernel.impl.store.counts.keys.CountsKey) Registers(org.neo4j.register.Registers) Assert.assertSame(org.junit.Assert.assertSame) Future(java.util.concurrent.Future) FakeClock(org.neo4j.time.FakeClock) CountsVisitor(org.neo4j.kernel.impl.api.CountsVisitor) Mockito.verifyNoMoreInteractions(org.mockito.Mockito.verifyNoMoreInteractions) CountsKeyFactory(org.neo4j.kernel.impl.store.counts.keys.CountsKeyFactory) DebugUtil.classNameContains(org.neo4j.kernel.impl.util.DebugUtil.classNameContains) Assert.fail(org.junit.Assert.fail) ReadableBuffer(org.neo4j.kernel.impl.store.kvstore.ReadableBuffer) STARTED(org.neo4j.test.rule.Resources.InitialLifecycle.STARTED) Config(org.neo4j.kernel.configuration.Config) CountsOracle(org.neo4j.kernel.impl.store.CountsOracle) Barrier(org.neo4j.test.Barrier) Lifespan(org.neo4j.kernel.lifecycle.Lifespan) Predicate(java.util.function.Predicate) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Register(org.neo4j.register.Register) IOFunction(org.neo4j.function.IOFunction) ThrowingFunction(org.neo4j.function.ThrowingFunction) File(java.io.File) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) DataInitializer(org.neo4j.kernel.impl.store.kvstore.DataInitializer) FILE_IN_EXISTING_DIRECTORY(org.neo4j.test.rule.Resources.TestPath.FILE_IN_EXISTING_DIRECTORY) DebugUtil.stackTraceContains(org.neo4j.kernel.impl.util.DebugUtil.stackTraceContains) RotationTimeoutException(org.neo4j.kernel.impl.store.kvstore.RotationTimeoutException) Rule(org.junit.Rule) CountsAccessor(org.neo4j.kernel.impl.api.CountsAccessor) Resources(org.neo4j.test.rule.Resources) ThreadingRule(org.neo4j.test.rule.concurrent.ThreadingRule) Clock(java.time.Clock) DebugUtil.methodIs(org.neo4j.kernel.impl.util.DebugUtil.methodIs) GraphDatabaseSettings(org.neo4j.graphdb.factory.GraphDatabaseSettings) Clocks(org.neo4j.time.Clocks) Assert.assertEquals(org.junit.Assert.assertEquals) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Predicates.all(org.neo4j.function.Predicates.all) Mockito.mock(org.mockito.Mockito.mock) Barrier(org.neo4j.test.Barrier) CountsKey(org.neo4j.kernel.impl.store.counts.keys.CountsKey) IOException(java.io.IOException) ReadableBuffer(org.neo4j.kernel.impl.store.kvstore.ReadableBuffer) CountsOracle(org.neo4j.kernel.impl.store.CountsOracle) Lifespan(org.neo4j.kernel.lifecycle.Lifespan) Test(org.junit.Test)

Example 15 with Barrier

use of org.neo4j.test.Barrier in project neo4j by neo4j.

the class StoreCopyCheckPointMutexTest method shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests.

@Test
public void shouldPropagateStoreCopyActionFailureToOtherStoreCopyRequests() throws Exception {
    // GIVEN
    Barrier.Control barrier = new Barrier.Control();
    IOException controlledFailure = new IOException("My own fault");
    AtomicReference<Future<Object>> secondRequest = new AtomicReference<>();
    ThrowingAction<IOException> controllableAndFailingAction = new ThrowingAction<IOException>() {

        @Override
        public void apply() throws IOException {
            // Now that we know we're first, start the second request...
            secondRequest.set(t3.execute(state -> mutex.storeCopy(ASSERT_NOT_CALLED)));
            // ...and wait for it to reach its destination
            barrier.awaitUninterruptibly();
            try {
                // OK, second request has made progress into the request, so we can now produce our failure
                throw controlledFailure;
            } finally {
                barrier.release();
            }
        }
    };
    Future<Object> firstRequest = t2.execute(state -> mutex.storeCopy(controllableAndFailingAction));
    while (secondRequest.get() == null) {
        parkARandomWhile();
    }
    t3.get().waitUntilWaiting(details -> details.isAt(StoreCopyCheckPointMutex.class, "waitForFirstStoreCopyActionToComplete"));
    // WHEN
    barrier.reached();
    // THEN
    try {
        firstRequest.get();
    } catch (ExecutionException e) {
        assertSame(controlledFailure, e.getCause());
    }
    try {
        secondRequest.get().get();
    } catch (ExecutionException e) {
        Throwable cooperativeActionFailure = e.getCause();
        assertThat(cooperativeActionFailure.getMessage(), containsString("Co-operative"));
        assertSame(controlledFailure, cooperativeActionFailure.getCause());
    }
    // WHEN afterwards trying another store-copy
    CountingAction action = new CountingAction();
    try (Resource lock = mutex.storeCopy(action)) {
        // THEN
        assertEquals(1, action.count());
    }
}
Also used : ThrowingAction(org.neo4j.function.ThrowingAction) Resource(org.neo4j.graphdb.Resource) OtherThreadRule(org.neo4j.test.rule.concurrent.OtherThreadRule) AtomicReference(java.util.concurrent.atomic.AtomicReference) Assert.assertSame(org.junit.Assert.assertSame) Assert.assertThat(org.junit.Assert.assertThat) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Matchers.lessThan(org.hamcrest.Matchers.lessThan) ThrowingAction(org.neo4j.function.ThrowingAction) Assert.fail(org.junit.Assert.fail) Barrier(org.neo4j.test.Barrier) Assert.assertNotNull(org.junit.Assert.assertNotNull) Test(org.junit.Test) IOException(java.io.IOException) Mockito.times(org.mockito.Mockito.times) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) Mockito.verify(org.mockito.Mockito.verify) ExecutionException(java.util.concurrent.ExecutionException) LockSupport(java.util.concurrent.locks.LockSupport) Rule(org.junit.Rule) Assert.assertNull(org.junit.Assert.assertNull) Race.throwing(org.neo4j.test.Race.throwing) Matchers.containsString(org.hamcrest.Matchers.containsString) Race(org.neo4j.test.Race) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) Resource(org.neo4j.graphdb.Resource) Barrier(org.neo4j.test.Barrier) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) Future(java.util.concurrent.Future) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Aggregations

Test (org.junit.Test)15 Barrier (org.neo4j.test.Barrier)15 Transaction (org.neo4j.graphdb.Transaction)7 Node (org.neo4j.graphdb.Node)6 ExecutionException (java.util.concurrent.ExecutionException)3 Server (org.eclipse.jetty.server.Server)3 NotFoundException (org.neo4j.graphdb.NotFoundException)3 TransactionFailureException (org.neo4j.graphdb.TransactionFailureException)3 InvalidRecordException (org.neo4j.kernel.impl.store.InvalidRecordException)3 File (java.io.File)2 IOException (java.io.IOException)2 Collections.emptyMap (java.util.Collections.emptyMap)2 Map (java.util.Map)2 Future (java.util.concurrent.Future)2 MILLISECONDS (java.util.concurrent.TimeUnit.MILLISECONDS)2 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)2 Assert.assertEquals (org.junit.Assert.assertEquals)2 Assert.assertSame (org.junit.Assert.assertSame)2 Assert.fail (org.junit.Assert.fail)2 Rule (org.junit.Rule)2