    private void switchToMaster()
    {
        final CancellationHandle cancellationHandle = new CancellationHandle();
        startModeSwitching( () -> {
            if ( currentTargetState != HighAvailabilityMemberState.TO_MASTER )
            {
                return;
            }

            // We just got scheduled. Maybe we are already obsolete - test
            if ( cancellationHandle.cancellationRequested() )
            {
                msgLog.info( "Switch to master cancelled on start." );
                return;
            }

            componentSwitcher.switchToMaster();

            if ( cancellationHandle.cancellationRequested() )
            {
                msgLog.info( "Switch to master cancelled before ha communication started." );
                return;
            }

            haCommunicationLife.shutdown();
            haCommunicationLife = new LifeSupport();

            try
            {
                masterHaURI = switchToMaster.switchToMaster( haCommunicationLife, me );
                canAskForElections.set( true );
            }
            catch ( Throwable e )
            {
                msgLog.error( "Failed to switch to master", e );
                // Since this master switch failed, elect someone else
                election.demote( instanceId );
            }
        }, cancellationHandle );
    }

    private void switchToMaster()
    {
        final CancellationHandle cancellationHandle = new CancellationHandle();
        startModeSwitching( new Runnable()
        {
            @Override
            public void run()
            {
                if ( currentTargetState != HighAvailabilityMemberState.TO_MASTER )
                {
                    return;
                }

                // We just got scheduled. Maybe we are already obsolete - test
                if ( cancellationHandle.cancellationRequested() )
                {
                    msgLog.info( "Switch to master cancelled on start." );
                    return;
                }

                componentSwitcher.switchToMaster();

                if ( cancellationHandle.cancellationRequested() )
                {
                    msgLog.info( "Switch to master cancelled before ha communication started." );
                    return;
                }

                haCommunicationLife.shutdown();
                haCommunicationLife = new LifeSupport();

                try
                {
                    masterHaURI = switchToMaster.switchToMaster( haCommunicationLife, me );
                    canAskForElections.set( true );
                }
                catch ( Throwable e )
                {
                    msgLog.error( "Failed to switch to master", e );
                    // Since this master switch failed, elect someone else
                    election.demote( instanceId );
                }
            }
        }, cancellationHandle );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcher.switchToMaster.startModeSwitching.new Runnable with () -> {if(currentTargetState != HighAvailabilityMemberState.TO_MASTER){return; in method private switchToMaster() : void from class org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcher


    private void switchToPending( final HighAvailabilityMemberState oldState )
    {
        msgLog.info( "I am %s, moving to pending", instanceId );

        startModeSwitching( () -> {
            if ( cancellationHandle.cancellationRequested() )
            {
                msgLog.info( "Switch to pending cancelled on start." );
                return;
            }

            if ( oldState.equals( HighAvailabilityMemberState.SLAVE ) )
            {
                clusterMemberAvailability.memberIsUnavailable( SLAVE );
            }
            else if ( oldState.equals( HighAvailabilityMemberState.MASTER ) )
            {
                clusterMemberAvailability.memberIsUnavailable( MASTER );
            }

            componentSwitcher.switchToPending();
            neoStoreDataSourceSupplier.getDataSource().beforeModeSwitch();

            if ( cancellationHandle.cancellationRequested() )
            {
                msgLog.info( "Switch to pending cancelled before ha communication shutdown." );
                return;
            }

            haCommunicationLife.shutdown();
            haCommunicationLife = new LifeSupport();
        }, new CancellationHandle() );

        try
        {
            modeSwitcherFuture.get( 10, TimeUnit.SECONDS );
        }
        catch ( Exception ignored )
        {
        }
    }

    private void switchToPending( final HighAvailabilityMemberState oldState )
    {
        msgLog.info( "I am %s, moving to pending", instanceId );

        startModeSwitching( new Runnable()
        {
            @Override
            public void run()
            {
                if ( cancellationHandle.cancellationRequested() )
                {
                    msgLog.info( "Switch to pending cancelled on start." );
                    return;
                }

                if ( oldState.equals( HighAvailabilityMemberState.SLAVE ) )
                {
                    clusterMemberAvailability.memberIsUnavailable( SLAVE );
                }
                else if ( oldState.equals( HighAvailabilityMemberState.MASTER ) )
                {
                    clusterMemberAvailability.memberIsUnavailable( MASTER );
                }

                componentSwitcher.switchToPending();
                neoStoreDataSourceSupplier.getDataSource().beforeModeSwitch();

                if ( cancellationHandle.cancellationRequested() )
                {
                    msgLog.info( "Switch to pending cancelled before ha communication shutdown." );
                    return;
                }

                haCommunicationLife.shutdown();
                haCommunicationLife = new LifeSupport();
            }
        }, new CancellationHandle() );

        try
        {
            modeSwitcherFuture.get( 10, TimeUnit.SECONDS );
        }
        catch ( Exception ignored )
        {
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcher.switchToPending.startModeSwitching.new Runnable with () -> {if(cancellationHandle.cancellationRequested()){msgLog.info("Switch to pending cancelled on start."); in method private switchToPending(oldState HighAvailabilityMemberState) : void from class org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcher


    @Test
    public void shouldReswitchToSlaveIfNewMasterBecameElectedAndAvailableDuringSwitch() throws Throwable
    {
        // Given
        final CountDownLatch switching = new CountDownLatch( 1 );
        final CountDownLatch slaveAvailable = new CountDownLatch( 2 );
        final AtomicBoolean firstSwitch = new AtomicBoolean( true );
        ClusterMemberAvailability availability = mock( ClusterMemberAvailability.class );
        SwitchToSlave switchToSlave = mock( SwitchToSlave.class );
        @SuppressWarnings( "resource" )
        SwitchToMaster switchToMaster = mock( SwitchToMaster.class );

        when( switchToSlave.switchToSlave( any( LifeSupport.class ), any( URI.class ), any( URI.class ),
                any( CancellationRequest.class ) ) ).thenAnswer( invocationOnMock -> {
                    switching.countDown();
                    CancellationRequest cancel = (CancellationRequest) invocationOnMock.getArguments()[3];
                    if ( firstSwitch.get() )
                    {
                        while ( !cancel.cancellationRequested() )
                        {
                            Thread.sleep( 1 );
                        }
                        firstSwitch.set( false );
                    }
                    slaveAvailable.countDown();
                    return URI.create( "ha://slave" );
                } );

        HighAvailabilityModeSwitcher toTest = new HighAvailabilityModeSwitcher( switchToSlave, switchToMaster,
                mock( Election.class ), availability, mock( ClusterClient.class ), storeSupplierMock(),
                mock( InstanceId.class ), new ComponentSwitcherContainer(), neoStoreDataSourceSupplierMock(),
                NullLogService.getInstance() );
        toTest.init();
        toTest.start();
        toTest.listeningAt( URI.create( "ha://server3?serverId=3" ) );

        // When
        // This will start a switch to slave
        toTest.masterIsAvailable( new HighAvailabilityMemberChangeEvent( PENDING,
                TO_SLAVE, mock( InstanceId.class ), URI.create( "ha://server1" ) ) );
        // Wait until it starts and blocks on the cancellation request
        switching.await();
        // change the elected master, moving to pending, cancelling the previous change. This will block until the
        // previous switch is aborted
        toTest.masterIsElected( new HighAvailabilityMemberChangeEvent( TO_SLAVE, PENDING, new InstanceId( 2 ),
                URI.create( "ha://server2" ) ) );
        // Now move to the new master by switching to TO_SLAVE
        toTest.masterIsAvailable( new HighAvailabilityMemberChangeEvent( PENDING, TO_SLAVE, new InstanceId( 2 ),
                URI.create( "ha://server2" ) ) );

        // Then
        // The second switch must happen and this test won't block
        slaveAvailable.await();
    }

    @Test
    public void shouldReswitchToSlaveIfNewMasterBecameElectedAndAvailableDuringSwitch() throws Throwable
    {
        // Given
        final CountDownLatch switching = new CountDownLatch( 1 );
        final CountDownLatch slaveAvailable = new CountDownLatch( 2 );
        final AtomicBoolean firstSwitch = new AtomicBoolean( true );
        ClusterMemberAvailability availability = mock( ClusterMemberAvailability.class );
        SwitchToSlave switchToSlave = mock( SwitchToSlave.class );
        @SuppressWarnings( "resource" )
        SwitchToMaster switchToMaster = mock( SwitchToMaster.class );

        when( switchToSlave.switchToSlave( any( LifeSupport.class ), any( URI.class ), any( URI.class ),
                any( CancellationRequest.class ) ) ).thenAnswer( new Answer<URI>()
        {
            @Override
            public URI answer( InvocationOnMock invocationOnMock ) throws Throwable
            {
                switching.countDown();
                CancellationRequest cancel = (CancellationRequest) invocationOnMock.getArguments()[3];
                if ( firstSwitch.get() )
                {
                    while ( !cancel.cancellationRequested() )
                    {
                        Thread.sleep( 1 );
                    }
                    firstSwitch.set( false );
                }
                slaveAvailable.countDown();
                return URI.create( "ha://slave" );
            }
        } );

        HighAvailabilityModeSwitcher toTest = new HighAvailabilityModeSwitcher( switchToSlave, switchToMaster,
                mock( Election.class ), availability, mock( ClusterClient.class ), storeSupplierMock(),
                mock( InstanceId.class ), new ComponentSwitcherContainer(), neoStoreDataSourceSupplierMock(),
                NullLogService.getInstance() );
        toTest.init();
        toTest.start();
        toTest.listeningAt( URI.create( "ha://server3?serverId=3" ) );

        // When
        // This will start a switch to slave
        toTest.masterIsAvailable( new HighAvailabilityMemberChangeEvent( PENDING,
                TO_SLAVE, mock( InstanceId.class ), URI.create( "ha://server1" ) ) );
        // Wait until it starts and blocks on the cancellation request
        switching.await();
        // change the elected master, moving to pending, cancelling the previous change. This will block until the
        // previous switch is aborted
        toTest.masterIsElected( new HighAvailabilityMemberChangeEvent( TO_SLAVE, PENDING, new InstanceId( 2 ),
                URI.create( "ha://server2" ) ) );
        // Now move to the new master by switching to TO_SLAVE
        toTest.masterIsAvailable( new HighAvailabilityMemberChangeEvent( PENDING, TO_SLAVE, new InstanceId( 2 ),
                URI.create( "ha://server2" ) ) );

        // Then
        // The second switch must happen and this test won't block
        slaveAvailable.await();
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcherTest.shouldReswitchToSlaveIfNewMasterBecameElectedAndAvailableDuringSwitch.thenAnswer.new Answer<URI> with invocationOnMock -> {switching.countDown(); in method public shouldReswitchToSlaveIfNewMasterBecameElectedAndAvailableDuringSwitch() : void from class org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcherTest


            @Override
            ScheduledExecutorService createExecutor()
            {
                ScheduledExecutorService executor = mock( ScheduledExecutorService.class );

                doAnswer( invocation -> {
                    ((Runnable) invocation.getArguments()[0]).run();
                    modeSwitchHappened.countDown();
                    return mock( Future.class );
                } ).when( executor ).submit( any( Runnable.class ) );

                return executor;
            }

            @Override
            ScheduledExecutorService createExecutor()
            {
                ScheduledExecutorService executor = mock( ScheduledExecutorService.class );

                doAnswer( new Answer<Future<?>>()
                {
                    @Override
                    public Future<?> answer( InvocationOnMock invocation ) throws Throwable
                    {
                        ((Runnable) invocation.getArguments()[0]).run();
                        modeSwitchHappened.countDown();
                        return mock( Future.class );
                    }
                } ).when( executor ).submit( any( Runnable.class ) );

                return executor;
            }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcherTest.shouldAllowForcedElectionsAfterModeSwitch.modeSwitcher.new HighAvailabilityModeSwitcher.createExecutor.submit.when.doAnswer.new Answer<Future<?>> with invocation -> {((Runnable)invocation.getArguments()[0]).run(); in method package createExecutor() : ScheduledExecutorService from class org.neo4j.kernel.ha.cluster.modeswitch.HighAvailabilityModeSwitcherTest.shouldAllowForcedElectionsAfterModeSwitch.modeSwitcher.new HighAvailabilityModeSwitcher


        @Override
        public Integer call() throws Exception
        {
            final GraphDatabaseAPI db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(
                    storeDir.getAbsolutePath() ).setConfig( OnlineBackupSettings.online_backup_server,
                    backupHostname + ":" + backupPort ).setConfig( GraphDatabaseSettings.keep_logical_logs, "true" )
                    .newGraphDatabase();

            try
            {
                createIndex( db );
                createSomeData( db );
                rotateLogAndCheckPoint( db );

                final AtomicBoolean keepGoing = new AtomicBoolean( true );

                // when
                Dependencies dependencies = new Dependencies( db.getDependencyResolver() );
                dependencies.satisfyDependencies( new Config(), NullLogProvider.getInstance(), new Monitors() );

                LifeSupport life = new LifeSupport();
                try
                {
                    life.add( (OnlineBackupKernelExtension)
                            new OnlineBackupExtensionFactory().newKernelExtension(
                                    DependenciesProxy.dependencies( dependencies,
                                            OnlineBackupExtensionFactory.Dependencies.class ) ) );
                }
                catch ( Throwable e )
                {
                    throw new RuntimeException( e );
                }
                life.start();

                ExecutorService executor = Executors.newFixedThreadPool( 2 );
                executor.execute( () -> {
                    while ( keepGoing.get() && until.getAsBoolean() )
                    {
                        createSomeData( db );
                    }
                } );

                final AtomicInteger inconsistentDbs = new AtomicInteger( 0 );
                executor.submit( new Callable<Void>()
                {
                    private final BackupService backupService = new BackupService( fileSystem,
                            NullLogProvider.getInstance(), new Monitors() );

                    @Override
                    public Void call() throws IOException
                    {
                        while ( keepGoing.get() && until.getAsBoolean() )
                        {
                            fileSystem.deleteRecursively( backupDir );
                            BackupService.BackupOutcome backupOutcome = backupService.doFullBackup( backupHostname,
                                    backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.DEFAULT, new Config(),
                                    BackupClient.BIG_READ_TIMEOUT, false );

                            if ( !backupOutcome.isConsistent() )
                            {
                                keepGoing.set( false );
                                int num = inconsistentDbs.incrementAndGet();
                                File dir = new File( brokenDir, "" + num );
                                fileSystem.mkdir( dir );
                                fileSystem.copyRecursively( backupDir, dir );
                            }
                        }
                        return null;
                    }
                } );

                while ( keepGoing.get() && until.getAsBoolean() )
                {
                    Thread.sleep( 500 );
                }

                executor.shutdown();
                assertTrue( executor.awaitTermination( 30, TimeUnit.SECONDS ) );

                life.shutdown();

                return inconsistentDbs.get();
            }
            finally
            {
                db.shutdown();
            }
        }

        @Override
        public Integer call() throws Exception
        {
            final GraphDatabaseAPI db = (GraphDatabaseAPI) new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(
                    storeDir.getAbsolutePath() ).setConfig( OnlineBackupSettings.online_backup_server,
                    backupHostname + ":" + backupPort ).setConfig( GraphDatabaseSettings.keep_logical_logs, "true" )
                    .newGraphDatabase();

            try
            {
                createIndex( db );
                createSomeData( db );
                rotateLogAndCheckPoint( db );

                final AtomicBoolean keepGoing = new AtomicBoolean( true );

                // when
                Dependencies dependencies = new Dependencies( db.getDependencyResolver() );
                dependencies.satisfyDependencies( new Config(), NullLogProvider.getInstance(), new Monitors() );

                LifeSupport life = new LifeSupport();
                OnlineBackupKernelExtension backup;
                try
                {
                    backup = life.add( (OnlineBackupKernelExtension)
                            new OnlineBackupExtensionFactory().newKernelExtension(
                                    DependenciesProxy.dependencies( dependencies,
                                            OnlineBackupExtensionFactory.Dependencies.class ) ) );
                }
                catch ( Throwable e )
                {
                    throw new RuntimeException( e );
                }
                life.start();

                ExecutorService executor = Executors.newFixedThreadPool( 2 );
                executor.execute( new Runnable()
                {
                    @Override
                    public void run()
                    {
                        while ( keepGoing.get() && until.getAsBoolean() )
                        {
                            createSomeData( db );
                        }
                    }
                } );

                final AtomicInteger inconsistentDbs = new AtomicInteger( 0 );
                executor.submit( new Callable<Void>()
                {
                    private final BackupService backupService = new BackupService( fileSystem,
                            NullLogProvider.getInstance(), new Monitors() );

                    @Override
                    public Void call() throws IOException
                    {
                        while ( keepGoing.get() && until.getAsBoolean() )
                        {
                            fileSystem.deleteRecursively( backupDir );
                            BackupService.BackupOutcome backupOutcome = backupService.doFullBackup( backupHostname,
                                    backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.DEFAULT, new Config(),
                                    BackupClient.BIG_READ_TIMEOUT, false );

                            if ( !backupOutcome.isConsistent() )
                            {
                                keepGoing.set( false );
                                int num = inconsistentDbs.incrementAndGet();
                                File dir = new File( brokenDir, "" + num );
                                fileSystem.mkdir( dir );
                                fileSystem.copyRecursively( backupDir, dir );
                            }
                        }
                        return null;
                    }
                } );

                while ( keepGoing.get() && until.getAsBoolean() )
                {
                    Thread.sleep( 500 );
                }

                executor.shutdown();
                assertTrue( executor.awaitTermination( 30, TimeUnit.SECONDS ) );

                life.shutdown();

                return inconsistentDbs.get();
            }
            finally
            {
                db.shutdown();
            }
        }

Replace Anonymous With Lambda org.neo4j.backup.BackupServiceStressTestingBuilder.RunTest.call.execute.new Runnable with () -> {while(keepGoing.get() && until.getAsBoolean()){createSomeData(db); in method public call() : Integer from class org.neo4j.backup.BackupServiceStressTestingBuilder.RunTest


    public static GraphDatabaseDependencies newDependencies()
    {
        List<KernelExtensionFactory<?>> kernelExtensions = new ArrayList<>();
        for ( KernelExtensionFactory factory : Service.load( KernelExtensionFactory.class ) )
        {
            kernelExtensions.add( factory );
        }

        Map<String,URLAccessRule> urlAccessRules = new HashMap<>();
        urlAccessRules.put( "http", URLAccessRules.alwaysPermitted() );
        urlAccessRules.put( "https", URLAccessRules.alwaysPermitted() );
        urlAccessRules.put( "ftp", URLAccessRules.alwaysPermitted() );
        urlAccessRules.put( "file", URLAccessRules.fileAccess() );

        List<QueryEngineProvider> queryEngineProviders = toList( Service.load( QueryEngineProvider.class ) );

        return new GraphDatabaseDependencies( null, null, new ArrayList<>(), kernelExtensions,
                urlAccessRules, queryEngineProviders );
    }

    public static GraphDatabaseDependencies newDependencies()
    {
        List<KernelExtensionFactory<?>> kernelExtensions = new ArrayList<>();
        for ( KernelExtensionFactory factory : Service.load( KernelExtensionFactory.class ) )
        {
            kernelExtensions.add( factory );
        }

        Map<String,URLAccessRule> urlAccessRules = new HashMap<>();
        urlAccessRules.put( "http", URLAccessRules.alwaysPermitted() );
        urlAccessRules.put( "https", URLAccessRules.alwaysPermitted() );
        urlAccessRules.put( "ftp", URLAccessRules.alwaysPermitted() );
        urlAccessRules.put( "file", URLAccessRules.fileAccess() );

        List<QueryEngineProvider> queryEngineProviders = toList( Service.load( QueryEngineProvider.class ) );

        return new GraphDatabaseDependencies( null, null, new ArrayList<Class<?>>(), kernelExtensions,
                urlAccessRules, queryEngineProviders );
    }

Replace Generic With Diamond GraphDatabaseDependencies with GraphDatabaseDependencies in method public newDependencies() : GraphDatabaseDependencies from class org.neo4j.kernel.GraphDatabaseDependencies


        @Override
        public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull,
                                            Node endNodeOrNull )
        {
            return new ReadOnlyIndexHitsProxy<>( this, actual.get( key, valueOrNull,
                    startNodeOrNull, endNodeOrNull ) );
        }

        @Override
        public IndexHits<Relationship> get( String key, Object valueOrNull, Node startNodeOrNull,
                                            Node endNodeOrNull )
        {
            return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.get( key, valueOrNull,
                    startNodeOrNull, endNodeOrNull ) );
        }

Replace Generic With Diamond ReadOnlyIndexHitsProxy<Relationship> with ReadOnlyIndexHitsProxy<> in method public get(key String, valueOrNull Object, startNodeOrNull Node, endNodeOrNull Node) : IndexHits<Relationship> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.ReadOnlyRelationshipIndexProxy


        @Override
        public IndexHits<Relationship> query( String key, Object queryOrQueryObjectOrNull,
                                              Node startNodeOrNull, Node endNodeOrNull )
        {
            return new ReadOnlyIndexHitsProxy<>( this, actual.query( key,
                    queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) );
        }

        @Override
        public IndexHits<Relationship> query( String key, Object queryOrQueryObjectOrNull,
                                              Node startNodeOrNull, Node endNodeOrNull )
        {
            return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.query( key,
                    queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) );
        }

Replace Generic With Diamond ReadOnlyIndexHitsProxy<Relationship> with ReadOnlyIndexHitsProxy<> in method public query(key String, queryOrQueryObjectOrNull Object, startNodeOrNull Node, endNodeOrNull Node) : IndexHits<Relationship> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.ReadOnlyRelationshipIndexProxy


        @Override
        public IndexHits<Relationship> query( Object queryOrQueryObjectOrNull,
                                              Node startNodeOrNull, Node endNodeOrNull )
        {
            return new ReadOnlyIndexHitsProxy<>( this, actual.query(
                    queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) );
        }

        @Override
        public IndexHits<Relationship> query( Object queryOrQueryObjectOrNull,
                                              Node startNodeOrNull, Node endNodeOrNull )
        {
            return new ReadOnlyIndexHitsProxy<Relationship>( this, actual.query(
                    queryOrQueryObjectOrNull, startNodeOrNull, endNodeOrNull ) );
        }

Replace Generic With Diamond ReadOnlyIndexHitsProxy<Relationship> with ReadOnlyIndexHitsProxy<> in method public query(queryOrQueryObjectOrNull Object, startNodeOrNull Node, endNodeOrNull Node) : IndexHits<Relationship> from class org.neo4j.shell.kernel.ReadOnlyGraphDatabaseProxy.ReadOnlyRelationshipIndexProxy


    TopDocsIterator( Query query, QueryContext context, IndexSearcher searcher ) throws IOException
    {
        TopDocs docs = toTopDocs( query, context, searcher );
        this.size = docs.scoreDocs.length;
        this.iterator = new ArrayIterator<>( docs.scoreDocs );
        this.searcher = searcher;
    }

    TopDocsIterator( Query query, QueryContext context, IndexSearcher searcher ) throws IOException
    {
        TopDocs docs = toTopDocs( query, context, searcher );
        this.size = docs.scoreDocs.length;
        this.iterator = new ArrayIterator<ScoreDoc>( docs.scoreDocs );
        this.searcher = searcher;
    }

Replace Generic With Diamond ArrayIterator<ScoreDoc> with ArrayIterator<> in method package TopDocsIterator(query Query, context QueryContext, searcher IndexSearcher) from class org.neo4j.index.impl.lucene.legacy.TopDocsIterator


    private RestartAction corruptTheLabelScanStoreIndex()
    {
        return ( fs, storeDirectory ) -> {
            try
            {
                int filesCorrupted = 0;
                for ( File file : labelScanStoreIndexDirectory( storeDirectory ).listFiles() )
                {
                    scrambleFile( file );
                    filesCorrupted++;
                }
                assertTrue( "No files found to corrupt", filesCorrupted > 0 );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        };
    }

    private RestartAction corruptTheLabelScanStoreIndex()
    {
        return new RestartAction()
        {
            @Override
            public void run( FileSystemAbstraction fs, File storeDirectory )
            {
                try
                {
                    int filesCorrupted = 0;
                    for ( File file : labelScanStoreIndexDirectory( storeDirectory ).listFiles() )
                    {
                        scrambleFile( file );
                        filesCorrupted++;
                    }
                    assertTrue( "No files found to corrupt", filesCorrupted > 0 );
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.LuceneLabelScanStoreChaosIT.corruptTheLabelScanStoreIndex.new RestartAction with (fs, storeDirectory) -> {tryint filesCorrupted=0; in method private corruptTheLabelScanStoreIndex() : RestartAction from class org.neo4j.graphdb.LuceneLabelScanStoreChaosIT


    private RestartAction deleteTheLabelScanStoreIndex()
    {
        return ( fs, storeDirectory ) -> {
            try
            {
                File directory = labelScanStoreIndexDirectory( storeDirectory );
                assertTrue( "We seem to want to delete the wrong directory here", directory.exists() );
                assertTrue( "No index files to delete", directory.listFiles().length > 0 );
                deleteRecursively( directory );
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
        };
    }

    private RestartAction deleteTheLabelScanStoreIndex()
    {
        return new RestartAction()
        {
            @Override
            public void run( FileSystemAbstraction fs, File storeDirectory )
            {
                try
                {
                    File directory = labelScanStoreIndexDirectory( storeDirectory );
                    assertTrue( "We seem to want to delete the wrong directory here", directory.exists() );
                    assertTrue( "No index files to delete", directory.listFiles().length > 0 );
                    deleteRecursively( directory );
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.graphdb.LuceneLabelScanStoreChaosIT.deleteTheLabelScanStoreIndex.new RestartAction with (fs, storeDirectory) -> {tryFile directory=labelScanStoreIndexDirectory(storeDirectory); in method private deleteTheLabelScanStoreIndex() : RestartAction from class org.neo4j.graphdb.LuceneLabelScanStoreChaosIT


    @Test
    public void incrementalBackupShouldFailWhenTargetDirContainsDifferentStore() throws IOException
    {
        // Given
        defaultBackupPortHostParams();
        Config defaultConfig = dbRule.getConfigCopy();
        GraphDatabaseAPI db1 = dbRule.getGraphDatabaseAPI();
        createAndIndexNode( db1, 1 );

        backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE,
                defaultConfig, BackupClient.BIG_READ_TIMEOUT, false );

        // When
        GraphDatabaseAPI db2 = dbRule.restartDatabase( ( fs, storeDirectory ) -> {
            deleteAllBackedUpTransactionLogs();

            fileSystem.deleteRecursively( storeDir );
            fileSystem.mkdir( storeDir );
        } );
        createAndIndexNode( db2, 2 );

        try
        {
            backupService().doIncrementalBackupOrFallbackToFull( BACKUP_HOST, backupPort,
                    backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
                    BackupClient.BIG_READ_TIMEOUT, false );

            fail( "Should have thrown exception about mismatching store ids" );
        }
        catch ( RuntimeException e )
        {
            // Then
            assertThat( e.getMessage(), equalTo( BackupService.DIFFERENT_STORE ) );
            assertThat( e.getCause(), instanceOf( MismatchingStoreIdException.class ) );
        }
    }

    @Test
    public void incrementalBackupShouldFailWhenTargetDirContainsDifferentStore() throws IOException
    {
        // Given
        defaultBackupPortHostParams();
        Config defaultConfig = dbRule.getConfigCopy();
        GraphDatabaseAPI db1 = dbRule.getGraphDatabaseAPI();
        createAndIndexNode( db1, 1 );

        backupService().doFullBackup( BACKUP_HOST, backupPort, backupDir.getAbsoluteFile(), ConsistencyCheck.NONE,
                defaultConfig, BackupClient.BIG_READ_TIMEOUT, false );

        // When
        GraphDatabaseAPI db2 = dbRule.restartDatabase( new DatabaseRule.RestartAction()
        {
            @Override
            public void run( FileSystemAbstraction fs, File storeDirectory ) throws IOException
            {
                deleteAllBackedUpTransactionLogs();

                fileSystem.deleteRecursively( storeDir );
                fileSystem.mkdir( storeDir );
            }
        } );
        createAndIndexNode( db2, 2 );

        try
        {
            backupService().doIncrementalBackupOrFallbackToFull( BACKUP_HOST, backupPort,
                    backupDir.getAbsoluteFile(), ConsistencyCheck.NONE, defaultConfig,
                    BackupClient.BIG_READ_TIMEOUT, false );

            fail( "Should have thrown exception about mismatching store ids" );
        }
        catch ( RuntimeException e )
        {
            // Then
            assertThat( e.getMessage(), equalTo( BackupService.DIFFERENT_STORE ) );
            assertThat( e.getCause(), instanceOf( MismatchingStoreIdException.class ) );
        }
    }

Replace Anonymous With Lambda org.neo4j.backup.BackupServiceIT.incrementalBackupShouldFailWhenTargetDirContainsDifferentStore.db2.restartDatabase.new DatabaseRule.RestartAction with (fs, storeDirectory) -> {deleteAllBackedUpTransactionLogs(); in method public incrementalBackupShouldFailWhenTargetDirContainsDifferentStore() : void from class org.neo4j.backup.BackupServiceIT


    private LabelScanStorageStrategy.StorageService storage( Document... documents ) throws Exception
    {
        LabelScanStorageStrategy.StorageService storage = mock( LabelScanStorageStrategy.StorageService.class );
        IndexSearcher searcher = mock( IndexSearcher.class );
        when( storage.acquireSearcher() ).thenReturn( searcher );
        for ( int i = 0; i < documents.length; i++ )
        {
            final int docId = i;
            doAnswer( invocation -> {
                FirstHitCollector collector = (FirstHitCollector) invocation.getArguments()[1];
                try
                {
                   collector.collect( docId );
                }
                catch ( CollectionTerminatedException swallow )
                {
                    // swallow
                }
                return null;
            } ).when( searcher ).search(
                    eq( new TermQuery( format.rangeTerm( documents[i] ) ) ),
                    any( FirstHitCollector.class )
            );
            when( searcher.doc( i ) ).thenReturn( documents[i] );
        }
        return storage;
    }

    private LabelScanStorageStrategy.StorageService storage( Document... documents ) throws Exception
    {
        LabelScanStorageStrategy.StorageService storage = mock( LabelScanStorageStrategy.StorageService.class );
        IndexSearcher searcher = mock( IndexSearcher.class );
        when( storage.acquireSearcher() ).thenReturn( searcher );
        for ( int i = 0; i < documents.length; i++ )
        {
            final int docId = i;
            doAnswer( new Answer<Void>()
            {
                @Override
                public Void answer( InvocationOnMock invocation ) throws Throwable
                {
                    Collector collector = (Collector) invocation.getArguments()[1];
                    LeafCollector leafCollector = collector.getLeafCollector( null );
                    try
                    {
                        leafCollector.collect( docId );
                    }
                    catch ( CollectionTerminatedException swallow )
                    {
                        // swallow
                    }
                    return null;
                }
            } ).when( searcher ).search(
                    eq( new TermQuery( format.rangeTerm( documents[i] ) ) ),
                    any( Collector.class )
            );
            when( searcher.search( new TermQuery( format.rangeTerm( documents[i] ) ), 1 ) )
                    .thenReturn( docs( new ScoreDoc( i, 0.0f ) ) );
            when( searcher.doc( i ) ).thenReturn( documents[i] );
        }
        return storage;
    }

Replace Anonymous With Lambda org.neo4j.kernel.api.impl.index.NodeRangeDocumentLabelScanStorageStrategyTest.storage.search.when.doAnswer.new Answer<Void> with invocation -> {FirstHitCollector collector=(FirstHitCollector)invocation.getArguments()[1]; in method private storage(documents Document...) : LabelScanStorageStrategy.StorageService from class org.neo4j.kernel.api.impl.index.NodeRangeDocumentLabelScanStorageStrategyTest


        private ScoreDocsIterator( TopDocs docs, LeafReaderContext[] contexts )
        {
            this.contexts = contexts;
            this.iterator = new ArrayIterator<>( docs.scoreDocs );
            int segments = contexts.length;
            docStarts = new int[segments + 1];
            for ( int i = 0; i < segments; i++ )
            {
                LeafReaderContext context = contexts[i];
                docStarts[i] = context.docBase;
            }
            LeafReaderContext lastContext = contexts[segments - 1];
            docStarts[segments] = lastContext.docBase + lastContext.reader().maxDoc();
        }

        private ScoreDocsIterator( TopDocs docs, LeafReaderContext[] contexts )
        {
            this.contexts = contexts;
            this.iterator = new ArrayIterator<ScoreDoc>( docs.scoreDocs );
            int segments = contexts.length;
            docStarts = new int[segments + 1];
            for ( int i = 0; i < segments; i++ )
            {
                LeafReaderContext context = contexts[i];
                docStarts[i] = context.docBase;
            }
            LeafReaderContext lastContext = contexts[segments - 1];
            docStarts[segments] = lastContext.docBase + lastContext.reader().maxDoc();
        }

Replace Generic With Diamond ArrayIterator<ScoreDoc> with ArrayIterator<> in method private ScoreDocsIterator(docs TopDocs, contexts LeafReaderContext[]) from class org.neo4j.kernel.api.impl.index.DocValuesCollector.ScoreDocsIterator


    private void writeOperationsTable( StringBuilder beanInfo,
                                       MBeanOperationInfo[] operations, boolean nonHtml )
    {
        addNonHtmlCondition( beanInfo, nonHtml );
        beanInfo.append( "[options=\"header\", cols=\"23m,37,20m,20m\"]\n"
                + "|===\n"
                + "|Name|Description|ReturnType|Signature\n" );
        SortedSet<String> operationInfo = new TreeSet<>( String.CASE_INSENSITIVE_ORDER );
        for ( MBeanOperationInfo operInfo : operations )
        {
            StringBuilder operationRow = new StringBuilder( 512 );
            String type = getType( operInfo.getReturnType() );
            Descriptor descriptor = operInfo.getDescriptor();
            type = getCompositeType( type, descriptor, nonHtml );
            operationRow.append( '|' )
                    .append( operInfo.getName() )
                    .append( '|' )
                    .append( operInfo.getDescription()
                            .replace( '\n', ' ' ) )
                    .append( '|' )
                    .append( type )
                    .append( '|' );
            MBeanParameterInfo[] params = operInfo.getSignature();
            if ( params.length > 0 )
            {
                for ( int i = 0; i < params.length; i++ )
                {
                    MBeanParameterInfo param = params[i];
                    operationRow.append( param.getType() );
                    if ( i != (params.length - 1) )
                    {
                        operationRow.append( ',' );
                    }
                }
            }
            else
            {
                operationRow.append( "(no parameters)" );
            }
            operationRow.append( '\n' );
            operationInfo.add( operationRow.toString() );
        }
        for ( String row : operationInfo )
        {
            beanInfo.append( row );
        }
        beanInfo.append( "|===\n" );
        beanInfo.append( ENDIF );
    }

    private void writeOperationsTable( StringBuilder beanInfo,
                                       MBeanOperationInfo[] operations, boolean nonHtml )
    {
        addNonHtmlCondition( beanInfo, nonHtml );
        beanInfo.append( "[options=\"header\", cols=\"23m,37,20m,20m\"]\n"
                + "|===\n"
                + "|Name|Description|ReturnType|Signature\n" );
        SortedSet<String> operationInfo = new TreeSet<String>(
                String.CASE_INSENSITIVE_ORDER );
        for ( MBeanOperationInfo operInfo : operations )
        {
            StringBuilder operationRow = new StringBuilder( 512 );
            String type = getType( operInfo.getReturnType() );
            Descriptor descriptor = operInfo.getDescriptor();
            type = getCompositeType( type, descriptor, nonHtml );
            operationRow.append( '|' )
                    .append( operInfo.getName() )
                    .append( '|' )
                    .append( operInfo.getDescription()
                            .replace( '\n', ' ' ) )
                    .append( '|' )
                    .append( type )
                    .append( '|' );
            MBeanParameterInfo[] params = operInfo.getSignature();
            if ( params.length > 0 )
            {
                for ( int i = 0; i < params.length; i++ )
                {
                    MBeanParameterInfo param = params[i];
                    operationRow.append( param.getType() );
                    if ( i != (params.length - 1) )
                    {
                        operationRow.append( ',' );
                    }
                }
            }
            else
            {
                operationRow.append( "(no parameters)" );
            }
            operationRow.append( '\n' );
            operationInfo.add( operationRow.toString() );
        }
        for ( String row : operationInfo )
        {
            beanInfo.append( row );
        }
        beanInfo.append( "|===\n" );
        beanInfo.append( ENDIF );
    }

Replace Generic With Diamond TreeSet<String> with TreeSet<> in method private writeOperationsTable(beanInfo StringBuilder, operations MBeanOperationInfo[], nonHtml boolean) : void from class jmx.JmxDocTest


    private void applyToStore( TransactionToApply batch, CommitEvent commitEvent, TransactionApplicationMode mode )
            throws TransactionFailureException
    {
        try ( StoreApplyEvent storeApplyEvent = commitEvent.beginStoreApply() )
        {
            storageEngine.apply( batch, mode );
        }
        catch ( Throwable cause )
        {
            throw new TransactionFailureException( CouldNotCommit, cause,
                    "Could not apply the transaction to the store after written to log" );
        }
    }

    private void applyToStore( TransactionToApply batch, CommitEvent commitEvent, TransactionApplicationMode mode )
            throws TransactionFailureException
    {
        try
        {
            storageEngine.apply( batch, mode );
        }
        catch ( Throwable cause )
        {
            throw new TransactionFailureException( CouldNotCommit, cause,
                    "Could not apply the transaction to the store after written to log" );
        }
    }

Try With Resources try(StoreApplyEvent storeApplyEvent=commitEvent.beginStoreApply()) in method private applyToStore(batch TransactionToApply, commitEvent CommitEvent, mode TransactionApplicationMode) : void from class org.neo4j.kernel.impl.api.TransactionRepresentationCommitProcess


        private void prepareNextLevel()
        {
            Collection<Node> nodesToIterate = new ArrayList<>( this.nextNodes );
            this.nextNodes.clear();
            this.lastPath.setLength( currentDepth );
            this.nextRelationships = new NestingIterator<Relationship,Node>( nodesToIterate.iterator() )
            {
                @Override
                protected Iterator<Relationship> createNestedIterator( Node node )
                {
                    lastPath.setEndNode( node );
                    return expander.expand( lastPath, BranchState.NO_STATE ).iterator();
                }
            };
            this.currentDepth++;
            this.sharedCurrentDepth.value++;
        }

        private void prepareNextLevel()
        {
            Collection<Node> nodesToIterate = new ArrayList<Node>( filterNextLevelNodes( this.nextNodes ) );
            this.nextNodes.clear();
            this.lastPath.setLength( currentDepth );
            this.nextRelationships = new NestingIterator<Relationship,Node>( nodesToIterate.iterator() )
            {
                @Override
                protected Iterator<Relationship> createNestedIterator( Node node )
                {
                    lastPath.setEndNode( node );
                    return expander.expand( lastPath, BranchState.NO_STATE ).iterator();
                }
            };
            this.currentDepth++;
            this.sharedCurrentDepth.value++;
        }

Replace Generic With Diamond ArrayList<Node> with ArrayList<> in method private prepareNextLevel() : void from class org.neo4j.graphalgo.impl.path.ShortestPath.DirectionData


    public static Builder headersBuilder()
    {
        return new Builder( new HashMap<>() );
    }

    public static Builder headersBuilder()
    {
        return new Builder( new HashMap<HeaderField<?>, Object>() );
    }

Replace Generic With Diamond Builder with Builder in method public headersBuilder() : Builder from class org.neo4j.kernel.impl.store.kvstore.Headers


    private static TransactionCommitProcess newRememberingCommitProcess( final TransactionRepresentation[] slot )
            throws TransactionFailureException

    {
        TransactionCommitProcess commitProcess = mock( TransactionCommitProcess.class );

        when( commitProcess.commit(
                any( TransactionRepresentation.class ), any( LockGroup.class ), any( CommitEvent.class ),
                any( TransactionApplicationMode.class ) ) )
                .then( invocation -> {
                    slot[0] = ((TransactionRepresentation) invocation.getArguments()[0]);
                    return 1L;
                } );

        return commitProcess;
    }

    private static TransactionCommitProcess newRememberingCommitProcess( final TransactionRepresentation[] slot )
            throws TransactionFailureException

    {
        TransactionCommitProcess commitProcess = mock( TransactionCommitProcess.class );

        when( commitProcess.commit(
                any( TransactionRepresentation.class ), any( LockGroup.class ), any( CommitEvent.class ),
                any( TransactionApplicationMode.class ) ) )
                .then( new Answer<Long>()
                {
                    @Override
                    public Long answer( InvocationOnMock invocation ) throws Throwable
                    {
                        slot[0] = ((TransactionRepresentation) invocation.getArguments()[0]);
                        return 1L;
                    }
                } );

        return commitProcess;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.KernelTransactionsTest.newRememberingCommitProcess.then.new Answer<Long> with invocation -> {slot[0]=((TransactionRepresentation)invocation.getArguments()[0]); in method private newRememberingCommitProcess(slot TransactionRepresentation[]) : TransactionCommitProcess from class org.neo4j.kernel.impl.api.KernelTransactionsTest


    /**
     * Throws cause of store not being OK.
     */
    public void verifyStoreOk()
    {
        visitStore( element -> {
            element.checkStoreOk();
            return false;
        } );
    }

    /**
     * Throws cause of store not being OK.
     */
    public void verifyStoreOk()
    {
        visitStore( new Visitor<CommonAbstractStore,RuntimeException>()
        {
            @Override
            public boolean visit( CommonAbstractStore element )
            {
                element.checkStoreOk();
                return false;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.NeoStores.verifyStoreOk.visitStore.new Visitor<CommonAbstractStore,RuntimeException> with element -> {element.checkStoreOk(); in method public verifyStoreOk() : void from class org.neo4j.kernel.impl.store.NeoStores


    public void deleteIdGenerators()
    {
        visitStore( store -> {
            store.deleteIdGenerator();
            return false;
        } );
    }

    public void deleteIdGenerators()
    {
        visitStore( new Visitor<CommonAbstractStore, RuntimeException>()
        {
            @Override
            public boolean visit( CommonAbstractStore store ) throws RuntimeException
            {
                store.deleteIdGenerator();
                return false;
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.store.NeoStores.deleteIdGenerators.visitStore.new Visitor<CommonAbstractStore,RuntimeException> with store -> {store.deleteIdGenerator(); in method public deleteIdGenerators() : void from class org.neo4j.kernel.impl.store.NeoStores


    @Before
    public void setUpNeoStores() throws Exception
    {
        storeDir = dir.graphDbDir();
        Config config = new Config( new HashMap<>(), GraphDatabaseSettings.class );
        pageCache = pageCacheRule.getPageCache( fs.get() );
        StoreFactory sf = new StoreFactory( storeDir, config, new DefaultIdGeneratorFactory( fs.get() ), pageCache,
                fs.get(), NullLogProvider.getInstance() );
        sf.openAllNeoStores( true ).close();
    }

    @Before
    public void setUpNeoStores() throws Exception
    {
        storeDir = dir.graphDbDir();
        Config config = new Config( new HashMap<String, String>(), GraphDatabaseSettings.class );
        pageCache = pageCacheRule.getPageCache( fs.get() );
        StoreFactory sf = new StoreFactory( storeDir, config, new DefaultIdGeneratorFactory( fs.get() ), pageCache,
                fs.get(), NullLogProvider.getInstance() );
        sf.openAllNeoStores( true ).close();
    }

Replace Generic With Diamond Config with Config in method public setUpNeoStores() : void from class org.neo4j.kernel.impl.store.NeoStoresTest


    @Test
    public void impossibleToGetStoreFromClosedNeoStoresContainer()
    {
        Config config = new Config( new HashMap<>(), GraphDatabaseSettings.class );
        StoreFactory sf = new StoreFactory( storeDir, config, new DefaultIdGeneratorFactory( fs.get() ), pageCache,
                fs.get(), NullLogProvider.getInstance() );
        NeoStores neoStores = sf.openAllNeoStores( true );

        assertNotNull( neoStores.getMetaDataStore() );

        neoStores.close();

        exception.expect( IllegalStateException.class );
        exception.expectMessage( "Specified store was already closed.");
        neoStores.getMetaDataStore();
    }

    @Test
    public void impossibleToGetStoreFromClosedNeoStoresContainer()
    {
        Config config = new Config( new HashMap<String, String>(), GraphDatabaseSettings.class );
        StoreFactory sf = new StoreFactory( storeDir, config, new DefaultIdGeneratorFactory( fs.get() ), pageCache,
                fs.get(), NullLogProvider.getInstance() );
        NeoStores neoStores = sf.openAllNeoStores( true );

        assertNotNull( neoStores.getMetaDataStore() );

        neoStores.close();

        exception.expect( IllegalStateException.class );
        exception.expectMessage( "Specified store was already closed.");
        neoStores.getMetaDataStore();
    }

Replace Generic With Diamond Config with Config in method public impossibleToGetStoreFromClosedNeoStoresContainer() : void from class org.neo4j.kernel.impl.store.NeoStoresTest


    @Test
    public void shouldReturnAllValueTypesContainedInTheIndex1() throws Exception
    {
        // Given
        when( terms.next() ).thenReturn( true, true, true, false );
        when( terms.term() ).thenReturn( new Term( "array" ), new Term( "string" ), new Term( "array" ) );

        // When
        final Set<Class> types = accessor.valueTypesInIndex();

        // Then

        assertEquals( new HashSet<>( Arrays.asList( Array.class, String.class ) ), types );
    }

    @Test
    public void shouldReturnAllValueTypesContainedInTheIndex1() throws Exception
    {
        // Given
        when( terms.next() ).thenReturn( true, true, true, false );
        when( terms.term() ).thenReturn( new Term( "array" ), new Term( "string" ), new Term( "array" ) );

        // When
        final Set<Class> types = accessor.valueTypesInIndex();

        // Then

        assertEquals( new HashSet<Class>( Arrays.asList( Array.class, String.class ) ), types );
    }

Replace Generic With Diamond HashSet<Class> with HashSet<> in method public shouldReturnAllValueTypesContainedInTheIndex1() : void from class org.neo4j.kernel.api.impl.index.LuceneIndexAccessorReaderTest


    @Test
    public void shouldReturnAllValueTypesContainedInTheIndex2() throws Exception
    {
        // Given
        when( terms.next() ).thenReturn( true, true, true, true, false );
        when( terms.term() )
                .thenReturn( new Term( "array" ), new Term( "number" ), new Term( "string" ), new Term( "bool" ) );

        // When
        final Set<Class> types = accessor.valueTypesInIndex();

        // Then
        assertEquals( new HashSet<>( Arrays.asList( Array.class, Number.class, String.class, Boolean.class ) ), types );
    }

    @Test
    public void shouldReturnAllValueTypesContainedInTheIndex2() throws Exception
    {
        // Given
        when( terms.next() ).thenReturn( true, true, true, true, false );
        when( terms.term() )
                .thenReturn( new Term( "array" ), new Term( "number" ), new Term( "string" ), new Term( "bool" ) );

        // When
        final Set<Class> types = accessor.valueTypesInIndex();

        // Then
        assertEquals( new HashSet<Class>( Arrays.asList( Array.class, Number.class, String.class, Boolean.class ) ), types );
    }

Replace Generic With Diamond HashSet<Class> with HashSet<> in method public shouldReturnAllValueTypesContainedInTheIndex2() : void from class org.neo4j.kernel.api.impl.index.LuceneIndexAccessorReaderTest


    protected Runnable $close( final PagedFile file )
    {
        return () -> {
            try
            {
                file.close();
            }
            catch ( IOException e )
            {
                throw new AssertionError( e );
            }
        };
    }

    protected Runnable $close( final PagedFile file )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    file.close();
                }
                catch ( IOException e )
                {
                    throw new AssertionError( e );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.$close.new Runnable with () -> {tryfile.close(); in method protected $close(file PagedFile) : Runnable from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = SHORT_TIMEOUT_MILLIS )
    public void mustNotPinPagesAfterNextReturnsFalse() throws Exception
    {
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        final CountDownLatch unpinLatch = new CountDownLatch( 1 );
        final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
        generateFileWithRecords( file( "a" ), recordsPerFilePage, recordSize );
        final PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );
        final PagedFile pagedFile = cache.map( file( "a" ), filePageSize );

        Runnable runnable = () -> {
            try ( PageCursor cursorA = pagedFile.io( 0, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
            {
                assertTrue( cursorA.next() );
                assertFalse( cursorA.next() );
                startLatch.countDown();
                unpinLatch.await();
                cursorA.close();
            }
            catch ( Exception e )
            {
                exceptionRef.set( e );
            }
        };
        executor.submit( runnable );

        startLatch.await();
        try ( PageCursor cursorB = pagedFile.io( 1, PF_EXCLUSIVE_LOCK ) )
        {
            assertTrue( cursorB.next() );
            unpinLatch.countDown();
        }
        finally
        {
            pagedFile.close();
        }
        Exception e = exceptionRef.get();
        if ( e != null )
        {
            throw new Exception( "Child thread got exception", e );
        }
    }

    @Test( timeout = SHORT_TIMEOUT_MILLIS )
    public void mustNotPinPagesAfterNextReturnsFalse() throws Exception
    {
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        final CountDownLatch unpinLatch = new CountDownLatch( 1 );
        final AtomicReference<Exception> exceptionRef = new AtomicReference<>();
        generateFileWithRecords( file( "a" ), recordsPerFilePage, recordSize );
        final PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );
        final PagedFile pagedFile = cache.map( file( "a" ), filePageSize );

        Runnable runnable = new Runnable()
        {
            @Override
            public void run()
            {
                try ( PageCursor cursorA = pagedFile.io( 0, PF_EXCLUSIVE_LOCK | PF_NO_GROW ) )
                {
                    assertTrue( cursorA.next() );
                    assertFalse( cursorA.next() );
                    startLatch.countDown();
                    unpinLatch.await();
                    cursorA.close();
                }
                catch ( Exception e )
                {
                    exceptionRef.set( e );
                }
            }
        };
        executor.submit( runnable );

        startLatch.await();
        try ( PageCursor cursorB = pagedFile.io( 1, PF_EXCLUSIVE_LOCK ) )
        {
            assertTrue( cursorB.next() );
            unpinLatch.countDown();
        }
        finally
        {
            pagedFile.close();
        }
        Exception e = exceptionRef.get();
        if ( e != null )
        {
            throw new Exception( "Child thread got exception", e );
        }
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.mustNotPinPagesAfterNextReturnsFalse.runnable.new Runnable with () -> {try(PageCursor cursorA=pagedFile.io(0,PF_EXCLUSIVE_LOCK | PF_NO_GROW))assertTrue(cursorA.next()); in method public mustNotPinPagesAfterNextReturnsFalse() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = SHORT_TIMEOUT_MILLIS )
    public void retryMustResetCursorOffset() throws Exception
    {
        // The general idea here, is that we have a page with a particular value in its 0th position.
        // We also have a thread that constantly writes to the middle of the page, so it modifies
        // the page, but does not change the value in the 0th position. This thread will in principle
        // mean that it is possible for a reader to get an inconsistent view and must retry.
        // We then check that every retry iteration will read the special value in the 0th position.
        // We repeat the experiment a couple of times to make sure we didn't succeed by chance.

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );
        final PagedFile pagedFile = cache.map( file( "a" ), filePageSize );
        final AtomicReference<Exception> caughtWriterException = new AtomicReference<>();
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        final byte expectedByte = (byte) 13;

        try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
        {
            if ( cursor.next() )
            {
                do
                {
                    cursor.putByte( expectedByte );
                } while ( cursor.shouldRetry() );
            }
        }

        Runnable writer = () -> {
            while ( !Thread.currentThread().isInterrupted() )
            {
                try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
                {
                    if ( cursor.next() )
                    {
                        do
                        {
                            cursor.setOffset( recordSize );
                            cursor.putByte( (byte) 14 );
                        } while ( cursor.shouldRetry() );
                    }
                    startLatch.countDown();
                }
                catch ( IOException e )
                {
                    caughtWriterException.set( e );
                    throw new RuntimeException( e );
                }
            }
        };
        Future<?> writerFuture = executor.submit( writer );

        startLatch.await();

        for ( int i = 0; i < 1000; i++ )
        {
            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                do
                {
                    assertThat( cursor.getByte(), is( expectedByte ) );
                } while ( cursor.shouldRetry() );
            }
        }

        writerFuture.cancel( true );
        pagedFile.close();
    }

    @Test( timeout = SHORT_TIMEOUT_MILLIS )
    public void retryMustResetCursorOffset() throws Exception
    {
        // The general idea here, is that we have a page with a particular value in its 0th position.
        // We also have a thread that constantly writes to the middle of the page, so it modifies
        // the page, but does not change the value in the 0th position. This thread will in principle
        // mean that it is possible for a reader to get an inconsistent view and must retry.
        // We then check that every retry iteration will read the special value in the 0th position.
        // We repeat the experiment a couple of times to make sure we didn't succeed by chance.

        PageCache cache = getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );
        final PagedFile pagedFile = cache.map( file( "a" ), filePageSize );
        final AtomicReference<Exception> caughtWriterException = new AtomicReference<>();
        final CountDownLatch startLatch = new CountDownLatch( 1 );
        final byte expectedByte = (byte) 13;

        try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
        {
            if ( cursor.next() )
            {
                do
                {
                    cursor.putByte( expectedByte );
                } while ( cursor.shouldRetry() );
            }
        }

        Runnable writer = new Runnable()
        {
            @Override
            public void run()
            {
                while ( !Thread.currentThread().isInterrupted() )
                {
                    try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
                    {
                        if ( cursor.next() )
                        {
                            do
                            {
                                cursor.setOffset( recordSize );
                                cursor.putByte( (byte) 14 );
                            } while ( cursor.shouldRetry() );
                        }
                        startLatch.countDown();
                    }
                    catch ( IOException e )
                    {
                        caughtWriterException.set( e );
                        throw new RuntimeException( e );
                    }
                }
            }
        };
        Future<?> writerFuture = executor.submit( writer );

        startLatch.await();

        for ( int i = 0; i < 1000; i++ )
        {
            try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
            {
                assertTrue( cursor.next() );
                do
                {
                    assertThat( cursor.getByte(), is( expectedByte ) );
                } while ( cursor.shouldRetry() );
            }
        }

        writerFuture.cancel( true );
        pagedFile.close();
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.retryMustResetCursorOffset.writer.new Runnable with () -> {while(!Thread.currentThread().isInterrupted()){try(PageCursor cursor=pagedFile.io(0,PF_EXCLUSIVE_LOCK))if(cursor.next()){do(cursor.shouldRetry()){cursor.setOffset(recordSize); in method public retryMustResetCursorOffset() : void from class org.neo4j.io.pagecache.PageCacheTest


    @RepeatRule.Repeat( times = 10 )
    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void readsAndWritesMustBeMutuallyConsistent() throws Exception
    {
        // The idea is this: have a range of pages and we set off a bunch of threads to
        // do writes within a small region of the page set. The writes they'll perform
        // is to fill a random page within the region, with the same random byte value.
        // We then have our main thread scan through all the pages over and over, and
        // check that all pages can be read consistently, such that all the bytes in a
        // given page have the same value. We do this check many times, because the
        // test is inherently about catching data races in the act.

        final int pageCount = 100;
        int writerThreads = 8;
        final CountDownLatch startLatch = new CountDownLatch( writerThreads );
        final CountDownLatch writersDoneLatch = new CountDownLatch( writerThreads );
        List<Future<?>> writers = new ArrayList<>();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );
        final PagedFile pagedFile = pageCache.map( file( "a" ), filePageSize );

        // zero-fill the file
        try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
        {
            for ( int i = 0; i < pageCount; i++ )
            {
                assertTrue( cursor.next() );
            }
        }

        Runnable writer = () -> {
            try
            {
                int pageRangeMin = pageCount / 2;
                int pageRangeMax = pageRangeMin + 5;
                ThreadLocalRandom rng = ThreadLocalRandom.current();
                int[] offsets = new int[filePageSize];
                for ( int i = 0; i < offsets.length; i++ )
                {
                    offsets[i] = i;
                }

                startLatch.countDown();

                while ( !Thread.interrupted() )
                {
                    byte value = (byte) rng.nextInt();
                    int pageId = rng.nextInt( pageRangeMin, pageRangeMax );
                    // shuffle offsets
                    for ( int i = 0; i < offsets.length; i++ )
                    {
                        int j = rng.nextInt( i, offsets.length );
                        int s = offsets[i];
                        offsets[i] = offsets[j];
                        offsets[j] = s;
                    }
                    // fill page
                    try ( PageCursor cursor = pagedFile.io( pageId, PF_EXCLUSIVE_LOCK ) )
                    {
                        if ( cursor.next() )
                        {
                            do
                            {
                                for ( int offset : offsets )
                                {
                                    cursor.setOffset( offset );
                                    cursor.putByte( value );
                                }
                            } while ( cursor.shouldRetry() );
                        }
                    }
                }
            }
            catch ( IOException e )
            {
                throw new RuntimeException( e );
            }
            finally
            {
                writersDoneLatch.countDown();
            }
        };

        for ( int i = 0; i < writerThreads; i++ )
        {
            writers.add( executor.submit( writer ) );
        }

        startLatch.await();

        try
        {
            for ( int i = 0; i < 2000; i++ )
            {
                int countedConsistentPageReads = 0;
                try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
                {
                    while ( cursor.next() )
                    {
                        boolean consistent;
                        do
                        {
                            consistent = true;
                            byte first = cursor.getByte();
                            for ( int j = 1; j < filePageSize; j++ )
                            {
                                byte b = cursor.getByte();
                                consistent = consistent && b == first;
                            }
                        } while ( cursor.shouldRetry() );
                        assertTrue( "checked consistency at itr " + i, consistent );
                        countedConsistentPageReads++;
                    }
                }
                assertThat( countedConsistentPageReads, is( pageCount ) );
            }

            for ( Future<?> future : writers )
            {
                if ( future.isDone() )
                {
                    future.get();
                }
                else
                {
                    future.cancel( true );
                }
            }
            writersDoneLatch.await();
        }
        finally
        {
            pagedFile.close();
        }
    }

    @RepeatRule.Repeat( times = 10 )
    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void readsAndWritesMustBeMutuallyConsistent() throws Exception
    {
        // The idea is this: have a range of pages and we set off a bunch of threads to
        // do writes within a small region of the page set. The writes they'll perform
        // is to fill a random page within the region, with the same random byte value.
        // We then have our main thread scan through all the pages over and over, and
        // check that all pages can be read consistently, such that all the bytes in a
        // given page have the same value. We do this check many times, because the
        // test is inherently about catching data races in the act.

        final int pageCount = 100;
        int writerThreads = 8;
        final CountDownLatch startLatch = new CountDownLatch( writerThreads );
        final CountDownLatch writersDoneLatch = new CountDownLatch( writerThreads );
        List<Future<?>> writers = new ArrayList<>();

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );
        final PagedFile pagedFile = pageCache.map( file( "a" ), filePageSize );

        // zero-fill the file
        try ( PageCursor cursor = pagedFile.io( 0, PF_EXCLUSIVE_LOCK ) )
        {
            for ( int i = 0; i < pageCount; i++ )
            {
                assertTrue( cursor.next() );
            }
        }

        Runnable writer = new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    int pageRangeMin = pageCount / 2;
                    int pageRangeMax = pageRangeMin + 5;
                    ThreadLocalRandom rng = ThreadLocalRandom.current();
                    int[] offsets = new int[filePageSize];
                    for ( int i = 0; i < offsets.length; i++ )
                    {
                        offsets[i] = i;
                    }

                    startLatch.countDown();

                    while ( !Thread.interrupted() )
                    {
                        byte value = (byte) rng.nextInt();
                        int pageId = rng.nextInt( pageRangeMin, pageRangeMax );
                        // shuffle offsets
                        for ( int i = 0; i < offsets.length; i++ )
                        {
                            int j = rng.nextInt( i, offsets.length );
                            int s = offsets[i];
                            offsets[i] = offsets[j];
                            offsets[j] = s;
                        }
                        // fill page
                        try ( PageCursor cursor = pagedFile.io( pageId, PF_EXCLUSIVE_LOCK ) )
                        {
                            if ( cursor.next() )
                            {
                                do
                                {
                                    for ( int offset : offsets )
                                    {
                                        cursor.setOffset( offset );
                                        cursor.putByte( value );
                                    }
                                } while ( cursor.shouldRetry() );
                            }
                        }
                    }
                }
                catch ( IOException e )
                {
                    throw new RuntimeException( e );
                }
                finally
                {
                    writersDoneLatch.countDown();
                }
            }
        };

        for ( int i = 0; i < writerThreads; i++ )
        {
            writers.add( executor.submit( writer ) );
        }

        startLatch.await();

        try
        {
            for ( int i = 0; i < 2000; i++ )
            {
                int countedConsistentPageReads = 0;
                try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
                {
                    while ( cursor.next() )
                    {
                        boolean consistent;
                        do
                        {
                            consistent = true;
                            byte first = cursor.getByte();
                            for ( int j = 1; j < filePageSize; j++ )
                            {
                                byte b = cursor.getByte();
                                consistent = consistent && b == first;
                            }
                        } while ( cursor.shouldRetry() );
                        assertTrue( "checked consistency at itr " + i, consistent );
                        countedConsistentPageReads++;
                    }
                }
                assertThat( countedConsistentPageReads, is( pageCount ) );
            }

            for ( Future<?> future : writers )
            {
                if ( future.isDone() )
                {
                    future.get();
                }
                else
                {
                    future.cancel( true );
                }
            }
            writersDoneLatch.await();
        }
        finally
        {
            pagedFile.close();
        }
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.readsAndWritesMustBeMutuallyConsistent.writer.new Runnable with () -> {tryint pageRangeMin=pageCount / 2; in method public readsAndWritesMustBeMutuallyConsistent() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void optimisticReadLockMustFaultOnRetryIfPageHasBeenEvicted() throws Exception
    {
        final byte a = 'a';
        final byte b = 'b';
        final File fileA = existingFile( "a" );
        final File fileB = existingFile( "b" );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );

        final PagedFile pagedFileA = pageCache.map( fileA, filePageSize );
        final PagedFile pagedFileB = pageCache.map( fileB, filePageSize );

        // Fill fileA with some predicable data
        try ( PageCursor cursor = pagedFileA.io( 0, PF_EXCLUSIVE_LOCK ) )
        {
            for ( int i = 0; i < maxPages; i++ )
            {
                assertTrue( cursor.next() );
                for ( int j = 0; j < filePageSize; j++ )
                {
                    cursor.putByte( a );
                }
            }
        }

        Runnable fillPagedFileB = () -> {
            try ( PageCursor cursor = pagedFileB.io( 0, PF_EXCLUSIVE_LOCK ) )
            {
                for ( int i = 0; i < maxPages * 30; i++ )
                {
                    assertTrue( cursor.next() );
                    for ( int j = 0; j < filePageSize; j++ )
                    {
                        cursor.putByte( b );
                    }
                }
            }
            catch ( IOException e )
            {
                e.printStackTrace();
            }
        };

        try ( PageCursor cursor = pagedFileA.io( 0, PF_SHARED_LOCK ) )
        {
            // First, make sure page 0 is in the cache:
            assertTrue( cursor.next( 0 ) );
            // If we took a page fault, we'd have a pessimistic lock on page 0.
            // Move to the next page to release that lock:
            assertTrue( cursor.next() );
            // Now go back to page 0. It's still in the cache, so we should get
            // an optimistic lock, if that's available:
            assertTrue( cursor.next( 0 ) );

            // Verify the page is all 'a's:
            for ( int i = 0; i < filePageSize; i++ )
            {
                assertThat( cursor.getByte(), is( a ) );
            }

            // Now fill file B with 'b's... this will cause our current page to be evicted
            fork( fillPagedFileB ).join();
            // So if we had an optimistic lock, we should be asked to retry:
            if ( cursor.shouldRetry() )
            {
                // When we do reads after the shouldRetry() call, we should fault our page back
                // and get consistent reads (assuming we don't race any further with eviction)
                int expected = a * filePageSize;
                int actual;
                do
                {
                    actual = 0;
                    for ( int i = 0; i < filePageSize; i++ )
                    {
                        actual += cursor.getByte();
                    }
                }
                while ( cursor.shouldRetry() );
                assertThat( actual, is( expected ) );
            }
        }

        pagedFileA.close();
        pagedFileB.close();
    }

    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void optimisticReadLockMustFaultOnRetryIfPageHasBeenEvicted() throws Exception
    {
        final byte a = 'a';
        final byte b = 'b';
        final File fileA = existingFile( "a" );
        final File fileB = existingFile( "b" );

        getPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );

        final PagedFile pagedFileA = pageCache.map( fileA, filePageSize );
        final PagedFile pagedFileB = pageCache.map( fileB, filePageSize );

        // Fill fileA with some predicable data
        try ( PageCursor cursor = pagedFileA.io( 0, PF_EXCLUSIVE_LOCK ) )
        {
            for ( int i = 0; i < maxPages; i++ )
            {
                assertTrue( cursor.next() );
                for ( int j = 0; j < filePageSize; j++ )
                {
                    cursor.putByte( a );
                }
            }
        }

        Runnable fillPagedFileB = new Runnable()
        {
            @Override
            public void run()
            {
                try ( PageCursor cursor = pagedFileB.io( 0, PF_EXCLUSIVE_LOCK ) )
                {
                    for ( int i = 0; i < maxPages * 30; i++ )
                    {
                        assertTrue( cursor.next() );
                        for ( int j = 0; j < filePageSize; j++ )
                        {
                            cursor.putByte( b );
                        }
                    }
                }
                catch ( IOException e )
                {
                    e.printStackTrace();
                }
            }
        };

        try ( PageCursor cursor = pagedFileA.io( 0, PF_SHARED_LOCK ) )
        {
            // First, make sure page 0 is in the cache:
            assertTrue( cursor.next( 0 ) );
            // If we took a page fault, we'd have a pessimistic lock on page 0.
            // Move to the next page to release that lock:
            assertTrue( cursor.next() );
            // Now go back to page 0. It's still in the cache, so we should get
            // an optimistic lock, if that's available:
            assertTrue( cursor.next( 0 ) );

            // Verify the page is all 'a's:
            for ( int i = 0; i < filePageSize; i++ )
            {
                assertThat( cursor.getByte(), is( a ) );
            }

            // Now fill file B with 'b's... this will cause our current page to be evicted
            fork( fillPagedFileB ).join();
            // So if we had an optimistic lock, we should be asked to retry:
            if ( cursor.shouldRetry() )
            {
                // When we do reads after the shouldRetry() call, we should fault our page back
                // and get consistent reads (assuming we don't race any further with eviction)
                int expected = a * filePageSize;
                int actual;
                do
                {
                    actual = 0;
                    for ( int i = 0; i < filePageSize; i++ )
                    {
                        actual += cursor.getByte();
                    }
                }
                while ( cursor.shouldRetry() );
                assertThat( actual, is( expected ) );
            }
        }

        pagedFileA.close();
        pagedFileB.close();
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.optimisticReadLockMustFaultOnRetryIfPageHasBeenEvicted.fillPagedFileB.new Runnable with () -> {try(PageCursor cursor=pagedFileB.io(0,PF_EXCLUSIVE_LOCK))for(int i=0; i < maxPages * 30; i++){assertTrue(cursor.next()); in method public optimisticReadLockMustFaultOnRetryIfPageHasBeenEvicted() : void from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void concurrentPageFaultingMustNotPutInterleavedDataIntoPages() throws Exception
    {
        final int filePageCount = 11;
        final RecordFormat recordFormat = new PageCountRecordFormat();
        RandomPageCacheTestHarness harness = new RandomPageCacheTestHarness();
        harness.setConcurrencyLevel( 11 );
        harness.setUseAdversarialIO( false );
        harness.setCachePageCount( 3 );
        harness.setCachePageSize( pageCachePageSize );
        harness.setFilePageCount( filePageCount );
        harness.setFilePageSize( pageCachePageSize );
        harness.setInitialMappedFiles( 1 );
        harness.setCommandCount( 10000 );
        harness.setRecordFormat( recordFormat );
        harness.setFileSystem( fs );
        harness.disableCommands(
                Command.FlushCache, Command.FlushFile, Command.MapFile, Command.UnmapFile, Command.WriteRecord );
        harness.setPreparation( ( pageCache1, fs1, filesTouched ) -> {
            File file = filesTouched.iterator().next();
            try ( PagedFile pf = pageCache1.map( file, pageCachePageSize );
                  PageCursor cursor = pf.io( 0, PF_EXCLUSIVE_LOCK ) )
            {
                for ( int pageId = 0; pageId < filePageCount; pageId++ )
                {
                    cursor.next();
                    recordFormat.fillWithRecords( cursor );
                }
            }
        } );

        harness.run( SEMI_LONG_TIMEOUT_MILLIS, MILLISECONDS );
    }

    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void concurrentPageFaultingMustNotPutInterleavedDataIntoPages() throws Exception
    {
        final int filePageCount = 11;
        final RecordFormat recordFormat = new PageCountRecordFormat();
        RandomPageCacheTestHarness harness = new RandomPageCacheTestHarness();
        harness.setConcurrencyLevel( 11 );
        harness.setUseAdversarialIO( false );
        harness.setCachePageCount( 3 );
        harness.setCachePageSize( pageCachePageSize );
        harness.setFilePageCount( filePageCount );
        harness.setFilePageSize( pageCachePageSize );
        harness.setInitialMappedFiles( 1 );
        harness.setCommandCount( 10000 );
        harness.setRecordFormat( recordFormat );
        harness.setFileSystem( fs );
        harness.disableCommands(
                Command.FlushCache, Command.FlushFile, Command.MapFile, Command.UnmapFile, Command.WriteRecord );
        harness.setPreparation( new Phase()
        {
            @Override
            public void run(
                    PageCache pageCache, FileSystemAbstraction fs, Set<File> filesTouched ) throws Exception
            {
                File file = filesTouched.iterator().next();
                try ( PagedFile pf = pageCache.map( file, pageCachePageSize );
                      PageCursor cursor = pf.io( 0, PF_EXCLUSIVE_LOCK ) )
                {
                    for ( int pageId = 0; pageId < filePageCount; pageId++ )
                    {
                        cursor.next();
                        recordFormat.fillWithRecords( cursor );
                    }
                }
            }
        } );

        harness.run( SEMI_LONG_TIMEOUT_MILLIS, MILLISECONDS );
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.concurrentPageFaultingMustNotPutInterleavedDataIntoPages.setPreparation.new Phase with (pageCache1, fs1, filesTouched) -> {File file=filesTouched.iterator().next(); in method public concurrentPageFaultingMustNotPutInterleavedDataIntoPages() : void from class org.neo4j.io.pagecache.PageCacheTest


    private Phase filesAreCorrectlyWrittenVerification( final RecordFormat recordFormat, final int filePageCount )
    {
        return ( pageCache1, fs1, filesTouched ) -> {
            for ( File file : filesTouched )
            {
                try ( PagedFile pf = pageCache1.map( file, pageCachePageSize );
                      PageCursor cursor = pf.io( 0, PF_SHARED_LOCK ) )
                {
                    for ( int pageId = 0; pageId < filePageCount && cursor.next(); pageId++ )
                    {
                        try
                        {
                            recordFormat.assertRecordsWrittenCorrectly( cursor );
                        }
                        catch ( Throwable th )
                        {
                            th.addSuppressed( new Exception( "pageId = " + pageId ) );
                            throw th;
                        }
                    }
                }
                try ( StoreChannel channel = fs1.open( file, "r" ) )
                {
                    recordFormat.assertRecordsWrittenCorrectly( file, channel );
                }
            }
        };
    }

    private Phase filesAreCorrectlyWrittenVerification( final RecordFormat recordFormat, final int filePageCount )
    {
        return new Phase()
        {
            @Override
            public void run(
                    PageCache pageCache, FileSystemAbstraction fs, Set<File> filesTouched ) throws Exception
            {
                for ( File file : filesTouched )
                {
                    try ( PagedFile pf = pageCache.map( file, pageCachePageSize );
                          PageCursor cursor = pf.io( 0, PF_SHARED_LOCK ) )
                    {
                        for ( int pageId = 0; pageId < filePageCount && cursor.next(); pageId++ )
                        {
                            try
                            {
                                recordFormat.assertRecordsWrittenCorrectly( cursor );
                            }
                            catch ( Throwable th )
                            {
                                th.addSuppressed( new Exception( "pageId = " + pageId ) );
                                throw th;
                            }
                        }
                    }
                    try ( StoreChannel channel = fs.open( file, "r" ) )
                    {
                        recordFormat.assertRecordsWrittenCorrectly( file, channel );
                    }
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.filesAreCorrectlyWrittenVerification.new Phase with (pageCache1, fs1, filesTouched) -> {for(File file: filesTouched){try(PagedFile pf=pageCache1.map(file,pageCachePageSize); PageCursor cursor=pf.io(0,PF_SHARED_LOCK))for(int pageId=0; pageId < filePageCount && cursor.next(); pageId++){tryrecordFormat.assertRecordsWrittenCorrectly(cursor); in method private filesAreCorrectlyWrittenVerification(recordFormat RecordFormat, filePageCount int) : Phase from class org.neo4j.io.pagecache.PageCacheTest


    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void backgroundThreadsMustGracefullyShutDown() throws Exception
    {
        assumeTrue( "For some reason, this test is very flaky on Windows", !SystemUtils.IS_OS_WINDOWS );

        int iterations = 1000;
        List<WeakReference<PageCache>> refs = new LinkedList<>();
        final Queue<Throwable> caughtExceptions = new ConcurrentLinkedQueue<>();
        final Thread.UncaughtExceptionHandler exceptionHandler = ( t, e ) -> {
            e.printStackTrace();
            caughtExceptions.offer( e );
        };
        Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler( exceptionHandler );

        try
        {
            generateFileWithRecords( file( "a" ), recordCount, recordSize );
            int filePagesInTotal = recordCount / recordsPerFilePage;

            for ( int i = 0; i < iterations; i++ )
            {
                PageCache cache = createPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );

                // Touch all the pages
                PagedFile pagedFile = cache.map( file( "a" ), filePageSize );
                try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
                {
                    for ( int j = 0; j < filePagesInTotal; j++ )
                    {
                        assertTrue( cursor.next() );
                    }
                }

                // We're now likely racing with the eviction thread
                pagedFile.close();
                cache.close();
                refs.add( new WeakReference<>( cache ) );

                assertTrue( caughtExceptions.isEmpty() );
            }
        }
        finally
        {
            Thread.setDefaultUncaughtExceptionHandler( defaultUncaughtExceptionHandler );
        }

        // Once the page caches has been closed and all references presumably set to null, then the only thing that
        // could possibly strongly reference the cache is any lingering background thread. If we do a couple of
        // GCs, then we should observe that the WeakReference has been cleared by the garbage collector. If it
        // hasn't, then something must be keeping it alive, even though it has been closed.
        int maxChecks = 100;
        boolean passed;
        do
        {
            System.gc();
            Thread.sleep( 100 );
            passed = true;

            for ( WeakReference<PageCache> ref : refs )
            {
                if ( ref.get() != null )
                {
                    passed = false;
                }
            }
        }
        while ( !passed && maxChecks-- > 0 );

        if ( !passed )
        {
            List<PageCache> nonNullPageCaches = new LinkedList<>();
            for ( WeakReference<PageCache> ref : refs )
            {
                PageCache pageCache = ref.get();
                if ( pageCache != null )
                {
                    nonNullPageCaches.add( pageCache );
                }
            }

            if( !nonNullPageCaches.isEmpty() )
            {
                fail( "PageCaches should not be held live after close: " + nonNullPageCaches );
            }
        }
    }

    @Test( timeout = SEMI_LONG_TIMEOUT_MILLIS )
    public void backgroundThreadsMustGracefullyShutDown() throws Exception
    {
        assumeTrue( "For some reason, this test is very flaky on Windows", !SystemUtils.IS_OS_WINDOWS );

        int iterations = 1000;
        List<WeakReference<PageCache>> refs = new LinkedList<>();
        final Queue<Throwable> caughtExceptions = new ConcurrentLinkedQueue<>();
        final Thread.UncaughtExceptionHandler exceptionHandler = new Thread.UncaughtExceptionHandler()
        {
            @Override
            public void uncaughtException( Thread t, Throwable e )
            {
                e.printStackTrace();
                caughtExceptions.offer( e );
            }
        };
        Thread.UncaughtExceptionHandler defaultUncaughtExceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler( exceptionHandler );

        try
        {
            generateFileWithRecords( file( "a" ), recordCount, recordSize );
            int filePagesInTotal = recordCount / recordsPerFilePage;

            for ( int i = 0; i < iterations; i++ )
            {
                PageCache cache = createPageCache( fs, maxPages, pageCachePageSize, PageCacheTracer.NULL );

                // Touch all the pages
                PagedFile pagedFile = cache.map( file( "a" ), filePageSize );
                try ( PageCursor cursor = pagedFile.io( 0, PF_SHARED_LOCK ) )
                {
                    for ( int j = 0; j < filePagesInTotal; j++ )
                    {
                        assertTrue( cursor.next() );
                    }
                }

                // We're now likely racing with the eviction thread
                pagedFile.close();
                cache.close();
                refs.add( new WeakReference<>( cache ) );

                assertTrue( caughtExceptions.isEmpty() );
            }
        }
        finally
        {
            Thread.setDefaultUncaughtExceptionHandler( defaultUncaughtExceptionHandler );
        }

        // Once the page caches has been closed and all references presumably set to null, then the only thing that
        // could possibly strongly reference the cache is any lingering background thread. If we do a couple of
        // GCs, then we should observe that the WeakReference has been cleared by the garbage collector. If it
        // hasn't, then something must be keeping it alive, even though it has been closed.
        int maxChecks = 100;
        boolean passed;
        do
        {
            System.gc();
            Thread.sleep( 100 );
            passed = true;

            for ( WeakReference<PageCache> ref : refs )
            {
                if ( ref.get() != null )
                {
                    passed = false;
                }
            }
        }
        while ( !passed && maxChecks-- > 0 );

        if ( !passed )
        {
            List<PageCache> nonNullPageCaches = new LinkedList<>();
            for ( WeakReference<PageCache> ref : refs )
            {
                PageCache pageCache = ref.get();
                if ( pageCache != null )
                {
                    nonNullPageCaches.add( pageCache );
                }
            }

            if( !nonNullPageCaches.isEmpty() )
            {
                fail( "PageCaches should not be held live after close: " + nonNullPageCaches );
            }
        }
    }

Replace Anonymous With Lambda org.neo4j.io.pagecache.PageCacheTest.backgroundThreadsMustGracefullyShutDown.exceptionHandler.new Thread.UncaughtExceptionHandler with (t, e) -> {e.printStackTrace(); in method public backgroundThreadsMustGracefullyShutDown() : void from class org.neo4j.io.pagecache.PageCacheTest