        @Override
        public void setState( ObjectInputStream input ) throws IOException, ClassNotFoundException
        {
            clusterMembersSnapshot = ClusterMembersSnapshot.class.cast( input.readObject() );

            if ( !snapshotValidator.test( clusterMembersSnapshot ) )
            {
                executor.submit( () -> cluster.leave() );
            }
            else
            {
                // Send current availability events to listeners
                listeners.notify( executor, listener -> {
                    for ( MemberIsAvailable memberIsAvailable : clusterMembersSnapshot.getCurrentAvailableMembers() )
                    {
                        listener.memberIsAvailable( memberIsAvailable.getRole(), memberIsAvailable.getInstanceId(),
                                memberIsAvailable.getRoleUri(), memberIsAvailable.getStoreId() );
                    }
                } );
            }
        }

        @Override
        public void setState( ObjectInputStream input ) throws IOException, ClassNotFoundException
        {
            clusterMembersSnapshot = ClusterMembersSnapshot.class.cast( input.readObject() );

            if ( !snapshotValidator.test( clusterMembersSnapshot ) )
            {
                executor.submit( (Runnable) () -> cluster.leave() );
            }
            else
            {
                // Send current availability events to listeners
                Listeners.notifyListeners( listeners, executor, new Listeners.Notification<ClusterMemberListener>()
                {
                    @Override
                    public void notify( ClusterMemberListener listener )
                    {
                        for ( MemberIsAvailable memberIsAvailable : clusterMembersSnapshot.getCurrentAvailableMembers() )
                        {
                            listener.memberIsAvailable( memberIsAvailable.getRole(), memberIsAvailable.getInstanceId(),
                                    memberIsAvailable.getRoleUri(), memberIsAvailable.getStoreId() );
                        }
                    }
                } );
            }
        }

Replace Anonymous With Lambda org.neo4j.cluster.member.paxos.PaxosClusterMemberEvents.HighAvailabilitySnapshotProvider.setState.notifyListeners.new Listeners.Notification<ClusterMemberListener> with listener -> {for(MemberIsAvailable memberIsAvailable: clusterMembersSnapshot.getCurrentAvailableMembers()){listener.memberIsAvailable(memberIsAvailable.getRole(),memberIsAvailable.getInstanceId(),memberIsAvailable.getRoleUri(),memberIsAvailable.getStoreId()); in method public setState(input ObjectInputStream) : void from class org.neo4j.cluster.member.paxos.PaxosClusterMemberEvents.HighAvailabilitySnapshotProvider


    private IOCursor<LogEntry> mockCursor( final LogEntry... entries )
    {
        return new ArrayIOCursor<>( entries );
    }

    private IOCursor<LogEntry> mockCursor( final LogEntry... entries )
    {
        return new IOCursor<LogEntry>()
        {
            private int pos = 0;

            @Override
            public LogEntry get()
            {
                return entries[pos++];
            }

            @Override
            public boolean next() throws IOException
            {
                return pos < entries.length;
            }

            @Override
            public void close() throws IOException
            {// nothing to do
            }
        };
    }

Replace Generic With Diamond IOCursor<LogEntry> with ArrayIOCursor<> in method private mockCursor(entries LogEntry...) : IOCursor<LogEntry> from class org.neo4j.kernel.impl.storemigration.legacylogs.LegacyLogEntryWriterTest


    @Override
    public void beginTry( final Resource... resources )
    {
        if ( resources.length > 0 && classSourceWriter.configuration.isSet( SourceCode.SIMPLIFY_TRY_WITH_RESOURCE ) )
        {
            for ( Resource resource : resources )
            {
                indent().append( resource.type().name() ).append( " " ).append( resource.name() ).append( " = " );
                resource.producer().accept( this );
                append( ";\n" );
            }
            indent().append( "try\n" );
            indent().append( "{" );
            level.push( () -> {
                beginFinally();
                for ( Resource resource : resources )
                {
                    indent().append( resource.name() ).append( ".close();\n" );
                }
                endBlock();
            } );
        }
        else
        {
            indent().append( "try" );
            if ( resources.length > 0 )
            {
                String sep = " ( ";
                for ( Resource resource : resources )
                {
                    append( sep ).append( resource.type().name() ).append( " " ).append( resource.name() )
                            .append( " = " );
                    resource.producer().accept( this );
                    sep = "; ";
                }
                append( " )" );
            }
            append( "\n" );
            indent().append( "{\n" );
            level.push( LEVEL );
        }
    }

    @Override
    public void beginTry( final Resource... resources )
    {
        if ( resources.length > 0 && classWriter.configuration.isSet( SourceCode.SIMPLIFY_TRY_WITH_RESOURCE ) )
        {
            for ( Resource resource : resources )
            {
                indent().append( resource.type().name() ).append( " " ).append( resource.name() ).append( " = " );
                resource.producer().accept( this );
                append( ";\n" );
            }
            indent().append( "try\n" );
            indent().append( "{" );
            level.push( new Runnable()
            {
                @Override
                public void run()
                {
                    beginFinally();
                    for ( Resource resource : resources )
                    {
                        indent().append( resource.name() ).append( ".close();\n" );
                    }
                    endBlock();
                }
            } );
        }
        else
        {
            indent().append( "try" );
            if ( resources.length > 0 )
            {
                String sep = " ( ";
                for ( Resource resource : resources )
                {
                    append( sep ).append( resource.type().name() ).append( " " ).append( resource.name() )
                            .append( " = " );
                    resource.producer().accept( this );
                    sep = "; ";
                }
                append( " )" );
            }
            append( "\n" );
            indent().append( "{\n" );
            level.push( LEVEL );
        }
    }

Replace Anonymous With Lambda org.neo4j.codegen.source.MethodWriter.beginTry.push.new Runnable with () -> {beginFinally(); in method public beginTry(resources Resource...) : void from class org.neo4j.codegen.source.MethodWriter


    @Before
    public void before() throws IOException
    {
        fs = fsr.get();
        pageCache = pageCacheRule.getPageCache( fsr.get() );
        try ( StoreChannel channel = fs.create( fileName ) )
        {
            ByteBuffer buffer = ByteBuffer.allocate( 4 );
            buffer.putInt( BLOCK_SIZE );
            buffer.flip();
            channel.write( buffer );
        }
    }

    @Before
    public void before() throws IOException
    {
        fs = fsr.get();
        pageCache = pageCacheRule.getPageCache( fsr.get() );
        StoreChannel channel = fs.create( fileName );
        try
        {
            ByteBuffer buffer = ByteBuffer.allocate( 4 );
            buffer.putInt( BLOCK_SIZE );
            buffer.flip();
            channel.write( buffer );
        }
        finally
        {
            channel.close();
        }
    }

Try With Resources try(StoreChannel channel=fs.create(fileName)) in method public before() : void from class org.neo4j.kernel.impl.store.AbstractDynamicStoreTest


    @BeforeClass
    public static void setupServer() throws Exception
    {
        clock = new FakeClock();
        server = CommunityServerBuilder.server()
                .usingDataDir( staticFolder.getRoot().getAbsolutePath() )
                .withClock( clock )
                .build();

        suppressAll().call( (Callable<Void>) () -> {
            server.start();
            return null;
        } );
        functionalTestHelper = new FunctionalTestHelper( server );
    }

    @BeforeClass
    public static void setupServer() throws Exception
    {
        clock = new FakeClock();
        server = CommunityServerBuilder.server()
                .usingDataDir( staticFolder.getRoot().getAbsolutePath() )
                .withClock( clock )
                .build();

        suppressAll().call( new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                server.start();
                return null;
            }
        } );
        functionalTestHelper = new FunctionalTestHelper( server );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.paging.PagedTraverserDocIT.setupServer.call.new Callable<Void> with () -> {server.start(); in method public setupServer() : void from class org.neo4j.server.rest.paging.PagedTraverserDocIT


    @AfterClass
    public static void stopServer() throws Exception
    {
        suppressAll().call( (Callable<Void>) () -> {
            server.stop();
            return null;
        } );
    }

    @AfterClass
    public static void stopServer() throws Exception
    {
        suppressAll().call( new Callable<Void>()
        {
            @Override
            public Void call() throws Exception
            {
                server.stop();
                return null;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.server.rest.paging.PagedTraverserDocIT.stopServer.call.new Callable<Void> with () -> {server.stop(); in method public stopServer() : void from class org.neo4j.server.rest.paging.PagedTraverserDocIT


    private static File[] relevantDbFiles( File storeDir )
    {
        if ( !storeDir.exists() )
        {
            return new File[0];
        }

        return storeDir.listFiles(file -> {
            for ( String directory : new String[] {"metrics", "logs", "certificates"} )
            {
                if ( file.getName().startsWith( directory ) )
                {
                    return false;
                }
            }
            return !isBranchedDataRootDirectory( file );
        });
    }

    private static File[] relevantDbFiles( File storeDir )
    {
        if ( !storeDir.exists() )
        {
            return new File[0];
        }

        return storeDir.listFiles( new FileFilter()
        {
            @Override
            public boolean accept( File file )
            {
                return !file.getName().startsWith( "metrics" ) && !file.getName().startsWith( "debug." ) &&
                       !isBranchedDataRootDirectory( file );
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.util.StoreUtil.relevantDbFiles.listFiles.new FileFilter with file -> {for(String directory: new String[]{"metrics","logs","certificates"}){if(file.getName().startsWith(directory)){return false; in method private relevantDbFiles(storeDir File) : File[] from class org.neo4j.kernel.impl.util.StoreUtil


    public static AwaitAnswer<Void> afterAwaiting( CountDownLatch latch )
    {
        return new AwaitAnswer<>( latch, null );
    }

    public static AwaitAnswer<Void> afterAwaiting( CountDownLatch latch )
    {
        return new AwaitAnswer<Void>( latch, null );
    }

Replace Generic With Diamond AwaitAnswer<Void> with AwaitAnswer<> in method public afterAwaiting(latch CountDownLatch) : AwaitAnswer<Void> from class org.neo4j.test.mockito.answer.AwaitAnswer


    public <R> Answer<R> then( Answer<R> result )
    {
        return new AwaitAnswer<>( latch, result );
    }

    public <R> Answer<R> then( Answer<R> result )
    {
        return new AwaitAnswer<R>( latch, result );
    }

Replace Generic With Diamond AwaitAnswer<R> with AwaitAnswer<> in method public then(result Answer<R>) : Answer<R> from class org.neo4j.test.mockito.answer.AwaitAnswer


    @Test
    public void clientShouldUseHandlersToHandleComExceptions()
    {
        // Given
        final String comExceptionMessage = "The ComException";

        MadeUpCommunicationInterface communication = mock( MadeUpCommunicationInterface.class,
                (Answer<Response<?>>) ingored -> {
                    throw new ComException( comExceptionMessage );
                } );

        ComExceptionHandler handler = mock( ComExceptionHandler.class );

        life.add( builder.server( communication ) );
        MadeUpClient client = life.add( builder.client() );
        client.setComExceptionHandler( handler );

        life.start();

        // When
        ComException exceptionThrownOnRequest = null;
        try
        {
            client.multiply( 1, 10 );
        }
        catch ( ComException e )
        {
            exceptionThrownOnRequest = e;
        }

        // Then
        assertNotNull( exceptionThrownOnRequest );
        assertEquals( comExceptionMessage, exceptionThrownOnRequest.getMessage() );

        ArgumentCaptor<ComException> exceptionCaptor = ArgumentCaptor.forClass( ComException.class );
        verify( handler ).handle( exceptionCaptor.capture() );
        assertEquals( comExceptionMessage, exceptionCaptor.getValue().getMessage() );
        verifyNoMoreInteractions( handler );
    }

    @Test
    public void clientShouldUseHandlersToHandleComExceptions()
    {
        // Given
        final String comExceptionMessage = "The ComException";

        MadeUpCommunicationInterface communication = mock( MadeUpCommunicationInterface.class, new Answer<Response<?>>()
        {
            @Override
            public Response<?> answer( InvocationOnMock _ ) throws ComException
            {
                throw new ComException( comExceptionMessage );
            }
        } );

        ComExceptionHandler handler = mock( ComExceptionHandler.class );

        life.add( builder.server( communication ) );
        MadeUpClient client = life.add( builder.client() );
        client.setComExceptionHandler( handler );

        life.start();

        // When
        ComException exceptionThrownOnRequest = null;
        try
        {
            client.multiply( 1, 10 );
        }
        catch ( ComException e )
        {
            exceptionThrownOnRequest = e;
        }

        // Then
        assertNotNull( exceptionThrownOnRequest );
        assertEquals( comExceptionMessage, exceptionThrownOnRequest.getMessage() );

        ArgumentCaptor<ComException> exceptionCaptor = ArgumentCaptor.forClass( ComException.class );
        verify( handler ).handle( exceptionCaptor.capture() );
        assertEquals( comExceptionMessage, exceptionCaptor.getValue().getMessage() );
        verifyNoMoreInteractions( handler );
    }

Replace Anonymous With Lambda org.neo4j.com.TestCommunication.clientShouldUseHandlersToHandleComExceptions.communication.mock.new Answer<Response<?>> with ingored -> {throw new ComException(comExceptionMessage); in method public clientShouldUseHandlersToHandleComExceptions() : void from class org.neo4j.com.TestCommunication


    protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator(
            final File storeDir, final GraphDatabaseFactoryState state )
    {
        return config -> {
            config.put( "unsupported.dbms.ephemeral", "false" );
            GraphDatabaseFacadeFactory.Dependencies dependencies = state.databaseDependencies();
            return GraphDatabaseFactory.this.newDatabase( storeDir, config, dependencies );
        };
    }

    protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator(
            final File storeDir, final GraphDatabaseFactoryState state )
    {
        return new GraphDatabaseBuilder.DatabaseCreator()
        {
            @Override
            public GraphDatabaseService newDatabase( Map<String,String> config )
            {
                config.put( "unsupported.dbms.ephemeral", "false" );
                GraphDatabaseFacadeFactory.Dependencies dependencies = state.databaseDependencies();
                return GraphDatabaseFactory.this.newDatabase( storeDir, config, dependencies );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.factory.GraphDatabaseFactory.createDatabaseCreator.new GraphDatabaseBuilder.DatabaseCreator with config -> {config.put("unsupported.dbms.ephemeral","false"); in method protected createDatabaseCreator(storeDir File, state GraphDatabaseFactoryState) : GraphDatabaseBuilder.DatabaseCreator from class org.neo4j.graphdb.factory.GraphDatabaseFactory


    @Override
    protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator(
            final File storeDir, final GraphDatabaseFactoryState state )
    {
        return config -> {
            config.put( "unsupported.dbms.ephemeral", "false" );
            return new HighlyAvailableGraphDatabase( storeDir, config, state.databaseDependencies() );
        };
    }

    @Override
    protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator(
            final File storeDir, final GraphDatabaseFactoryState state )
    {
        return new GraphDatabaseBuilder.DatabaseCreator()
        {
            @Override
            public GraphDatabaseService newDatabase( final Map<String, String> config )
            {
                config.put( "unsupported.dbms.ephemeral", "false" );
                return new HighlyAvailableGraphDatabase( storeDir, config, state.databaseDependencies() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory.createDatabaseCreator.new GraphDatabaseBuilder.DatabaseCreator with config -> {config.put("unsupported.dbms.ephemeral","false"); in method protected createDatabaseCreator(storeDir File, state GraphDatabaseFactoryState) : GraphDatabaseBuilder.DatabaseCreator from class org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory


    @Before
    public void setup()
    {
        KernelExtensionFactory<?> testExtension = new LuceneLabelScanStoreExtension( 100, monitor );
        TestHighlyAvailableGraphDatabaseFactory factory = new TestHighlyAvailableGraphDatabaseFactory();
        factory.addKernelExtensions( Arrays.<KernelExtensionFactory<?>>asList( testExtension ) );
        ClusterManager clusterManager = new ClusterManager.Builder( testDirectory.directory( "root" ) )
                .withDbFactory( factory )
                .withStoreDirInitializer( ( serverId, storeDir ) -> {
                    if ( serverId == 1 )
                    {
                        GraphDatabaseService db =
                                new TestGraphDatabaseFactory().newEmbeddedDatabase( storeDir.getAbsoluteFile() );
                        try
                        {
                            createSomeLabeledNodes( db,
                                    new Label[] {Labels.First},
                                    new Label[] {Labels.First, Labels.Second},
                                    new Label[] {Labels.Second} );
                        }
                        finally
                        {
                            db.shutdown();
                        }
                    }
                } ).build();
        life.add( clusterManager );
        life.start();
        cluster = clusterManager.getDefaultCluster();
        cluster.await( allSeesAllAsAvailable() );
        cluster.await( allAvailabilityGuardsReleased() );
    }

    @Before
    public void setup()
    {
        KernelExtensionFactory<?> testExtension = new LuceneLabelScanStoreExtension( 100, monitor );
        HighlyAvailableGraphDatabaseFactory factory = new TestHighlyAvailableGraphDatabaseFactory();
        factory.addKernelExtensions( Arrays.<KernelExtensionFactory<?>>asList( testExtension ) );
        ClusterManager clusterManager = new ClusterManager.Builder( testDirectory.directory( "root" ) )
                .withDbFactory( factory )
                .withStoreDirInitializer( new ClusterManager.StoreDirInitializer()
        {
            @Override
            public void initializeStoreDir( int serverId, File storeDir ) throws IOException
            {
                if ( serverId == 1 )
                {
                    GraphDatabaseService db = new TestGraphDatabaseFactory().newEmbeddedDatabase(
                            storeDir.getAbsolutePath() );
                    try
                    {
                        createSomeLabeledNodes( db,
                                new Label[] {Labels.First},
                                new Label[] {Labels.First, Labels.Second},
                                new Label[] {Labels.Second} );
                    }
                    finally
                    {
                        db.shutdown();
                    }
                }
            }
        } ).build();
        life.add( clusterManager );
        life.start();
        cluster = clusterManager.getDefaultCluster();
        cluster.await( allSeesAllAsAvailable() );
        cluster.await( allAvailabilityGuardsReleased() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.labelscan.LabelScanStoreHaIT.setup.clusterManager.build.withStoreDirInitializer.new ClusterManager.StoreDirInitializer with (serverId, storeDir) -> {if(serverId == 1){GraphDatabaseService db=new TestGraphDatabaseFactory().newEmbeddedDatabase(storeDir.getAbsoluteFile()); in method public setup() : void from class org.neo4j.kernel.api.impl.labelscan.LabelScanStoreHaIT


    @Override
    protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator( final File storeDir,
            final GraphDatabaseFactoryState state )
    {
        return config -> {
            config.put( "unsupported.dbms.ephemeral", "false" );
            return new EnterpriseGraphDatabase( storeDir, config, state.databaseDependencies() );
        };
    }

    @Override
    protected GraphDatabaseBuilder.DatabaseCreator createDatabaseCreator( final File storeDir,
            final GraphDatabaseFactoryState state )
    {
        return new GraphDatabaseBuilder.DatabaseCreator()
        {
            @Override
            public GraphDatabaseService newDatabase( Map<String,String> config )
            {
                config.put( "unsupported.dbms.ephemeral", "false" );

                return new EnterpriseGraphDatabase( storeDir, config, state.databaseDependencies() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.factory.EnterpriseGraphDatabaseFactory.createDatabaseCreator.new GraphDatabaseBuilder.DatabaseCreator with config -> {config.put("unsupported.dbms.ephemeral","false"); in method protected createDatabaseCreator(storeDir File, state GraphDatabaseFactoryState) : GraphDatabaseBuilder.DatabaseCreator from class org.neo4j.graphdb.factory.EnterpriseGraphDatabaseFactory


    private CountDownLatch loadThreadPool( QueuedThreadPool threadPool,
                                           int tasksToSubmit,
                                           final CountDownLatch startLatch )
    {
        CountDownLatch endLatch = new CountDownLatch( 1 );
        for ( int i = 0; i < tasksToSubmit; i++ )
        {
            threadPool.execute( () -> {
                startLatch.countDown();
                try
                {
                    endLatch.await();
                }
                catch ( InterruptedException e )
                {
                    e.printStackTrace();
                }
            } );
        }
        return endLatch;
    }

    private CountDownLatch loadThreadPool(
            QueuedThreadPool threadPool,
            int tasksToSubmit,
            final CountDownLatch startLatch )
    {
        final CountDownLatch endLatch = new CountDownLatch( 1 );
        for ( int i = 0; i < tasksToSubmit; i++ )
        {
            threadPool.execute( new Runnable()
            {
                @Override
                public void run()
                {
                    startLatch.countDown();
                    try
                    {
                        endLatch.await();
                    }
                    catch ( InterruptedException e )
                    {
                        e.printStackTrace();
                    }
                }
            } );
        }
        return endLatch;
    }

Replace Anonymous With Lambda org.neo4j.server.web.JettyThreadLimitTest.loadThreadPool.execute.new Runnable with () -> {startLatch.countDown(); in method private loadThreadPool(threadPool QueuedThreadPool, tasksToSubmit int, startLatch CountDownLatch) : CountDownLatch from class org.neo4j.server.web.JettyThreadLimitTest


    private static JPanel createStartedStatusDisplay( DesktopModel model )
    {
        final JLabel link = new JLabel( "http://localhost:7474/" );

        model.register( model1 -> link.setText("http://" + model1.getServerAddress() +  "/") );

        link.setFont( Components.underlined( link.getFont() ) );
        link.addMouseListener( new OpenBrowserMouseListener( link, model ) );

        return createStatusDisplay( STARTED_COLOR, new JLabel( "Neo4j is ready. Browse to " ), link );
    }

    private static JPanel createStartedStatusDisplay( DesktopModel model )
    {
        final JLabel link = new JLabel( "http://localhost:7474/" );

        model.register( new DesktopModelListener() {
            @Override
            public void desktopModelChanged(DesktopModel model) {
                link.setText("http://localhost:" + model.getServerPort() +  "/");
            }
        });

        link.setFont( Components.underlined( link.getFont() ) );
        link.addMouseListener( new OpenBrowserMouseListener( link, model ) );

        return createStatusDisplay( STARTED_COLOR, new JLabel( "Neo4j is ready. Browse to " ), link );
    }

Replace Anonymous With Lambda org.neo4j.desktop.ui.DatabaseStatus.createStartedStatusDisplay.register.new DesktopModelListener with model1 -> link.setText("http://" + model1.getServerAddress() + "/") in method private createStartedStatusDisplay(model DesktopModel) : JPanel from class org.neo4j.desktop.ui.DatabaseStatus


    private void repopulateAllIndexes() throws IOException, IndexEntryConflictException
    {
        if ( !labelsTouched )
        {
            return;
        }

        final IndexRule[] rules = getIndexesNeedingPopulation();
        final IndexPopulator[] populators = new IndexPopulator[rules.length];
        // the store is uncontended at this point, so creating a local LockService is safe.

        final int[] labelIds = new int[rules.length];
        final int[] propertyKeyIds = new int[rules.length];

        for ( int i = 0; i < labelIds.length; i++ )
        {
            IndexRule rule = rules[i];
            int labelId = rule.getLabel();
            int propertyKeyId = rule.getPropertyKey();
            labelIds[i] = labelId;
            propertyKeyIds[i] = propertyKeyId;

            IndexDescriptor descriptor = new IndexDescriptor( labelId, propertyKeyId );
            populators[i] = schemaIndexProviders.apply( rule.getProviderDescriptor() )
                                                .getPopulator( rule.getId(),
                                                        descriptor,
                                                        IndexConfiguration.of( rule ),
                                                        new IndexSamplingConfig( config ) );
            populators[i].create();
        }

        Visitor<NodePropertyUpdates, IOException> propertyUpdateVisitor = updates -> {
            // Do a lookup from which property has changed to a list of indexes worried about that property.
            for ( NodePropertyUpdate update : updates.getPropertyUpdates() )
            {
                int propertyKeyInQuestion = update.getPropertyKeyId();
                for ( int i = 0; i < propertyKeyIds.length; i++ )
                {
                    if ( propertyKeyIds[i] == propertyKeyInQuestion )
                    {
                        if ( update.forLabel( labelIds[i] ) )
                        {
                            try
                            {
                                populators[i].add( Collections.singletonList( update ) );
                            }
                            catch ( IndexEntryConflictException conflict )
                            {
                                throw conflict.notAllowed( rules[i].getLabel(), rules[i].getPropertyKey() );
                            }
                        }
                    }
                }
            }
            return true;
        };

        InitialNodeLabelCreationVisitor labelUpdateVisitor = new InitialNodeLabelCreationVisitor();
        StoreScan<IOException> storeScan = indexStoreView.visitNodes(
                (labelId) -> PrimitiveIntCollections.contains( labelIds, labelId ),
                (propertyKeyId) -> PrimitiveIntCollections.contains( propertyKeyIds, propertyKeyId ),
                propertyUpdateVisitor, labelUpdateVisitor );
        storeScan.run();

        for ( IndexPopulator populator : populators )
        {
            populator.verifyDeferredConstraints( indexStoreView );
            populator.close( true );
        }
        labelUpdateVisitor.close();
    }

    private void repopulateAllIndexes() throws IOException, IndexEntryConflictException
    {
        if ( !labelsTouched )
        {
            return;
        }

        final IndexRule[] rules = getIndexesNeedingPopulation();
        final IndexPopulator[] populators = new IndexPopulator[rules.length];
        // the store is uncontended at this point, so creating a local LockService is safe.

        final int[] labelIds = new int[rules.length];
        final int[] propertyKeyIds = new int[rules.length];

        for ( int i = 0; i < labelIds.length; i++ )
        {
            IndexRule rule = rules[i];
            int labelId = rule.getLabel();
            int propertyKeyId = rule.getPropertyKey();
            labelIds[i] = labelId;
            propertyKeyIds[i] = propertyKeyId;

            IndexDescriptor descriptor = new IndexDescriptor( labelId, propertyKeyId );
            populators[i] = schemaIndexProviders.apply( rule.getProviderDescriptor() )
                                                .getPopulator( rule.getId(),
                                                        descriptor,
                                                        IndexConfiguration.of( rule ),
                                                        new IndexSamplingConfig( config ) );
            populators[i].create();
        }

        Visitor<NodePropertyUpdate, IOException> propertyUpdateVisitor = new Visitor<NodePropertyUpdate,IOException>()
        {
            @Override
            public boolean visit( NodePropertyUpdate update ) throws IOException
            {
                // Do a lookup from which property has changed to a list of indexes worried about that property.
                int propertyKeyInQuestion = update.getPropertyKeyId();
                for ( int i = 0; i < propertyKeyIds.length; i++ )
                {
                    if ( propertyKeyIds[i] == propertyKeyInQuestion )
                    {
                        if ( update.forLabel( labelIds[i] ) )
                        {
                            try
                            {
                                populators[i].add( Collections.singletonList( update ) );
                            }
                            catch ( IndexEntryConflictException conflict )
                            {
                                throw conflict.notAllowed( rules[i].getLabel(), rules[i].getPropertyKey() );
                            }
                        }
                    }
                }
                return true;
            }
        };

        InitialNodeLabelCreationVisitor labelUpdateVisitor = new InitialNodeLabelCreationVisitor();
        StoreScan<IOException> storeScan = indexStoreView.visitNodes(
                (labelId) -> PrimitiveIntCollections.contains( labelIds, labelId ),
                (propertyKeyId) -> PrimitiveIntCollections.contains( propertyKeyIds, propertyKeyId ),
                propertyUpdateVisitor, labelUpdateVisitor );
        storeScan.run();

        for ( IndexPopulator populator : populators )
        {
            populator.verifyDeferredConstraints( indexStoreView );
            populator.close( true );
        }
        labelUpdateVisitor.close();
    }

Replace Anonymous With Lambda org.neo4j.unsafe.batchinsert.BatchInserterImpl.repopulateAllIndexes.propertyUpdateVisitor.new Visitor<NodePropertyUpdate,IOException> with updates -> {for(NodePropertyUpdate update: updates.getPropertyUpdates()){int propertyKeyInQuestion=update.getPropertyKeyId(); in method private repopulateAllIndexes() : void from class org.neo4j.unsafe.batchinsert.BatchInserterImpl


    @Before
    public void before() throws KernelException
    {
        graphDb = dbRule.getGraphDatabaseAPI();

        createAlistairAndStefanNodes();
        getOrCreateIds();

        neoStores = graphDb.getDependencyResolver().resolveDependency( RecordStorageEngine.class ).testAccessNeoStores();
        locks = mock( LockService.class, (Answer) invocation -> {
            Long nodeId = (Long) invocation.getArguments()[0];
            Lock lock = lockMocks.get( nodeId );
            if ( lock == null )
            {
                lockMocks.put( nodeId, lock = mock( Lock.class ) );
            }
            return lock;
        } );
        storeView = new NeoStoreIndexStoreView( locks, neoStores );
    }

    @Before
    public void before() throws KernelException
    {
        graphDb = dbRule.getGraphDatabaseAPI();

        createAlistairAndStefanNodes();
        getOrCreateIds();

        neoStores = graphDb.getDependencyResolver().resolveDependency( RecordStorageEngine.class ).testAccessNeoStores();
        counts = neoStores.getCounts();
        locks = mock( LockService.class, new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                Long nodeId = (Long) invocation.getArguments()[0];
                Lock lock = lockMocks.get( nodeId );
                if ( lock == null )
                {
                    lockMocks.put( nodeId, lock = mock( Lock.class ) );
                }
                return lock;
            }
        } );
        storeView = new NeoStoreIndexStoreView( locks, neoStores );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.state.NeoStoreIndexStoreViewTest.before.mock.new Answer with invocation -> {Long nodeId=(Long)invocation.getArguments()[0]; in method public before() : void from class org.neo4j.kernel.impl.transaction.state.NeoStoreIndexStoreViewTest


    public static void main( String[] args ) throws IOException
    {
        Args arg = Args.parse( args );

        String from = arg.get( "from" );
        System.out.println("From is " + from);
        String to = arg.get( "to" );
        System.out.println("to is " + to);

        File logDirectory = new File( from );
        System.out.println( "logDirectory = " + logDirectory );
        NaiveDurableRaftLog log = new NaiveDurableRaftLog( new DefaultFileSystemAbstraction(),
                logDirectory, new CoreReplicatedContentMarshal(), NullLogProvider.getInstance() );

        long totalCommittedEntries = log.commitIndex();

//        File target = new File( to );
//        RandomAccessFile newLog = new RandomAccessFile( target, "rw" );

        for ( int i = 0; i <= totalCommittedEntries; i++ )
        {
            ReplicatedContent content = readLogEntry( log, i ).content();
            if ( content instanceof ReplicatedTransaction )
            {
                ReplicatedTransaction tx = (ReplicatedTransaction) content;
                ReplicatedTransactionFactory.extractTransactionRepresentation( tx, new byte[0] ).accept(
                        element -> {
                            System.out.println(element);
                            return false;
                        } );
            }
        }
//        newLog.close();
    }

    public static void main( String[] args ) throws IOException
    {
        Args arg = Args.parse( args );

        String from = arg.get( "from" );
        System.out.println("From is " + from);
        String to = arg.get( "to" );
        System.out.println("to is " + to);

        File logDirectory = new File( from );
        System.out.println( "logDirectory = " + logDirectory );
        NaiveDurableRaftLog log = new NaiveDurableRaftLog( new DefaultFileSystemAbstraction(),
                logDirectory, new CoreReplicatedContentMarshal(), NullLogProvider.getInstance() );

        long totalCommittedEntries = log.commitIndex();

//        File target = new File( to );
//        RandomAccessFile newLog = new RandomAccessFile( target, "rw" );

        for ( int i = 0; i <= totalCommittedEntries; i++ )
        {
            ReplicatedContent content = log.readLogEntry( i ).content();
            if ( content instanceof ReplicatedTransaction )
            {
                ReplicatedTransaction tx = (ReplicatedTransaction) content;
                ReplicatedTransactionFactory.extractTransactionRepresentation( tx, new byte[0] ).accept(
                        new Visitor<StorageCommand, IOException>()
                        {
                            @Override
                            public boolean visit( StorageCommand element ) throws IOException
                            {
                                System.out.println(element);
                                return false;
                            }
                        } );
            }
        }
//        newLog.close();
    }

Replace Anonymous With Lambda org.neo4j.coreedge.raft.log.debug.ReplayRaftLog.main.accept.new Visitor<StorageCommand,IOException> with element -> {System.out.println(element); in method public main(args String[]) : void from class org.neo4j.coreedge.raft.log.debug.ReplayRaftLog


    @Test
    public void getAllNodesIteratorShouldPickUpHigherIdsThanHighIdWhenStarted() throws Exception
    {
        // GIVEN
        {
            Transaction tx = db.beginTx();
            db.createNode();
            db.createNode();
            tx.success();
            tx.close();
        }

        // WHEN iterator is started
        Transaction transaction = db.beginTx();
        Iterator<Node> allNodes = db.getAllNodes().iterator();
        allNodes.next();

        // and WHEN another node is then added
        Thread thread = new Thread( () -> {
            Transaction newTx = db.beginTx();
            assertThat( newTx, not( instanceOf( PlaceboTransaction.class ) ) );
            db.createNode();
            newTx.success();
            newTx.close();
        } );
        thread.start();
        thread.join();

        // THEN the new node is picked up by the iterator
        assertThat( addToCollection( allNodes, new ArrayList<Node>() ).size(), is( 2 ) );
        transaction.close();
    }

    @Test
    public void getAllNodesIteratorShouldPickUpHigherIdsThanHighIdWhenStarted() throws Exception
    {
        // GIVEN
        {
            Transaction tx = db.beginTx();
            db.createNode();
            db.createNode();
            tx.success();
            tx.close();
        }

        // WHEN iterator is started
        Transaction transaction = db.beginTx();
        Iterator<Node> allNodes = db.getAllNodes().iterator();
        allNodes.next();

        // and WHEN another node is then added
        Thread thread = new Thread( new Runnable()
        {
            @Override
            public void run()
            {
                Transaction newTx = db.beginTx();
                assertThat( newTx, not( instanceOf( PlaceboTransaction.class ) ) );
                db.createNode();
                newTx.success();
                newTx.close();
            }
        } );
        thread.start();
        thread.join();

        // THEN the new node is picked up by the iterator
        assertThat( addToCollection( allNodes, new ArrayList<Node>() ).size(), is( 2 ) );
        transaction.close();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.core.NodeManagerTest.getAllNodesIteratorShouldPickUpHigherIdsThanHighIdWhenStarted.thread.new Thread.new Runnable with () -> {Transaction newTx=db.beginTx(); in method public getAllNodesIteratorShouldPickUpHigherIdsThanHighIdWhenStarted() : void from class org.neo4j.kernel.impl.core.NodeManagerTest


    /**
     * Starts multiple threads which updates and queries an index concurrently
     * during a long period of time just to make sure that number of file handles doesn't grow.
     * @throws Exception
     */
    @Test
    @Ignore
    public void makeSureFilesAreClosedProperly() throws Exception
    {
        commitTx();

        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(testDirectory.directory( "filesClosedProperty" ) );
        final Index<Node> index = nodeIndex( "open-files", LuceneIndexImplementation.EXACT_CONFIG );
        final long time = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch( 30 );
        int coreCount = Runtime.getRuntime().availableProcessors();
        ExecutorService pool = Executors.newFixedThreadPool( coreCount );
        for ( int t = 0; t < latch.getCount(); t++ )
        {
            pool.execute( () -> {
                for ( int i = 0; System.currentTimeMillis() - time < 60*1000*2; i++ )
                {
                    if ( i%10 == 0 )
                    {
                        if ( i%100 == 0 )
                        {
                            int type = (int)(System.currentTimeMillis()%3);
                            if ( type == 0 )
                            {
                                IndexHits<Node> itr = index.get( "key", "value5" );
                                try
                                {
                                    itr.getSingle();
                                }
                                catch ( NoSuchElementException e )
                                { // For when there are multiple hits
                                }
                            }
                            else if ( type == 1 )
                            {
                                IndexHits<Node> itr = index.get( "key", "value5" );
                                for ( int size = 0; itr.hasNext() && size < 5; size++ )
                                {
                                    itr.next();
                                }
                                itr.close();
                            }
                            else
                            {
                                IndexHits<Node> itr = index.get( "key", "crap value" ); /* Will return 0 hits */
                                // Iterate over the hits sometimes (it's always gonna be 0 sized)
                                if ( System.currentTimeMillis() % 10 > 5 )
                                {
                                    Iterators.count( itr );
                                }
                            }
                        }
                        else
                        {
                            Iterators.count( index.get( "key", "value5" ) );
                        }
                    }
                    else
                    {
                        try ( Transaction tx1 = graphDb.beginTx() )
                        {
                            for ( int ii = 0; ii < 20; ii++ )
                            {
                                Node node = graphDb.createNode();
                                index.add( node, "key", "value" + ii );
                            }
                            tx1.success();
                        }
                    }
                }
            } );
        }
        pool.shutdown();
        pool.awaitTermination( 10, TimeUnit.DAYS );
        graphDb.shutdown();
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
    }

    /**
     * Starts multiple threads which updates and queries an index concurrently
     * during a long period of time just to make sure that number of file handles doesn't grow.
     * @throws Exception
     */
    @Test
    @Ignore
    public void makeSureFilesAreClosedProperly() throws Exception
    {
        commitTx();

        graphDb = new GraphDatabaseFactory().newEmbeddedDatabase(testDirectory.directory( "filesClosedProperty" ) );
        final Index<Node> index = nodeIndex( "open-files", LuceneIndexImplementation.EXACT_CONFIG );
        final long time = System.currentTimeMillis();
        final CountDownLatch latch = new CountDownLatch( 30 );
        int coreCount = Runtime.getRuntime().availableProcessors();
        ExecutorService pool = Executors.newFixedThreadPool( coreCount );
        for ( int t = 0; t < latch.getCount(); t++ )
        {
            pool.execute( new Runnable()
            {
                @Override
                public void run()
                {
                    for ( int i = 0; System.currentTimeMillis() - time < 60*1000*2; i++ )
                    {
                        if ( i%10 == 0 )
                        {
                            if ( i%100 == 0 )
                            {
                                int type = (int)(System.currentTimeMillis()%3);
                                if ( type == 0 )
                                {
                                    IndexHits<Node> itr = index.get( "key", "value5" );
                                    try
                                    {
                                        itr.getSingle();
                                    }
                                    catch ( NoSuchElementException e )
                                    { // For when there are multiple hits
                                    }
                                }
                                else if ( type == 1 )
                                {
                                    IndexHits<Node> itr = index.get( "key", "value5" );
                                    for ( int size = 0; itr.hasNext() && size < 5; size++ )
                                    {
                                        itr.next();
                                    }
                                    itr.close();
                                }
                                else
                                {
                                    IndexHits<Node> itr = index.get( "key", "crap value" ); /* Will return 0 hits */
                                    // Iterate over the hits sometimes (it's always gonna be 0 sized)
                                    if ( System.currentTimeMillis() % 10 > 5 )
                                    {
                                        IteratorUtil.count( (Iterator<Node>) itr );
                                    }
                                }
                            }
                            else
                            {
                                IteratorUtil.count( (Iterator<Node>) index.get( "key", "value5" ) );
                            }
                        }
                        else
                        {
                            try ( Transaction tx = graphDb.beginTx() )
                            {
                                for ( int ii = 0; ii < 20; ii++ )
                                {
                                    Node node = graphDb.createNode();
                                    index.add( node, "key", "value" + ii );
                                }
                                tx.success();
                            }
                        }
                    }
                }
            } );
        }
        pool.shutdown();
        pool.awaitTermination( 10, TimeUnit.DAYS );
        graphDb.shutdown();
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
    }

Replace Anonymous With Lambda org.neo4j.index.impl.lucene.legacy.PerformanceAndSanityIT.makeSureFilesAreClosedProperly.execute.new Runnable with () -> {for(int i=0; System.currentTimeMillis() - time < 60 * 1000 * 2; i++){if(i % 10 == 0){if(i % 100 == 0){int type=(int)(System.currentTimeMillis() % 3); in method public makeSureFilesAreClosedProperly() : void from class org.neo4j.index.impl.lucene.legacy.PerformanceAndSanityIT


    @Test
    public void exampleWithParameterForNodeId() throws Exception
    {
        // START SNIPPET: exampleWithParameterForNodeId
        Map<String, Object> params = new HashMap<>();
        params.put( "id", 0 );
        String query = "MATCH (n) WHERE id(n) = {id} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForNodeId

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Michaela", n_column.next() );
        dumpToFile( "exampleWithParameterForNodeId", query, params );
    }

    @Test
    public void exampleWithParameterForNodeId() throws Exception
    {
        // START SNIPPET: exampleWithParameterForNodeId
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "id", 0 );
        String query = "MATCH (n) WHERE id(n) = {id} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForNodeId

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Michaela", n_column.next() );
        dumpToFile( "exampleWithParameterForNodeId", query, params );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterForNodeId() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParameterForMultipleNodeIds() throws Exception
    {
        // START SNIPPET: exampleWithParameterForMultipleNodeIds
        Map<String, Object> params = new HashMap<>();
        params.put( "ids", Arrays.asList( 0, 1, 2 ) );
        String query = "MATCH (n) WHERE id(n) in {ids} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForMultipleNodeIds

        assertEquals( asList( "Michaela", "Andreas", "Johan" ), this.<String>toList( result, "n.name" ) );
        dumpToFile( "exampleWithParameterForMultipleNodeIds", query, params );
    }

    @Test
    public void exampleWithParameterForMultipleNodeIds() throws Exception
    {
        // START SNIPPET: exampleWithParameterForMultipleNodeIds
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "ids", Arrays.asList( 0, 1, 2 ) );
        String query = "MATCH (n) WHERE id(n) in {ids} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForMultipleNodeIds

        assertEquals( asList( "Michaela", "Andreas", "Johan" ), this.<String>toList( result, "n.name" ) );
        dumpToFile( "exampleWithParameterForMultipleNodeIds", query, params );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterForMultipleNodeIds() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithStringLiteralAsParameter() throws Exception
    {
        // START SNIPPET: exampleWithStringLiteralAsParameter
        Map<String, Object> params = new HashMap<>();
        params.put( "name", "Johan" );
        String query = "MATCH (n) WHERE n.name = {name} RETURN n";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithStringLiteralAsParameter

        assertEquals( asList( johanNode ), this.<Node>toList( result, "n" ) );
        dumpToFile( "exampleWithStringLiteralAsParameter", query, params );
    }

    @Test
    public void exampleWithStringLiteralAsParameter() throws Exception
    {
        // START SNIPPET: exampleWithStringLiteralAsParameter
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "name", "Johan" );
        String query = "MATCH (n) WHERE n.name = {name} RETURN n";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithStringLiteralAsParameter

        assertEquals( asList( johanNode ), this.<Node>toList( result, "n" ) );
        dumpToFile( "exampleWithStringLiteralAsParameter", query, params );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithStringLiteralAsParameter() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithShortSyntaxStringLiteralAsParameter() throws Exception
    {
        // START SNIPPET: exampleWithShortSyntaxStringLiteralAsParameter
        Map<String, Object> params = new HashMap<>();
        params.put( "name", "Johan" );
        String query = "MATCH (n {name: {name}}) RETURN n";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithShortSyntaxStringLiteralAsParameter

        assertEquals( asList( johanNode ), this.<Node>toList( result, "n" ) );
        dumpToFile( "exampleWithShortSyntaxStringLiteralAsParameter", query, params );
    }

    @Test
    public void exampleWithShortSyntaxStringLiteralAsParameter() throws Exception
    {
        // START SNIPPET: exampleWithShortSyntaxStringLiteralAsParameter
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "name", "Johan" );
        String query = "MATCH (n {name: {name}}) RETURN n";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithShortSyntaxStringLiteralAsParameter

        assertEquals( asList( johanNode ), this.<Node>toList( result, "n" ) );
        dumpToFile( "exampleWithShortSyntaxStringLiteralAsParameter", query, params );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithShortSyntaxStringLiteralAsParameter() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParameterForIndexValue() throws Exception
    {
        try ( Transaction ignored = db.beginTx() )
        {
            // START SNIPPET: exampleWithParameterForIndexValue
            Map<String, Object> params = new HashMap<>();
            params.put( "value", "Michaela" );
            String query = "START n=node:people(name = {value}) RETURN n";
            Result result = db.execute( query, params );
            // END SNIPPET: exampleWithParameterForIndexValue
            assertEquals( asList( michaelaNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParameterForIndexValue", query, params );
        }
    }

    @Test
    public void exampleWithParameterForIndexValue() throws Exception
    {
        try ( Transaction ignored = db.beginTx() )
        {
            // START SNIPPET: exampleWithParameterForIndexValue
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "value", "Michaela" );
            String query = "START n=node:people(name = {value}) RETURN n";
            Result result = db.execute( query, params );
            // END SNIPPET: exampleWithParameterForIndexValue
            assertEquals( asList( michaelaNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParameterForIndexValue", query, params );
        }
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterForIndexValue() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParametersForQuery() throws Exception
    {
        try ( Transaction ignored = db.beginTx() )
        {
            // START SNIPPET: exampleWithParametersForQuery
            Map<String, Object> params = new HashMap<>();
            params.put( "query", "name:Andreas" );
            String query = "START n=node:people({query}) RETURN n";
            Result result = db.execute( query, params );
            // END SNIPPET: exampleWithParametersForQuery
            assertEquals( asList( andreasNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParametersForQuery", query, params );
        }
    }

    @Test
    public void exampleWithParametersForQuery() throws Exception
    {
        try ( Transaction ignored = db.beginTx() )
        {
            // START SNIPPET: exampleWithParametersForQuery
            Map<String, Object> params = new HashMap<String, Object>();
            params.put( "query", "name:Andreas" );
            String query = "START n=node:people({query}) RETURN n";
            Result result = db.execute( query, params );
            // END SNIPPET: exampleWithParametersForQuery
            assertEquals( asList( andreasNode ), this.<Node>toList( result, "n" ) );
            dumpToFile( "exampleWithParametersForQuery", query, params );
        }
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParametersForQuery() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParameterForNodeObject() throws Exception
    {
        // START SNIPPET: exampleWithParameterForNodeObject
        Map<String, Object> params = new HashMap<>();
        params.put( "node", andreasNode );
        String query = "MATCH (n) WHERE n = {node} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForNodeObject

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Andreas", n_column.next() );
    }

    @Test
    public void exampleWithParameterForNodeObject() throws Exception
    {
        // START SNIPPET: exampleWithParameterForNodeObject
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "node", andreasNode );
        String query = "MATCH (n) WHERE n = {node} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForNodeObject

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Andreas", n_column.next() );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterForNodeObject() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParameterForSkipAndLimit() throws Exception
    {
        // START SNIPPET: exampleWithParameterForSkipLimit
        Map<String, Object> params = new HashMap<>();
        params.put( "s", 1 );
        params.put( "l", 1 );
        String query = "MATCH (n) RETURN n.name SKIP {s} LIMIT {l}";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForSkipLimit

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Andreas", n_column.next() );
        dumpToFile( "exampleWithParameterForSkipLimit", query, params );
    }

    @Test
    public void exampleWithParameterForSkipAndLimit() throws Exception
    {
        // START SNIPPET: exampleWithParameterForSkipLimit
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "s", 1 );
        params.put( "l", 1 );
        String query = "MATCH (n) RETURN n.name SKIP {s} LIMIT {l}";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterForSkipLimit

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Andreas", n_column.next() );
        dumpToFile( "exampleWithParameterForSkipLimit", query, params );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterForSkipAndLimit() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParameterRegularExpression() throws Exception
    {
        // START SNIPPET: exampleWithParameterRegularExpression
        Map<String, Object> params = new HashMap<>();
        params.put( "regex", ".*h.*" );
        String query = "MATCH (n) WHERE n.name =~ {regex} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterRegularExpression
        dumpToFile( "exampleWithParameterRegularExpression", query, params );

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Michaela", n_column.next() );
        assertEquals( "Johan", n_column.next() );
    }

    @Test
    public void exampleWithParameterRegularExpression() throws Exception
    {
        // START SNIPPET: exampleWithParameterRegularExpression
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "regex", ".*h.*" );
        String query = "MATCH (n) WHERE n.name =~ {regex} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterRegularExpression
        dumpToFile( "exampleWithParameterRegularExpression", query, params );

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Michaela", n_column.next() );
        assertEquals( "Johan", n_column.next() );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterRegularExpression() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    @Test
    public void exampleWithParameterCSCIStringPatternMatching() throws Exception
    {
        // START SNIPPET: exampleWithParameterCSCIStringPatternMatching
        Map<String, Object> params = new HashMap<>();
        params.put( "name", "Michael" );
        String query = "MATCH (n) WHERE n.name STARTS WITH {name} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterCSCIStringPatternMatching
        dumpToFile( "exampleWithParameterCSCIStringPatternMatching", query, params );

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Michaela", n_column.next() );
    }

    @Test
    public void exampleWithParameterCSCIStringPatternMatching() throws Exception
    {
        // START SNIPPET: exampleWithParameterCSCIStringPatternMatching
        Map<String, Object> params = new HashMap<String, Object>();
        params.put( "name", "Michael" );
        String query = "MATCH (n) WHERE n.name STARTS WITH {name} RETURN n.name";
        Result result = db.execute( query, params );
        // END SNIPPET: exampleWithParameterCSCIStringPatternMatching
        dumpToFile( "exampleWithParameterCSCIStringPatternMatching", query, params );

        assertThat( result.columns(), hasItem( "n.name" ) );
        Iterator<Object> n_column = result.columnAs( "n.name" );
        assertEquals( "Michaela", n_column.next() );
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public exampleWithParameterCSCIStringPatternMatching() : void from class org.neo4j.cypher.example.JavaExecutionEngineDocTest


    private void terminateAllWaiters()
    {
        manager.accept( lock -> {
            lock.terminateLockRequestsForLockTransaction( lockTransaction );
            return false;
        } );
    }

    private void terminateAllWaiters()
    {
        manager.accept( new Visitor<RWLock,RuntimeException>()
        {
            @Override
            public boolean visit( RWLock lock ) throws RuntimeException
            {
                lock.terminateLockRequestsForLockTransaction( lockTransaction );
                return false;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.CommunityLockClient.terminateAllWaiters.accept.new Visitor<RWLock,RuntimeException> with lock -> {lock.terminateLockRequestsForLockTransaction(lockTransaction); in method private terminateAllWaiters() : void from class org.neo4j.kernel.impl.locking.community.CommunityLockClient


    @Override
    public void accept( final Visitor visitor )
    {
        manager.accept( element -> {
            Object resource = element.resource();
            if ( resource instanceof LockResource )
            {
                LockResource lockResource = (LockResource) resource;
                visitor.visit( lockResource.type(), lockResource.resourceId(),
                        element.describe(), element.maxWaitTime(), System.identityHashCode( lockResource ) );
            }
            return false;
        } );
    }

    @Override
    public void accept( final Visitor visitor )
    {
        manager.accept( new org.neo4j.helpers.collection.Visitor<RWLock, RuntimeException>()
        {
            @Override
            public boolean visit( RWLock element ) throws RuntimeException
            {
                Object resource = element.resource();
                if(resource instanceof LockResource)
                {
                    LockResource lockResource = (LockResource)resource;
                    visitor.visit( lockResource.type(), lockResource.resourceId(),
                            element.describe(), element.maxWaitTime(), System.identityHashCode( lockResource ) );
                }
                return false;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.CommunityLockManger.accept.accept.new org.neo4j.helpers.collection.Visitor<RWLock,RuntimeException> with element -> {Object resource=element.resource(); in method public accept(visitor Visitor) : void from class org.neo4j.kernel.impl.locking.community.CommunityLockManger


    @Test( timeout = 1000 )
    public void testThreadRemovedFromWaitingListOnDeadlock() throws InterruptedException
    {
        RagManager ragManager = Mockito.mock( RagManager.class );
        LockResource resource = new LockResource( ResourceTypes.NODE, 1L );
        final RWLock lock = new RWLock( resource, ragManager );
        final LockTransaction lockTransaction = new LockTransaction();
        final LockTransaction anotherTransaction = new LockTransaction();

        final CountDownLatch exceptionLatch = new CountDownLatch( 1 );
        final CountDownLatch completionLatch = new CountDownLatch( 1 );

        Mockito.doNothing().doAnswer( invocation -> {
            exceptionLatch.countDown();
            throw new DeadlockDetectedException( "Deadlock" );
        } ).when( ragManager ).checkWaitOn( lock, lockTransaction );

        lock.mark();
        lock.mark();
        lock.acquireReadLock( lockTransaction );
        lock.acquireReadLock( anotherTransaction );

        // writer will be added to a waiting list
        // then spurious wake up will be simulated
        // and deadlock will be detected
        Runnable writer = () -> {
            try
            {
                lock.mark();
                lock.acquireWriteLock( lockTransaction );
            }
            catch ( DeadlockDetectedException ignored )
            {
                // ignored
            }
            completionLatch.countDown();
        };
        executor.execute( writer );

        waitWaitingThreads( lock, 1 );

        // sending notify for all threads till our writer will not cause deadlock exception
        do
        {
            //noinspection SynchronizationOnLocalVariableOrMethodParameter
            synchronized ( lock )
            {
                lock.notifyAll();
            }
        }
        while ( exceptionLatch.getCount() == 1 );

        // waiting for writer to finish
        completionLatch.await();

        assertEquals( "In case of deadlock caused by spurious wake up " +
                      "thread should be removed from waiting list", 0, lock.getWaitingThreadsCount() );
    }

    @Test( timeout = 1000 )
    public void testThreadRemovedFromWaitingListOnDeadlock() throws InterruptedException
    {
        RagManager ragManager = Mockito.mock( RagManager.class );
        LockResource resource = new LockResource( ResourceTypes.NODE, 1l );
        final RWLock lock = new RWLock( resource, ragManager );
        final LockTransaction lockTransaction = new LockTransaction();
        final LockTransaction anotherTransaction = new LockTransaction();

        final CountDownLatch exceptionLatch = new CountDownLatch( 1 );
        final CountDownLatch completionLatch = new CountDownLatch( 1 );

        Mockito.doNothing().doAnswer( new Answer<Void>()
        {
            @Override
            public Void answer( InvocationOnMock invocation ) throws Throwable
            {
                exceptionLatch.countDown();
                throw new DeadlockDetectedException( "Deadlock" );
            }
        } ).when( ragManager ).checkWaitOn( lock, lockTransaction );

        lock.acquireReadLock( lockTransaction );
        lock.acquireReadLock( anotherTransaction );

        // writer will be added to a waiting list
        // then spurious wake up will be simulated
        // and deadlock will be detected
        Runnable writer = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    lock.acquireWriteLock( lockTransaction );
                }
                catch ( DeadlockDetectedException ignored )
                {
                    // ignored
                }
                completionLatch.countDown();
            }
        };
        executor.execute( writer );

        waitWaitingThreads( lock, 1 );

        // sending notify for all threads till our writer will not cause deadlock exception
        do
        {
            synchronized ( lock )
            {
                lock.notifyAll();
            }
        }
        while ( exceptionLatch.getCount() == 1 );

        // waiting for writer to finish
        completionLatch.await();

        assertEquals( "In case of deadlock caused by spurious wake up " +
                             "thread should be removed from waiting list", 0, lock.getWaitingThreadsCount() );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.RWLockTest.testThreadRemovedFromWaitingListOnDeadlock.writer.new Runnable with () -> {trylock.mark(); in method public testThreadRemovedFromWaitingListOnDeadlock() : void from class org.neo4j.kernel.impl.locking.community.RWLockTest


    private Runnable createReader( final RWLock lock, final LockTransaction transaction,
                                   final CountDownLatch latch )
    {
        return () -> {
            lock.mark();
            lock.acquireReadLock( transaction );
            latch.countDown();
        };
    }

    private Runnable createReader( final RWLock lock, final LockTransaction transaction,
            final CountDownLatch latch )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                lock.acquireReadLock( transaction );
                latch.countDown();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.RWLockTest.createReader.new Runnable with () -> {lock.mark(); in method private createReader(lock RWLock, transaction LockTransaction, latch CountDownLatch) : Runnable from class org.neo4j.kernel.impl.locking.community.RWLockTest


    private Runnable createFailedReader( final RWLock lock, final LockTransaction transaction,
                                         final CountDownLatch latch )
    {
        return () -> {
            lock.mark();
            Assert.assertFalse( lock.acquireReadLock( transaction ) );
            latch.countDown();
        };
    }

    private Runnable createFailedReader( final RWLock lock, final LockTransaction transaction,
            final CountDownLatch latch )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                Assert.assertFalse( lock.acquireReadLock( transaction ) );
                latch.countDown();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.RWLockTest.createFailedReader.new Runnable with () -> {lock.mark(); in method private createFailedReader(lock RWLock, transaction LockTransaction, latch CountDownLatch) : Runnable from class org.neo4j.kernel.impl.locking.community.RWLockTest


    private Runnable createWriter( final RWLock lock, final LockTransaction transaction,
                                   final CountDownLatch latch )
    {
        return () -> {
            lock.mark();
            lock.acquireWriteLock( transaction );
            latch.countDown();
        };
    }

    private Runnable createWriter( final RWLock lock, final LockTransaction transaction,
            final CountDownLatch latch )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                lock.acquireWriteLock( transaction );
                latch.countDown();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.RWLockTest.createWriter.new Runnable with () -> {lock.mark(); in method private createWriter(lock RWLock, transaction LockTransaction, latch CountDownLatch) : Runnable from class org.neo4j.kernel.impl.locking.community.RWLockTest


    private Runnable createFailedWriter( final RWLock lock, final LockTransaction transaction,
                                         final CountDownLatch latch )
    {
        return () -> {
            lock.mark();
            Assert.assertFalse( lock.acquireWriteLock( transaction ) );
            latch.countDown();
        };
    }

    private Runnable createFailedWriter( final RWLock lock, final LockTransaction transaction,
            final CountDownLatch latch )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                Assert.assertFalse( lock.acquireWriteLock( transaction ) );
                latch.countDown();
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.RWLockTest.createFailedWriter.new Runnable with () -> {lock.mark(); in method private createFailedWriter(lock RWLock, transaction LockTransaction, latch CountDownLatch) : Runnable from class org.neo4j.kernel.impl.locking.community.RWLockTest


    private Runnable createReaderForDeadlock( final RWLock node, final LockTransaction transaction,
                                              final CountDownLatch latch )
    {
        return () -> {
            try
            {
                node.mark();
                node.acquireReadLock( transaction );
            }
            catch ( DeadlockDetectedException e )
            {
                latch.countDown();
            }
        };
    }

    private Runnable createReaderForDeadlock( final RWLock node, final LockTransaction transaction,
            final CountDownLatch latch )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    node.acquireReadLock( transaction );
                }
                catch ( DeadlockDetectedException e )
                {
                    latch.countDown();
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.RWLockTest.createReaderForDeadlock.new Runnable with () -> {trynode.mark(); in method private createReaderForDeadlock(node RWLock, transaction LockTransaction, latch CountDownLatch) : Runnable from class org.neo4j.kernel.impl.locking.community.RWLockTest


        @Override
        public void start()
        {
            scheduler = Executors.newSingleThreadScheduledExecutor(
                    daemon( "timeout-clusterClient", monitors.newMonitor( NamedThreadFactory.Monitor.class ) ) );

            tickFuture = scheduler.scheduleWithFixedDelay( () -> {
                long now = System.currentTimeMillis();

                server.getTimeouts().tick( now );
            }, 0, 10, TimeUnit.MILLISECONDS );
        }

        @Override
        public void start()
        {
            scheduler = Executors.newSingleThreadScheduledExecutor(
                    daemon( "timeout-clusterClient", monitors.newMonitor( NamedThreadFactory.Monitor.class ) ) );

            tickFuture = scheduler.scheduleWithFixedDelay( new Runnable()
            {
                @Override
                public void run()
                {
                    long now = System.currentTimeMillis();

                    server.getTimeouts().tick( now );
                }
            }, 0, 10, TimeUnit.MILLISECONDS );
        }

Replace Anonymous With Lambda org.neo4j.cluster.client.ClusterClientModule.TimeoutTrigger.start.scheduleWithFixedDelay.new Runnable with () -> {long now=System.currentTimeMillis(); in method public start() : void from class org.neo4j.cluster.client.ClusterClientModule.TimeoutTrigger


    private void tryOnce( final GraphDatabaseAPI db, final Node node, int iterations ) throws Throwable
    {
        ExecutorService executor = newCachedThreadPool();
        final CountDownLatch startSignal = new CountDownLatch( 1 );
        int threads = getRuntime().availableProcessors();
        final List<Throwable> errors = Collections.synchronizedList( new ArrayList<>() );
        for ( int i = 0; i < threads; i++ )
        {
            executor.submit( () -> {
                awaitStartSignalAndRandomTimeLonger( startSignal );
                try ( Transaction ignored = db.beginTx() )
                {
                    assertEquals( relCount, count( node.getRelationships() ) );
                }
                catch ( Throwable e )
                {
                    errors.add( e );
                }
            } );
        }
        startSignal.countDown();
        executor.shutdown();
        executor.awaitTermination( 10, SECONDS );

        if ( !errors.isEmpty() )
        {
            Exception exception = new Exception(
                    format("Exception(s) after %s iterations with %s threads", iterations, threads));
            for ( Throwable error : errors )
            {
                exception.addSuppressed( error );
            }
            throw exception;
        }
    }

    private void tryOnce( final GraphDatabaseAPI db, final Node node, int iterations ) throws Throwable
    {
        ExecutorService executor = newCachedThreadPool();
        final CountDownLatch startSignal = new CountDownLatch( 1 );
        int threads = getRuntime().availableProcessors();
        final List<Throwable> errors = Collections.synchronizedList( new ArrayList<Throwable>() );
        for ( int i = 0; i < threads; i++ )
        {
            executor.submit( new Runnable()
            {
                @Override
                public void run()
                {
                    awaitStartSignalAndRandomTimeLonger( startSignal );
                    try ( Transaction transaction = db.beginTx() )
                    {
                        assertEquals( relCount, count( node.getRelationships() ) );
                    }
                    catch ( Throwable e )
                    {
                        errors.add( e );
                    }
                }
            } );
        }
        startSignal.countDown();
        executor.shutdown();
        executor.awaitTermination( 10, SECONDS );

        if ( !errors.isEmpty() )
        {
            Exception exception = new Exception(
                    format("Exception(s) after %s iterations with %s threads", iterations, threads));
            for ( Throwable error : errors )
            {
                exception.addSuppressed( error );
            }
            throw exception;
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.core.TestConcurrentRelationshipChainLoadingIssue.tryOnce.submit.new Runnable with () -> {awaitStartSignalAndRandomTimeLonger(startSignal); in method private tryOnce(db GraphDatabaseAPI, node Node, iterations int) : void from class org.neo4j.kernel.impl.core.TestConcurrentRelationshipChainLoadingIssue


    @Override
    public Iterable<Label> getNodeLabels( final long node )
    {
        return () -> {
            NodeRecord record = getNodeRecord( node ).forReadingData();
            long[] labels = parseLabelsField( record ).get( nodeStore );
            return map( labelIdToLabelFunction, PrimitiveLongCollections.iterator( labels ) );
        };
    }

    @Override
    public Iterable<Label> getNodeLabels( final long node )
    {
        return new Iterable<Label>()
        {
            @Override
            public Iterator<Label> iterator()
            {
                NodeRecord record = getNodeRecord( node ).forReadingData();
                long[] labels = parseLabelsField( record ).get( nodeStore );
                return map( labelIdToLabelFunction, PrimitiveLongCollections.iterator( labels ) );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.unsafe.batchinsert.BatchInserterImpl.getNodeLabels.new Iterable<Label> with () -> {NodeRecord record=getNodeRecord(node).forReadingData(); in method public getNodeLabels(node long) : Iterable<Label> from class org.neo4j.unsafe.batchinsert.BatchInserterImpl


    @Override
    public Iterator<R> iterator()
    {
        return new CloningRecordIterator<>( actual.iterator() );
    }

    @Override
    public Iterator<R> iterator()
    {
        return new PrefetchingIterator<R>()
        {
            private final Iterator<R> actualIterator = actual.iterator();

            @Override
            protected R fetchNextOrNull()
            {
                return actualIterator.hasNext() ? (R) actualIterator.next().clone() : null;
            }
        };
    }

Replace Generic With Diamond PrefetchingIterator<R> with CloningRecordIterator<> in method public iterator() : Iterator<R> from class org.neo4j.consistency.checking.full.CloningRecordIterable


    @Test
    public void forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() throws Throwable
    {
        // Given
        ReentrantLock reentrantLock = new ReentrantLock();
        final Lock spyLock = spy( reentrantLock );

        doAnswer( invocation -> {
            verify( appender ).checkPoint( any( LogPosition.class ), any( LogCheckPointEvent.class ) );
            reset( appender );
            invocation.callRealMethod();
            return null;
        } ).when( spyLock ).unlock();

        final CheckPointerImpl checkPointing = checkPointer( spyLock );
        mockTxIdStore();

        final CountDownLatch startSignal = new CountDownLatch( 2 );
        final CountDownLatch completed = new CountDownLatch( 2 );

        checkPointing.start();

        Thread checkPointerThread = new CheckPointerThread( checkPointing, startSignal, completed );

        Thread forceCheckPointThread = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    startSignal.countDown();
                    startSignal.await();
                    checkPointing.forceCheckPoint( INFO );

                    completed.countDown();
                }
                catch ( Throwable e )
                {
                    throw new RuntimeException( e );
                }
            }
        };

        // when
        checkPointerThread.start();
        forceCheckPointThread.start();

        completed.await();

        verify( spyLock, times( 2 ) ).lock();
        verify( spyLock, times( 2 ) ).unlock();
    }

    @Test
    public void forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() throws Throwable
    {
        // Given
        ReentrantLock reentrantLock = new ReentrantLock();
        final Lock spyLock = spy( reentrantLock );

        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                verify( appender ).checkPoint( any( LogPosition.class ), any( LogCheckPointEvent.class ) );
                reset( appender );
                invocation.callRealMethod();
                return null;
            }
        } ).when( spyLock ).unlock();

        final CheckPointerImpl checkPointing = checkPointer( spyLock );
        mockTxIdStore();

        final CountDownLatch startSignal = new CountDownLatch( 2 );
        final CountDownLatch completed = new CountDownLatch( 2 );

        checkPointing.start();

        Thread checkPointerThread = new CheckPointerThread( checkPointing, startSignal, completed );

        Thread forceCheckPointThread = new Thread()
        {
            @Override
            public void run()
            {
                try
                {
                    startSignal.countDown();
                    startSignal.await();
                    checkPointing.forceCheckPoint( INFO );

                    completed.countDown();
                }
                catch ( Throwable e )
                {
                    throw new RuntimeException( e );
                }
            }
        };

        // when
        checkPointerThread.start();
        forceCheckPointThread.start();

        completed.await();

        verify( spyLock, times( 2 ) ).lock();
        verify( spyLock, times( 2 ) ).unlock();
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointerImplTest.forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning.unlock.when.doAnswer.new Answer with invocation -> {verify(appender).checkPoint(any(LogPosition.class),any(LogCheckPointEvent.class)); in method public forceCheckPointShouldWaitTheCurrentCheckPointingToCompleteBeforeRunning() : void from class org.neo4j.kernel.impl.transaction.log.checkpoint.CheckPointerImplTest


    private byte[] createCommands( String tokenName )
    {
        StorageEngine storageEngine = dependencies.resolveDependency( StorageEngine.class );
        Collection<StorageCommand> commands = new ArrayList<>();
        TransactionState txState = new TxState();
        int tokenId = Math.toIntExact( idGeneratorFactory.get( tokenIdType ).nextId() );
        createToken( txState, tokenName, tokenId );
        try ( StorageStatement statement = storageEngine.storeReadLayer().acquireStatement() )
        {
            storageEngine.createCommands( commands, txState, statement, ResourceLocker.NONE, Long.MAX_VALUE );
        }
        catch ( CreateConstraintFailureException | TransactionFailureException | ConstraintValidationKernelException e )
        {
            throw new RuntimeException( "Unable to create token '" + tokenName + "'", e );
        }

        return ReplicatedTokenRequestSerializer.commandBytes( commands );
    }

    private byte[] createCommands( String tokenName )
    {
        StorageEngine storageEngine = dependencies.resolveDependency( StorageEngine.class );
        Collection<StorageCommand> commands = new ArrayList<>();
        TransactionState txState = new TxState();
        int tokenId = Math.toIntExact( idGeneratorFactory.get( tokenIdType ).nextId() );
        createToken( txState, tokenName, tokenId );
        try
        {
            storageEngine.createCommands( commands, txState, ResourceLocker.NONE, Long.MAX_VALUE );
        }
        catch ( CreateConstraintFailureException | TransactionFailureException | ConstraintValidationKernelException e )
        {
            throw new RuntimeException( "Unable to create token '" + tokenName + "'", e );
        }

        return ReplicatedTokenRequestSerializer.commandBytes( commands );
    }

Try With Resources try(StorageStatement statement=storageEngine.storeReadLayer().acquireStatement()) in method private createCommands(tokenName String) : byte[] from class org.neo4j.coreedge.raft.replication.token.ReplicatedTokenHolder


    @Override
    public RecordKey<NodeRecord> node()
    {
        return ( written, read ) -> {
            assertEquals( written.getNextProp(), read.getNextProp() );
            assertEquals( written.getNextRel(), read.getNextRel() );
            assertEquals( written.getLabelField(), read.getLabelField() );
            assertEquals( written.isDense(), read.isDense() );
        };
    }

    @Override
    public RecordKey<NodeRecord> node()
    {
        return new RecordKey<NodeRecord>()
        {
            @Override
            public void assertRecordsEquals( NodeRecord written, NodeRecord read )
            {
                assertEquals( written.getNextProp(), read.getNextProp() );
                assertEquals( written.getNextRel(), read.getNextRel() );
                assertEquals( written.getLabelField(), read.getLabelField() );
                assertEquals( written.isDense(), read.isDense() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys.node.new RecordKey<NodeRecord> with (written, read) -> {assertEquals(written.getNextProp(),read.getNextProp()); in method public node() : RecordKey<NodeRecord> from class org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys


    @Override
    public RecordKey<RelationshipRecord> relationship()
    {
        return ( written, read ) -> {
            assertEquals( written.getNextProp(), read.getNextProp() );
            assertEquals( written.getFirstNode(), read.getFirstNode() );
            assertEquals( written.getSecondNode(), read.getSecondNode() );
            assertEquals( written.getType(), read.getType() );
            assertEquals( written.getFirstPrevRel(), read.getFirstPrevRel() );
            assertEquals( written.getFirstNextRel(), read.getFirstNextRel() );
            assertEquals( written.getSecondPrevRel(), read.getSecondPrevRel() );
            assertEquals( written.getSecondNextRel(), read.getSecondNextRel() );
            assertEquals( written.isFirstInFirstChain(), read.isFirstInFirstChain() );
            assertEquals( written.isFirstInSecondChain(), read.isFirstInSecondChain() );
        };
    }

    @Override
    public RecordKey<RelationshipRecord> relationship()
    {
        return new RecordKey<RelationshipRecord>()
        {
            @Override
            public void assertRecordsEquals( RelationshipRecord written, RelationshipRecord read )
            {
                assertEquals( written.getNextProp(), read.getNextProp() );
                assertEquals( written.getFirstNode(), read.getFirstNode() );
                assertEquals( written.getSecondNode(), read.getSecondNode() );
                assertEquals( written.getType(), read.getType() );
                assertEquals( written.getFirstPrevRel(), read.getFirstPrevRel() );
                assertEquals( written.getFirstNextRel(), read.getFirstNextRel() );
                assertEquals( written.getSecondPrevRel(), read.getSecondPrevRel() );
                assertEquals( written.getSecondNextRel(), read.getSecondNextRel() );
                assertEquals( written.isFirstInFirstChain(), read.isFirstInFirstChain() );
                assertEquals( written.isFirstInSecondChain(), read.isFirstInSecondChain() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys.relationship.new RecordKey<RelationshipRecord> with (written, read) -> {assertEquals(written.getNextProp(),read.getNextProp()); in method public relationship() : RecordKey<RelationshipRecord> from class org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys


    @Override
    public RecordKey<RelationshipGroupRecord> relationshipGroup()
    {
        return ( written, read ) -> {
            assertEquals( written.getType(), read.getType() );
            assertEquals( written.getFirstOut(), read.getFirstOut() );
            assertEquals( written.getFirstIn(), read.getFirstIn() );
            assertEquals( written.getFirstLoop(), read.getFirstLoop() );
            assertEquals( written.getNext(), read.getNext() );
            assertEquals( written.getOwningNode(), read.getOwningNode() );
        };
    }

    @Override
    public RecordKey<RelationshipGroupRecord> relationshipGroup()
    {
        return new RecordKey<RelationshipGroupRecord>()
        {
            @Override
            public void assertRecordsEquals( RelationshipGroupRecord written, RelationshipGroupRecord read )
            {
                assertEquals( written.getType(), read.getType() );
                assertEquals( written.getFirstOut(), read.getFirstOut() );
                assertEquals( written.getFirstIn(), read.getFirstIn() );
                assertEquals( written.getFirstLoop(), read.getFirstLoop() );
                assertEquals( written.getNext(), read.getNext() );
                assertEquals( written.getOwningNode(), read.getOwningNode() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys.relationshipGroup.new RecordKey<RelationshipGroupRecord> with (written, read) -> {assertEquals(written.getType(),read.getType()); in method public relationshipGroup() : RecordKey<RelationshipGroupRecord> from class org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys


    @Override
    public RecordKey<PropertyKeyTokenRecord> propertyKeyToken()
    {
        return ( written, read ) -> {
            assertEquals( written.getNameId(), read.getNameId() );
            assertEquals( written.getPropertyCount(), read.getPropertyCount() );
        };
    }

    @Override
    public RecordKey<PropertyKeyTokenRecord> propertyKeyToken()
    {
        return new RecordKey<PropertyKeyTokenRecord>()
        {
            @Override
            public void assertRecordsEquals( PropertyKeyTokenRecord written, PropertyKeyTokenRecord read )
            {
                assertEquals( written.getNameId(), read.getNameId() );
                assertEquals( written.getPropertyCount(), read.getPropertyCount() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys.propertyKeyToken.new RecordKey<PropertyKeyTokenRecord> with (written, read) -> {assertEquals(written.getNameId(),read.getNameId()); in method public propertyKeyToken() : RecordKey<PropertyKeyTokenRecord> from class org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys


    @Override
    public RecordKey<DynamicRecord> dynamic()
    {
        return ( written, read ) -> {
            // Don't assert type, since that's read from the data, and the data in this test
            // is randomly generated. Since we assert that the data is the same then the type
            // is also correct.
            assertEquals( written.getLength(), read.getLength() );
            assertEquals( written.getNextBlock(), read.getNextBlock() );
            assertArrayEquals( written.getData(), read.getData() );
            assertEquals( written.isStartRecord(), read.isStartRecord() );
        };
    }

    @Override
    public RecordKey<DynamicRecord> dynamic()
    {
        return new RecordKey<DynamicRecord>()
        {
            @Override
            public void assertRecordsEquals( DynamicRecord written, DynamicRecord read )
            {
                // Don't assert type, since that's read from the data, and the data in this test
                // is randomly generated. Since we assert that the data is the same then the type
                // is also correct.
                assertEquals( written.getLength(), read.getLength() );
                assertEquals( written.getNextBlock(), read.getNextBlock() );
                assertArrayEquals( written.getData(), read.getData() );
                assertEquals( written.isStartRecord(), read.isStartRecord() );
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys.dynamic.new RecordKey<DynamicRecord> with (written, read) -> {assertEquals(written.getLength(),read.getLength()); in method public dynamic() : RecordKey<DynamicRecord> from class org.neo4j.kernel.impl.store.format.FullyCoveringRecordKeys


    private NodeInUseWithCorrectLabelsCheck<LabelScanDocument, ConsistencyReport.LabelScanConsistencyReport> checker( long[] expectedLabels )
    {
        return new NodeInUseWithCorrectLabelsCheck<>( expectedLabels );
    }

    private NodeInUseWithCorrectLabelsCheck<LabelScanDocument, ConsistencyReport.LabelScanConsistencyReport> checker( long[] expectedLabels )
    {
        return new NodeInUseWithCorrectLabelsCheck<LabelScanDocument, ConsistencyReport.LabelScanConsistencyReport>( expectedLabels );
    }

Replace Generic With Diamond NodeInUseWithCorrectLabelsCheck<LabelScanDocument,ConsistencyReport.LabelScanConsistencyReport> with NodeInUseWithCorrectLabelsCheck<> in method private checker(expectedLabels long[]) : NodeInUseWithCorrectLabelsCheck<LabelScanDocument,ConsistencyReport.LabelScanConsistencyReport> from class org.neo4j.consistency.checking.full.NodeInUseWithCorrectLabelsCheckTest