    private LockAcquisition acquireSharedAndExclusiveLocksInAnotherThread( final CountDownLatch sharedLockAcquired,
            final CountDownLatch startExclusiveLock )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( state ->
        {
            try ( Locks.Client client = newLockClient( lockAcquisition ) )
            {
                client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );

                sharedLockAcquired.countDown();
                await( startExclusiveLock );

                client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
            }
            return null;
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

    private LockAcquisition acquireSharedAndExclusiveLocksInAnotherThread( final CountDownLatch sharedLockAcquired,
            final CountDownLatch startExclusiveLock )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Locks.Client client = newLockClient( lockAcquisition ) )
                {
                    client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );

                    sharedLockAcquired.countDown();
                    await( startExclusiveLock );

                    client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                }
                return null;
            }
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.StopCompatibility.acquireSharedAndExclusiveLocksInAnotherThread.future.execute.new WorkerCommand<Void,Void> with state -> {try(Locks.Client client=newLockClient(lockAcquisition))client.acquireShared(RESOURCE_TYPE,RESOURCE_ID); in method private acquireSharedAndExclusiveLocksInAnotherThread(sharedLockAcquired CountDownLatch, startExclusiveLock CountDownLatch) : LockAcquisition from class org.neo4j.kernel.impl.locking.StopCompatibility


    private LockAcquisition tryAcquireTwoLocksLockInAnotherThread( final boolean shared,
            final CountDownLatch firstLockAcquired )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( state ->
        {
            try ( Locks.Client client = newLockClient( lockAcquisition ) )
            {
                if ( shared )
                {
                    client.acquireShared( RESOURCE_TYPE, OTHER_RESOURCE_ID );
                }
                else
                {
                    client.acquireExclusive( RESOURCE_TYPE, OTHER_RESOURCE_ID );
                }

                firstLockAcquired.countDown();

                if ( shared )
                {
                    client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                }
                else
                {
                    client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                }
            }
            return null;
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

    private LockAcquisition tryAcquireTwoLocksLockInAnotherThread( final boolean shared,
            final CountDownLatch firstLockAcquired )
    {
        final LockAcquisition lockAcquisition = new LockAcquisition();

        Future<Void> future = threadA.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Locks.Client client = newLockClient( lockAcquisition ) )
                {
                    if ( shared )
                    {
                        client.acquireShared( RESOURCE_TYPE, OTHER_RESOURCE_ID );
                    }
                    else
                    {
                        client.acquireExclusive( RESOURCE_TYPE, OTHER_RESOURCE_ID );
                    }

                    firstLockAcquired.countDown();

                    if ( shared )
                    {
                        client.acquireShared( RESOURCE_TYPE, RESOURCE_ID );
                    }
                    else
                    {
                        client.acquireExclusive( RESOURCE_TYPE, RESOURCE_ID );
                    }
                }
                return null;
            }
        } );
        lockAcquisition.setFuture( future, threadA.get() );

        return lockAcquisition;
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.StopCompatibility.tryAcquireTwoLocksLockInAnotherThread.future.execute.new WorkerCommand<Void,Void> with state -> {try(Locks.Client client=newLockClient(lockAcquisition))if(shared){client.acquireShared(RESOURCE_TYPE,OTHER_RESOURCE_ID); in method private tryAcquireTwoLocksLockInAnotherThread(shared boolean, firstLockAcquired CountDownLatch) : LockAcquisition from class org.neo4j.kernel.impl.locking.StopCompatibility


    private int countLocks( LockManagerImpl lockManager )
    {
        final int[] counter = new int[1];
        lockManager.accept( element ->
        {
            counter[0]++;
            return false;
        } );
        return counter[0];
    }

    private int countLocks( LockManagerImpl lockManager )
    {
        final int[] counter = new int[1];
        lockManager.accept( new Visitor<RWLock,RuntimeException>()
        {
            @Override
            public boolean visit( RWLock element ) throws RuntimeException
            {
                counter[0]++;
                return false;
            }
        } );
        return counter[0];
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.community.LockManagerImplTest.countLocks.accept.new Visitor<RWLock,RuntimeException> with element -> {counter[0]++; in method private countLocks(lockManager LockManagerImpl) : int from class org.neo4j.kernel.impl.locking.community.LockManagerImplTest


    public static PrimitiveRecordCheck<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> dummyNeoStoreCheck()
    {
        return new NeoStoreCheck( new PropertyChain<>( from -> null ) )
        {
            @Override
            public void check( NeoStoreRecord record,
                               CheckerEngine<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> engine,
                               RecordAccess records )
            {
            }
        };
    }

    public static PrimitiveRecordCheck<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> dummyNeoStoreCheck()
    {
        return new NeoStoreCheck( new PropertyChain<NeoStoreRecord,ConsistencyReport.NeoStoreConsistencyReport>(
                from -> null ) )
        {
            @Override
            public void check( NeoStoreRecord record,
                               CheckerEngine<NeoStoreRecord, ConsistencyReport.NeoStoreConsistencyReport> engine,
                               RecordAccess records )
            {
            }
        };
    }

Replace Generic With Diamond NeoStoreCheck with NeoStoreCheck in method public dummyNeoStoreCheck() : PrimitiveRecordCheck<NeoStoreRecord,ConsistencyReport.NeoStoreConsistencyReport> from class org.neo4j.consistency.checking.RecordCheckTestBase


    OwnerCheck( boolean active, DynamicStore... stores )
    {
        this.owners = active ? new ConcurrentHashMap<>( 16, 0.75f, 4 ) : null;
        this.dynamics = active ? initialize( stores ) : null;
    }

    OwnerCheck( boolean active, DynamicStore... stores )
    {
        this.owners = active ? new ConcurrentHashMap<Long, PropertyOwner>( 16, 0.75f, 4 ) : null;
        this.dynamics = active ? initialize( stores ) : null;
    }

Replace Generic With Diamond ConcurrentHashMap<Long,PropertyOwner> with ConcurrentHashMap<> in method package OwnerCheck(active boolean, stores DynamicStore...) from class org.neo4j.consistency.checking.full.OwnerCheck


    private static Map<RecordType, ConcurrentMap<Long, DynamicOwner>> initialize( DynamicStore[] stores )
    {
        EnumMap<RecordType, ConcurrentMap<Long, DynamicOwner>> map =
                new EnumMap<>( RecordType.class );
        for ( DynamicStore store : stores )
        {
            map.put( store.type, new ConcurrentHashMap<>( 16, 0.75f, 4 ) );
        }
        return unmodifiableMap( map );
    }

    private static Map<RecordType, ConcurrentMap<Long, DynamicOwner>> initialize( DynamicStore[] stores )
    {
        EnumMap<RecordType, ConcurrentMap<Long, DynamicOwner>> map =
                new EnumMap<>( RecordType.class );
        for ( DynamicStore store : stores )
        {
            map.put( store.type, new ConcurrentHashMap<Long, DynamicOwner>( 16, 0.75f, 4 ) );
        }
        return unmodifiableMap( map );
    }

Replace Generic With Diamond ConcurrentHashMap<Long,DynamicOwner> with ConcurrentHashMap<> in method private initialize(stores DynamicStore[]) : Map<RecordType,ConcurrentMap<Long,DynamicOwner>> from class org.neo4j.consistency.checking.full.OwnerCheck


    public static <RECORD> void distributeRecords(
            int numberOfThreads,
            String workerNames,
            int queueSize,
            Iterator<RECORD> records,
            final ProgressListener progress,
            RecordProcessor<RECORD> processor,
            QueueDistributor<RECORD> idDistributor )
    {
        if ( !records.hasNext() )
        {
            return;
        }

        @SuppressWarnings( "unchecked" )
        final ArrayBlockingQueue<RECORD>[] recordQ = new ArrayBlockingQueue[numberOfThreads];
        final Workers<RecordCheckWorker<RECORD>> workers = new Workers<>( workerNames );
        final AtomicInteger idGroup = new AtomicInteger( -1 );
        for ( int threadId = 0; threadId < numberOfThreads; threadId++ )
        {
            recordQ[threadId] = new ArrayBlockingQueue<>( queueSize );
            workers.start( new RecordCheckWorker<>( threadId, idGroup, recordQ[threadId], processor ) );
        }

        final int[] recsProcessed = new int[numberOfThreads];
        RecordConsumer<RECORD> recordConsumer = ( record, qIndex ) ->
        {
            recordQ[qIndex].put( record );
            recsProcessed[qIndex]++;
        };

        try
        {
            while ( records.hasNext() )
            {
                try
                {
                    // Put records into the queues using the queue distributor. Each Worker will pull and process.
                    RECORD record = records.next();
                    idDistributor.distribute( record, recordConsumer );
                    progress.add( 1 );
                }
                catch ( InterruptedException e )
                {
                    Thread.currentThread().interrupt();
                    break;
                }
            }

            // No more records to distribute, mark as done so that the workers will exit when no more records in queue.
            for ( RecordCheckWorker<RECORD> worker : workers )
            {
                worker.done();
            }

            workers.awaitAndThrowOnError( RuntimeException.class );
        }
        catch ( InterruptedException e )
        {
            Thread.currentThread().interrupt();
            throw new RuntimeException( "Was interrupted while awaiting completion" );
        }
    }

    public static <RECORD> void distributeRecords(
            int numberOfThreads,
            String workerNames,
            int queueSize,
            Iterator<RECORD> records,
            final ProgressListener progress,
            RecordProcessor<RECORD> processor,
            QueueDistributor<RECORD> idDistributor )
    {
        if ( !records.hasNext() )
        {
            return;
        }

        @SuppressWarnings( "unchecked" )
        final ArrayBlockingQueue<RECORD>[] recordQ = new ArrayBlockingQueue[numberOfThreads];
        final Workers<RecordCheckWorker<RECORD>> workers = new Workers<>( workerNames );
        final AtomicInteger idGroup = new AtomicInteger( -1 );
        for ( int threadId = 0; threadId < numberOfThreads; threadId++ )
        {
            recordQ[threadId] = new ArrayBlockingQueue<>( queueSize );
            workers.start( new RecordCheckWorker<>( threadId, idGroup, recordQ[threadId], processor ) );
        }

        final int[] recsProcessed = new int[numberOfThreads];
        RecordConsumer<RECORD> recordConsumer = new RecordConsumer<RECORD>()
        {
            @Override
            public void accept( RECORD record, int qIndex ) throws InterruptedException
            {
                recordQ[qIndex].put( record );
                recsProcessed[qIndex]++;
            }
        };

        try
        {
            while ( records.hasNext() )
            {
                try
                {
                    // Put records into the queues using the queue distributor. Each Worker will pull and process.
                    RECORD record = records.next();
                    idDistributor.distribute( record, recordConsumer );
                    progress.add( 1 );
                }
                catch ( InterruptedException e )
                {
                    Thread.currentThread().interrupt();
                    break;
                }
            }

            // No more records to distribute, mark as done so that the workers will exit when no more records in queue.
            for ( RecordCheckWorker<RECORD> worker : workers )
            {
                worker.done();
            }

            workers.awaitAndThrowOnError( RuntimeException.class );
        }
        catch ( InterruptedException e )
        {
            Thread.currentThread().interrupt();
            throw new RuntimeException( "Was interrupted while awaiting completion" );
        }
    }

Replace Anonymous With Lambda org.neo4j.consistency.checking.full.RecordDistributor.distributeRecords.recordConsumer.new RecordConsumer<RECORD> with (record, qIndex) -> {recordQ[qIndex].put(record); in method public distributeRecords(numberOfThreads int, workerNames String, queueSize int, records Iterator<RECORD>, progress ProgressListener, processor RecordProcessor<RECORD>, idDistributor QueueDistributor<RECORD>) : void from class org.neo4j.consistency.checking.full.RecordDistributor


        @Override
        public <REFERRED extends AbstractBaseRecord> void comparativeCheck(
                RecordReference<REFERRED> reference, ComparativeRecordChecker<RECORD, ? super REFERRED, REPORT> checker )
        {
            references++;
            reference.dispatch( new PendingReferenceCheck<>( this, checker ) );
        }

        @Override
        public <REFERRED extends AbstractBaseRecord> void comparativeCheck(
                RecordReference<REFERRED> reference, ComparativeRecordChecker<RECORD, ? super REFERRED, REPORT> checker )
        {
            references++;
            reference.dispatch( new PendingReferenceCheck<REFERRED>( this, checker ) );
        }

Replace Generic With Diamond PendingReferenceCheck<REFERRED> with PendingReferenceCheck<> in method public comparativeCheck(reference RecordReference<REFERRED>, checker ComparativeRecordChecker<RECORD,? super REFERRED,REPORT>) : void from class org.neo4j.consistency.report.ConsistencyReporter.ReportInvocationHandler


    @Test
    public void shouldContainAddedValues() throws Exception
    {
        // GIVEN
        Map<Long, Integer> expectedEntries = new HashMap<>();
        expectedEntries.put( 1994703545L, 59 );
        expectedEntries.put( 1583732120L, 98 );
        expectedEntries.put( 756530774L, 56 );
        expectedEntries.put( 1433091763L, 22 );

        PrimitiveLongObjectMap<Integer> map = Primitive.longObjectMap();
        for ( Map.Entry<Long, Integer> entry : expectedEntries.entrySet() )
        {
            map.put( entry.getKey(), entry.getValue() );
        }

        // WHEN/THEN
        boolean existedBefore = map.containsKey( 1433091763 );
        Integer valueBefore = map.get( 1433091763 );
        Integer previous = map.put( 1433091763, 35 );
        boolean existsAfter = map.containsKey( 1433091763 );
        Integer valueAfter = map.get( 1433091763 );
        assertTrue( "1433091763 should exist before putting here", existedBefore );
        assertEquals( (Integer) 22, valueBefore );
        assertEquals( (Integer) 22, previous );
        assertTrue( "(1433091763, 35) should exist", existsAfter );
        assertEquals( (Integer) 35, valueAfter );
        expectedEntries.put( 1433091763L, 35 );

        final Map<Long, Integer> visitedEntries = new HashMap<>();
        map.visitEntries( ( key, value ) ->
        {
            visitedEntries.put( key, value );
            return false;
        } );
        assertEquals( expectedEntries, visitedEntries );
    }

    @Test
    public void shouldContainAddedValues() throws Exception
    {
        // GIVEN
        Map<Long, Integer> expectedEntries = new HashMap<>();
        expectedEntries.put( 1994703545L, 59 );
        expectedEntries.put( 1583732120L, 98 );
        expectedEntries.put( 756530774L, 56 );
        expectedEntries.put( 1433091763L, 22 );

        PrimitiveLongObjectMap<Integer> map = Primitive.longObjectMap();
        for ( Map.Entry<Long, Integer> entry : expectedEntries.entrySet() )
        {
            map.put( entry.getKey(), entry.getValue() );
        }

        // WHEN/THEN
        boolean existedBefore = map.containsKey( 1433091763 );
        Integer valueBefore = map.get( 1433091763 );
        Integer previous = map.put( 1433091763, 35 );
        boolean existsAfter = map.containsKey( 1433091763 );
        Integer valueAfter = map.get( 1433091763 );
        assertTrue( "1433091763 should exist before putting here", existedBefore );
        assertEquals( (Integer) 22, valueBefore );
        assertEquals( (Integer) 22, previous );
        assertTrue( "(1433091763, 35) should exist", existsAfter );
        assertEquals( (Integer) 35, valueAfter );
        expectedEntries.put( 1433091763L, 35 );

        final Map<Long, Integer> visitedEntries = new HashMap<>();
        map.visitEntries( new PrimitiveLongObjectVisitor<Integer, RuntimeException>()
        {
            @Override
            public boolean visited( long key, Integer value )
            {
                visitedEntries.put( key, value );
                return false;
            }
        } );
        assertEquals( expectedEntries, visitedEntries );
    }

Replace Anonymous With Lambda org.neo4j.collection.primitive.hopscotch.PrimitiveLongMapTest.shouldContainAddedValues.visitEntries.new PrimitiveLongObjectVisitor<Integer,RuntimeException> with (key, value) -> {visitedEntries.put(key,value); in method public shouldContainAddedValues() : void from class org.neo4j.collection.primitive.hopscotch.PrimitiveLongMapTest


    private void executeInThread( final String query )
    {
        executorService.execute( () -> {
            Result execute = db.execute( query );
            try
            {
                //resultAsString is good test case since it serializes labels, types, properties etc
                execute.resultAsString();
            }
            catch ( Exception e )
            {
                e.printStackTrace();
                hasFailed.set( true );
            }
        } );
    }

    private void executeInThread( final String query )
    {
        executorService.execute( new Runnable()
        {
            @Override
            public void run()
            {
                Result execute = db.execute( query );
                try
                {
                    //resultAsString is good test case since it serializes labels, types, properties etc
                    execute.resultAsString();
                }
                catch ( Exception e )
                {
                    e.printStackTrace();
                    hasFailed.set( true );
                }
            }
        } );
    }

Replace Anonymous With Lambda org.neo4j.cypher.DeleteNodeStressIT.executeInThread.execute.new Runnable with () -> {Result execute=db.execute(query); in method private executeInThread(query String) : void from class org.neo4j.cypher.DeleteNodeStressIT


    @Test
    public void shouldRespectTheStoreLock() throws IOException, IncorrectUsage
    {
        Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" );
        Files.createDirectories( databaseDirectory );

        try ( StoreLocker locker = new StoreLocker( new DefaultFileSystemAbstraction() ) )
        {
            locker.checkLock( databaseDirectory.toFile() );
            execute( "foo.db", "--force" );
            fail( "expected exception" );
        }
        catch ( CommandFailed e )
        {
            assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) );
        }
    }

    @Test
    public void shouldRespectTheStoreLock() throws IOException, IncorrectUsage
    {
        Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" );
        Files.createDirectories( databaseDirectory );
        new StoreLocker( new DefaultFileSystemAbstraction() ).checkLock( databaseDirectory.toFile() );

        try
        {
            execute( "foo.db", "--force" );
            fail( "expected exception" );
        }
        catch ( CommandFailed e )
        {
            assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) );
        }
    }

Try With Resources try(StoreLocker locker=new StoreLocker(new DefaultFileSystemAbstraction())) in method public shouldRespectTheStoreLock() : void from class org.neo4j.commandline.dbms.LoadCommandTest


    public static void checkLock( Path databaseDirectory ) throws CommandFailed
    {
        try ( StoreLocker storeLocker = new StoreLocker( new DefaultFileSystemAbstraction() ) )
        {
            storeLocker.checkLock( databaseDirectory.toFile() );
        }
        catch ( StoreLockException e )
        {
            throw new CommandFailed( "the database is in use -- stop Neo4j and try again", e );
        }
        catch ( IOException e )
        {
            wrapIOException( e );
        }
    }

    public static void checkLock( Path databaseDirectory ) throws CommandFailed
    {
        try
        {
            StoreLocker storeLocker = new StoreLocker( new DefaultFileSystemAbstraction() );
            storeLocker.checkLock( databaseDirectory.toFile() );
            storeLocker.release();
        }
        catch ( StoreLockException e )
        {
            throw new CommandFailed( "the database is in use -- stop Neo4j and try again", e );
        }
        catch ( IOException e )
        {
            wrapIOException( e );
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(new DefaultFileSystemAbstraction())) in method public checkLock(databaseDirectory Path) : void from class org.neo4j.commandline.dbms.Util


    @Test
    public void shouldRespectTheStoreLock() throws IOException, IncorrectUsage, CommandFailed
    {
        Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" );
        Files.createDirectories( databaseDirectory );

        try ( StoreLocker storeLocker = new StoreLocker( new DefaultFileSystemAbstraction() ) )
        {
            storeLocker.checkLock( databaseDirectory.toFile() );

            execute( "foo.db" );
            fail( "expected exception" );
        }
        catch ( CommandFailed e )
        {
            assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) );
        }
    }

    @Test
    public void shouldRespectTheStoreLock() throws IOException, IncorrectUsage, CommandFailed
    {
        Path databaseDirectory = homeDir.resolve( "data/databases/foo.db" );
        Files.createDirectories( databaseDirectory );
        StoreLocker storeLocker = new StoreLocker( new DefaultFileSystemAbstraction() );
        storeLocker.checkLock( databaseDirectory.toFile() );

        try
        {
            execute( "foo.db" );
            fail( "expected exception" );
        }
        catch ( CommandFailed e )
        {
            assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) );
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(new DefaultFileSystemAbstraction())) in method public shouldRespectTheStoreLock() : void from class org.neo4j.commandline.dbms.DumpCommandTest


    @Test
    public void shouldObtainLockWhenStoreFileNotLocked() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public boolean fileExists( File fileName )
            {
                return true;
            }
        };

        try ( StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction ) )
        {
            storeLocker.checkLock( target.directory( "unused" ) );

            // Ok
        }
        catch ( StoreLockException e )
        {
            fail();
        }
    }

    @Test
    public void shouldObtainLockWhenStoreFileNotLocked() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public boolean fileExists( File fileName )
            {
                return true;
            }
        };
        StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction );

        try
        {
            storeLocker.checkLock( target.directory( "unused" ) );

            // Ok
        }
        catch ( StoreLockException e )
        {
            fail();
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(fileSystemAbstraction)) in method public shouldObtainLockWhenStoreFileNotLocked() : void from class org.neo4j.kernel.internal.StoreLockerTest


    @Test
    public void shouldCreateStoreDirAndObtainLockWhenStoreDirDoesNotExist() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }
        };

        try ( StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction ) )
        {
            storeLocker.checkLock( target.directory( "unused" ) );
            // Ok
        }
    }

    @Test
    public void shouldCreateStoreDirAndObtainLockWhenStoreDirDoesNotExist() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }
        };
        StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction );

        try
        {
            storeLocker.checkLock( target.directory( "unused" ) );
            // Ok
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(fileSystemAbstraction)) in method public shouldCreateStoreDirAndObtainLockWhenStoreDirDoesNotExist() : void from class org.neo4j.kernel.internal.StoreLockerTest


    @Test
    public void shouldNotObtainLockWhenStoreDirCannotBeCreated() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public void mkdirs( File fileName ) throws IOException
            {
                throw new IOException( "store dir could not be created" );
            }

            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }
        };

        File storeDir = target.directory( "unused" );

        try ( StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction ) )
        {
            storeLocker.checkLock( storeDir );
            fail();
        }
        catch ( StoreLockException e )
        {
            String msg = format( "Unable to create path for store dir: %s. " +
                    "Please ensure no other process is using this database, and that " +
                    "the directory is writable (required even for read-only access)", storeDir );
            assertThat( e.getMessage(), is( msg ) );
        }
    }

    @Test
    public void shouldNotObtainLockWhenStoreDirCannotBeCreated() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public void mkdirs( File fileName ) throws IOException
            {
                throw new IOException( "store dir could not be created" );
            }

            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }
        };
        StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction );
        File storeDir = target.directory( "unused" );

        try
        {
            storeLocker.checkLock( storeDir );
            fail();
        }
        catch ( StoreLockException e )
        {
            String msg = format( "Unable to create path for store dir: %s. Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", storeDir );
            assertThat( e.getMessage(), is( msg ) );
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(fileSystemAbstraction)) in method public shouldNotObtainLockWhenStoreDirCannotBeCreated() : void from class org.neo4j.kernel.internal.StoreLockerTest


    @Test
    public void shouldNotObtainLockWhenUnableToOpenLockFile() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public StoreChannel open( File fileName, String mode ) throws IOException
            {
                throw new IOException( "cannot open lock file" );
            }

            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }
        };

        File storeDir = target.directory( "unused" );

        try ( StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction ) )
        {
            storeLocker.checkLock( storeDir );
            fail();
        }
        catch ( StoreLockException e )
        {
            String msg = format( "Unable to obtain lock on store lock file: %s. " +
                            "Please ensure no other process is using this database, and that the " +
                            "directory is writable (required even for read-only access)",
                    new File( storeDir, STORE_LOCK_FILENAME ) );
            assertThat( e.getMessage(), is( msg ) );
        }
    }

    @Test
    public void shouldNotObtainLockWhenUnableToOpenLockFile() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public StoreChannel open( File fileName, String mode ) throws IOException
            {
                throw new IOException( "cannot open lock file" );
            }

            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }
        };
        StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction );
        File storeDir = target.directory( "unused" );

        try
        {
            storeLocker.checkLock( storeDir );
            fail();
        }
        catch ( StoreLockException e )
        {
            String msg = format( "Unable to obtain lock on store lock file: %s. Please ensure no other process is using this database, and that the directory is writable (required even for read-only access)", new File( storeDir,
                    STORE_LOCK_FILENAME ) );
            assertThat( e.getMessage(), is( msg ) );
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(fileSystemAbstraction)) in method public shouldNotObtainLockWhenUnableToOpenLockFile() : void from class org.neo4j.kernel.internal.StoreLockerTest


    @Test
    public void shouldNotObtainLockWhenStoreAlreadyInUse() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }

            @Override
            public StoreChannel open( File fileName, String mode ) throws IOException
            {
                return new DelegatingStoreChannel( super.open( fileName, mode ) )
                {
                    @Override
                    public FileLock tryLock() throws IOException
                    {
                        return null; // 'null' implies that the file has been externally locked
                    }
                };
            }
        };

        try ( StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction ) )
        {
            storeLocker.checkLock( target.directory( "unused" ) );
            fail();
        }
        catch ( StoreLockException e )
        {
            assertThat( e.getMessage(),
                    containsString( "Store and its lock file has been locked by another process" ) );
        }
    }

    @Test
    public void shouldNotObtainLockWhenStoreAlreadyInUse() throws Exception
    {
        FileSystemAbstraction fileSystemAbstraction = new DelegatingFileSystemAbstraction( new DefaultFileSystemAbstraction() )
        {
            @Override
            public boolean fileExists( File fileName )
            {
                return false;
            }

            @Override
            public StoreChannel open( File fileName, String mode ) throws IOException
            {
                return new DelegatingStoreChannel( super.open( fileName, mode ) )
                {
                    @Override
                    public FileLock tryLock() throws IOException
                    {
                        return null; // 'null' implies that the file has been externally locked
                    }
                };
            }
        };
        StoreLocker storeLocker = new StoreLocker( fileSystemAbstraction );

        try
        {
            storeLocker.checkLock( target.directory( "unused" ) );
            fail();
        }
        catch ( StoreLockException e )
        {
            assertThat( e.getMessage(), containsString( "Store and its lock file has been locked by another process" ) );
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(fileSystemAbstraction)) in method public shouldNotObtainLockWhenStoreAlreadyInUse() : void from class org.neo4j.kernel.internal.StoreLockerTest


    @Test
    public void testFailsOnExistingStoreLockFile() throws IOException
    {
        // Given
        File parent = testDirectory.graphDbDir();
        try ( StoreLocker lock = new StoreLocker( new DefaultFileSystemAbstraction() ) )
        {
            lock.checkLock( parent );

            // Then
            expected.expect( StoreLockException.class );
            expected.expectMessage( "Unable to obtain lock on store lock file" );
            // When
            BatchInserters.inserter( parent.getAbsoluteFile() );
        }
    }

    @Test
    public void testFailsOnExistingStoreLockFile() throws IOException
    {
        // Given
        File parent = testDirectory.graphDbDir();
        StoreLocker lock = new StoreLocker( new DefaultFileSystemAbstraction() );
        lock.checkLock( parent );

        // When
        try
        {
            BatchInserters.inserter( parent.getAbsoluteFile() );

            // Then
            fail();
        }
        catch ( StoreLockException e )
        {
            // OK
        }
        finally
        {
            lock.release();
        }
    }

Try With Resources try(StoreLocker lock=new StoreLocker(new DefaultFileSystemAbstraction())) in method public testFailsOnExistingStoreLockFile() : void from class org.neo4j.unsafe.batchinsert.internal.BatchInserterImplTest


    @Test
    public void forceShouldRespectStoreLock() throws Exception
    {
        FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        String databaseName = "to";
        Config config = configWith(  Config.empty(), databaseName);

        File fromPath = new File( directory.absolutePath(), "from" );
        File toPath = config.get( DatabaseManagementSystemSettings.database_path );
        int fromNodeCount = 10;
        int toNodeCount = 20;

        createDbAt( fromPath, fromNodeCount );
        createDbAt( toPath, toNodeCount );

        try ( StoreLocker storeLocker = new StoreLocker( fs ) )
        {
            storeLocker.checkLock( toPath );

            new RestoreDatabaseCommand( fs, fromPath, config, databaseName, true ).execute();
            fail( "expected exception" );
        }
        catch ( Exception e )
        {
            assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) );
        }
    }

    @Test
    public void forceShouldRespectStoreLock() throws Exception
    {
        FileSystemAbstraction fs = new DefaultFileSystemAbstraction();
        String databaseName = "to";
        Config config = configWith(  Config.empty(), databaseName);

        File fromPath = new File( directory.absolutePath(), "from" );
        File toPath = config.get( DatabaseManagementSystemSettings.database_path );
        int fromNodeCount = 10;
        int toNodeCount = 20;

        createDbAt( fromPath, fromNodeCount );
        createDbAt( toPath, toNodeCount );

        StoreLocker storeLocker = new StoreLocker( fs );
        storeLocker.checkLock( toPath );

        try
        {
            new RestoreDatabaseCommand( fs, fromPath, config, databaseName, true ).execute();
            fail( "expected exception" );
        }
        catch ( Exception e )
        {
            assertThat( e.getMessage(), equalTo( "the database is in use -- stop Neo4j and try again" ) );
        }
        finally
        {
            storeLocker.release();
        }
    }

Try With Resources try(StoreLocker storeLocker=new StoreLocker(fs)) in method public forceShouldRespectStoreLock() : void from class org.neo4j.restore.RestoreDatabaseCommandTest


    public static <T> Validator<T[]> atLeast( final String key, final int length )
    {
        return value ->
        {
            if ( value.length < length )
            {
                throw new IllegalArgumentException( "Expected '" + key + "' to have at least " +
                        length + " valid item" + (length == 1 ? "" : "s") + ", but had " + value.length +
                        " " + Arrays.toString( value ) );
            }
        };
    }

    public static <T> Validator<T[]> atLeast( final String key, final int length )
    {
        return new Validator<T[]>()
        {
            @Override
            public void validate( T[] value )
            {
                if ( value.length < length )
                {
                    throw new IllegalArgumentException( "Expected '" + key + "' to have at least " +
                            length + " valid item" + (length == 1 ? "" : "s") + ", but had " + value.length +
                            " " + Arrays.toString( value ) );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.util.Validators.atLeast.new Validator<T[]> with value -> {if(value.length < length){throw new IllegalArgumentException("Expected '" + key + "' to have at least " + length + " valid item" + (length == 1 ? "" : "s") + ", but had " + value.length + " " + Arrays.toString(value)); in method public atLeast(key String, length int) : Validator<T[]> from class org.neo4j.kernel.impl.util.Validators


    /**
     * Perform a transaction against the leader of the core cluster, retrying as necessary.
     */
    private CoreClusterMember leaderTx( BiConsumer<CoreGraphDatabase, Transaction> op )
            throws TimeoutException, InterruptedException
    {
        long endTime = System.currentTimeMillis() + DEFAULT_TIMEOUT_MS;

        do
        {
            CoreClusterMember member = awaitCoreMemberWithRole( DEFAULT_TIMEOUT_MS, Role.LEADER );
            CoreGraphDatabase db = member.database();
            if ( db == null )
            {
                throw new DatabaseShutdownException();
            }

            try ( Transaction tx = db.beginTx() )
            {
                op.accept( db, tx );
                return member;
            }
            catch ( Throwable e )
            {
                if ( isTransientFailure( e ) )
                {
                    // this is not the best, but it helps in debugging
                    System.err.println( "Transient failure in leader transaction, trying again." );
                    e.printStackTrace();
                    // sleep and retry
                    Thread.sleep( DEFAULT_BACKOFF_MS );
                }
                else
                {
                    throw e;
                }
            }
        }
        while ( System.currentTimeMillis() < endTime );

        throw new TimeoutException( "Transaction did not succeed in time" );
    }

    /**
     * Perform a transaction against the leader of the core cluster, retrying as necessary.
     */
    private CoreClusterMember leaderTx( BiConsumer<CoreGraphDatabase, Transaction> op )
            throws TimeoutException, InterruptedException
    {
        long endTime = System.currentTimeMillis() + DEFAULT_TIMEOUT_MS;

        do
        {
            CoreClusterMember member = awaitCoreMemberWithRole( DEFAULT_TIMEOUT_MS, Role.LEADER );
            CoreGraphDatabase db = member.database();
            if ( db == null )
            {
                throw new DatabaseShutdownException();
            }

            try
            {
                Transaction tx = db.beginTx();
                op.accept( db, tx );
                tx.close();
                return member;
            }
            catch ( Throwable e )
            {
                if ( isTransientFailure( e ) )
                {
                    // sleep and retry
                    Thread.sleep( DEFAULT_BACKOFF_MS );
                }
                else
                {
                    throw e;
                }
            }
        }
        while ( System.currentTimeMillis() < endTime );

        throw new TimeoutException( "Transaction did not succeed in time" );
    }

Try With Resources try(Transaction tx=db.beginTx()) in method private leaderTx(op BiConsumer<CoreGraphDatabase,Transaction>) : CoreClusterMember from class org.neo4j.coreedge.discovery.Cluster


    /**
     * Performs an incremental backup based off the given context. This means
     * receiving and applying selectively (i.e. irrespective of the actual state
     * of the target db) a set of transactions starting at the desired txId and
     * spanning up to the latest of the master
     *
     * @param targetDb The database that contains a previous full copy
     * @param context The context, containing transaction id to start streaming transaction from
     * @return A backup context, ready to perform
     */
    private BackupOutcome incrementalWithContext( String sourceHostNameOrIp, int sourcePort, GraphDatabaseAPI targetDb,
            long timeout, RequestContext context ) throws IncrementalBackupNotPossibleException
    {
        DependencyResolver resolver = targetDb.getDependencyResolver();

        ProgressTxHandler handler = new ProgressTxHandler();
        TransactionCommittingResponseUnpacker unpacker = new TransactionCommittingResponseUnpacker(
                resolver, DEFAULT_BATCH_SIZE, 0 );

        Monitors monitors = resolver.resolveDependency( Monitors.class );
        LogProvider logProvider = resolver.resolveDependency( LogService.class ).getInternalLogProvider();
        BackupClient client = new BackupClient( sourceHostNameOrIp, sourcePort, null, logProvider, targetDb.storeId(),
                timeout, unpacker, monitors.newMonitor( ByteCounterMonitor.class, BackupClient.class ),
                monitors.newMonitor( RequestMonitor.class, BackupClient.class ), new VersionAwareLogEntryReader<>() );

        try ( Lifespan lifespan = new Lifespan( unpacker, client ) )
        {
            try ( Response<Void> response = client.incrementalBackup( context ) )
            {
                unpacker.unpackResponse( response, handler );
            }
        }
        catch ( MismatchingStoreIdException e )
        {
            throw new RuntimeException( DIFFERENT_STORE, e );
        }
        catch ( RuntimeException | IOException e )
        {
            if ( e.getCause() != null && e.getCause() instanceof MissingLogDataException )
            {
                throw new IncrementalBackupNotPossibleException( TOO_OLD_BACKUP, e.getCause() );
            }
            if ( e.getCause() != null && e.getCause() instanceof ConnectException )
            {
                throw new RuntimeException( e.getMessage(), e.getCause() );
            }
            throw new RuntimeException( "Failed to perform incremental backup.", e );
        }
        catch ( Throwable throwable )
        {
            throw new RuntimeException( "Unexpected error", throwable );
        }

        return new BackupOutcome( handler.getLastSeenTransactionId(), true );
    }

    /**
     * Performs an incremental backup based off the given context. This means
     * receiving and applying selectively (i.e. irrespective of the actual state
     * of the target db) a set of transactions starting at the desired txId and
     * spanning up to the latest of the master
     *
     * @param targetDb The database that contains a previous full copy
     * @param context The context, containing transaction id to start streaming transaction from
     * @return A backup context, ready to perform
     */
    private BackupOutcome incrementalWithContext( String sourceHostNameOrIp, int sourcePort, GraphDatabaseAPI targetDb,
            long timeout, RequestContext context ) throws IncrementalBackupNotPossibleException
    {
        DependencyResolver resolver = targetDb.getDependencyResolver();

        ProgressTxHandler handler = new ProgressTxHandler();
        TransactionCommittingResponseUnpacker unpacker = new TransactionCommittingResponseUnpacker(
                resolver, DEFAULT_BATCH_SIZE, 0 );

        Monitors monitors = resolver.resolveDependency( Monitors.class );
        LogProvider logProvider = resolver.resolveDependency( LogService.class ).getInternalLogProvider();
        BackupClient client = new BackupClient( sourceHostNameOrIp, sourcePort, null, logProvider, targetDb.storeId(),
                timeout, unpacker, monitors.newMonitor( ByteCounterMonitor.class, BackupClient.class ),
                monitors.newMonitor( RequestMonitor.class, BackupClient.class ), entryReader );

        boolean consistent = false;
        try
        {
            client.start();
            unpacker.start();

            try ( Response<Void> response = client.incrementalBackup( context ) )
            {
                unpacker.unpackResponse( response, handler );
            }

            consistent = true;
        }
        catch ( MismatchingStoreIdException e )
        {
            throw new RuntimeException( DIFFERENT_STORE, e );
        }
        catch ( RuntimeException | IOException e )
        {
            if ( e.getCause() != null && e.getCause() instanceof MissingLogDataException )
            {
                throw new IncrementalBackupNotPossibleException( TOO_OLD_BACKUP, e.getCause() );
            }
            if ( e.getCause() != null && e.getCause() instanceof ConnectException )
            {
                throw new RuntimeException( e.getMessage(), e.getCause() );
            }
            throw new RuntimeException( "Failed to perform incremental backup.", e );
        }
        catch ( Throwable throwable )
        {
            throw new RuntimeException( "Unexpected error", throwable );
        }
        finally
        {
            try
            {
                client.stop();
                unpacker.stop();
            }
            catch ( Throwable throwable )
            {
                log.warn( "Unable to stop backup client", throwable );
            }
        }
        return new BackupOutcome( handler.getLastSeenTransactionId(), consistent );
    }

Try With Resources try(Lifespan lifespan=new Lifespan(unpacker,client)) in method private incrementalWithContext(sourceHostNameOrIp String, sourcePort int, targetDb GraphDatabaseAPI, timeout long, context RequestContext) : BackupOutcome from class org.neo4j.backup.BackupService


    private void clearDocument( Document document )
    {
        Set<String> names = new HashSet<>();
        for ( IndexableField field : document.getFields() )
        {
            names.add( field.name() );
        }
        names.remove( LuceneLegacyIndex.KEY_DOC_ID );
        for ( String name : names )
        {
            document.removeFields( name );
        }
    }

    private void clearDocument( Document document )
    {
        Set<String> names = new HashSet<String>();
        for ( IndexableField field : document.getFields() )
        {
            names.add( field.name() );
        }
        names.remove( LuceneLegacyIndex.KEY_DOC_ID );
        for ( String name : names )
        {
            document.removeFields( name );
        }
    }

Replace Generic With Diamond HashSet<String> with HashSet<> in method private clearDocument(document Document) : void from class org.neo4j.index.impl.lucene.legacy.IndexType


            @Override
            protected GraphDatabaseService newDatabase( File storeDir, Map<String,String> config,
                    GraphDatabaseFacadeFactory.Dependencies dependencies )
            {
                return new GraphDatabaseFacadeFactory( DatabaseInfo.COMMUNITY,
                        ( platformModule) -> new CommunityEditionModule( platformModule )
                {

                    @Override
                    protected TransactionHeaderInformationFactory createHeaderInformationFactory()
                    {
                        return new TransactionHeaderInformationFactory.WithRandomBytes()
                        {
                            @Override
                            protected TransactionHeaderInformation createUsing( byte[] additionalHeader )
                            {
                                return new TransactionHeaderInformation( 1, 2, additionalHeader );
                            }
                        };
                    }
                })
                {

                }.newFacade( storeDir, config, dependencies );
            }

            @Override
            protected GraphDatabaseService newDatabase( File storeDir, Map<String,String> config,
                    GraphDatabaseFacadeFactory.Dependencies dependencies )
            {
                return new CommunityFacadeFactory()
                {

                    @Override
                    protected EditionModule createEdition( PlatformModule platformModule )
                    {
                        return new CommunityEditionModule( platformModule )
                        {

                            @Override
                            protected TransactionHeaderInformationFactory createHeaderInformationFactory()
                            {
                                return new TransactionHeaderInformationFactory.WithRandomBytes()
                                {
                                    @Override
                                    protected TransactionHeaderInformation createUsing( byte[] additionalHeader )
                                    {
                                        return new TransactionHeaderInformation( 1, 2, additionalHeader );
                                    }
                                };
                            }
                        };
                    }
                }.newFacade( storeDir, config, dependencies );
            }

Replace Anonymous With Lambda org.neo4j.backup.TestBackup.startGraphDatabase.dbFactory.new TestGraphDatabaseFactory.newDatabase.newFacade.new CommunityFacadeFactory with (platformModule) -> new CommunityEditionModule(platformModule){ in method protected newDatabase(storeDir File, config Map<String,String>, dependencies GraphDatabaseFacadeFactory.Dependencies) : GraphDatabaseService from class org.neo4j.backup.TestBackup.startGraphDatabase.dbFactory.new TestGraphDatabaseFactory


    /**
     * Create a new WorkSync that will synchronize the application of work to
     * the given material.
     * @param material The material we want to apply work to, in a thread-safe
     * way.
     */
    public WorkSync( Material material )
    {
        this.material = material;
        this.stackEnd = new WorkUnit<>( null, null, null );
        this.stack = new AtomicReference<>( stackEnd );
        this.lock = new AtomicReference<>();
    }

    /**
     * Create a new WorkSync that will synchronize the application of work to
     * the given material.
     * @param material The material we want to apply work to, in a thread-safe
     * way.
     */
    public WorkSync( Material material )
    {
        this.material = material;
        this.stackEnd = new WorkUnit<>( null, null, null );
        this.stack = new AtomicReference<>( stackEnd );
        this.lock = new AtomicReference<Thread>();
    }

Replace Generic With Diamond AtomicReference<Thread> with AtomicReference<> in method public WorkSync(material Material) from class org.neo4j.concurrent.WorkSync


    /**
     * Apply the given work to the material in a thread-safe way, possibly by
     * combining it with other work.
     * @param work The work to be done.
     */
    public void apply( W work )
    {
        // Schedule our work on the stack.
        WorkUnit<Material,W> unit = new WorkUnit<>( work, Thread.currentThread(), stackEnd );
        unit.next = stack.getAndSet( unit ); // benign race, see reverse()

        // Try grabbing the lock to do all the work, until our work unit
        // has been completed.
        boolean wasInterrupted = false;
        int tryCount = 0;
        do
        {
            tryCount++;
            try
            {
                if ( tryLock( tryCount, unit ) )
                {
                    try
                    {
                        doSynchronizedWork();
                    }
                    finally
                    {
                        unlock();
                    }
                }
            }
            catch ( InterruptedException e )
            {
                // We can't stop now, because our work has already been
                // scheduled. So instead we're just going to reset the
                // interruption status when we're done.
                wasInterrupted = true;
            }
        }
        while ( !unit.isDone() );

        if ( wasInterrupted )
        {
            Thread.currentThread().interrupt();
        }
    }

    /**
     * Apply the given work to the material in a thread-safe way, possibly by
     * combining it with other work.
     * @param work The work to be done.
     */
    public void apply( W work )
    {
        // Schedule our work on the stack.
        WorkUnit<Material,W> unit = new WorkUnit<Material,W>( work, Thread.currentThread(), stackEnd );
        unit.next = stack.getAndSet( unit ); // benign race, see reverse()

        // Try grabbing the lock to do all the work, until our work unit
        // has been completed.
        boolean wasInterrupted = false;
        int tryCount = 0;
        do
        {
            tryCount++;
            try
            {
                if ( tryLock( tryCount, unit ) )
                {
                    try
                    {
                        doSynchronizedWork();
                    }
                    finally
                    {
                        unlock();
                    }
                }
            }
            catch ( InterruptedException e )
            {
                // We can't stop now, because our work has already been
                // scheduled. So instead we're just going to reset the
                // interruption status when we're done.
                wasInterrupted = true;
            }
        }
        while ( !unit.isDone() );

        if ( wasInterrupted )
        {
            Thread.currentThread().interrupt();
        }
    }

Replace Generic With Diamond WorkUnit<Material,W> with WorkUnit<> in method public apply(work W) : void from class org.neo4j.concurrent.WorkSync


    final <T> Collection<T> getProxiesFor( Class<T> beanInterface, KernelBean kernel )
    {
        Collection<T> result = new ArrayList<>();
        ObjectName query = createObjectNameQuery( kernel.getInstanceId(), beanInterface );
        for ( ObjectName name : getMBeanServer().queryNames( query, null ) )
        {
            result.add( makeProxy( kernel, name, beanInterface ) );
        }
        return result;
    }

    final <T> Collection<T> getProxiesFor( Class<T> beanInterface, KernelBean kernel )
    {
        Collection<T> result = new ArrayList<T>();
        ObjectName query = createObjectNameQuery( kernel.getInstanceId(), beanInterface );
        for ( ObjectName name : getMBeanServer().queryNames( query, null ) )
        {
            result.add( makeProxy( kernel, name, beanInterface ) );
        }
        return result;
    }

Replace Generic With Diamond ArrayList<T> with ArrayList<> in method package getProxiesFor(beanInterface Class<T>, kernel KernelBean) : Collection<T> from class org.neo4j.jmx.impl.ManagementSupport


    protected ObjectName createObjectName( String instanceId, String beanName, boolean query, String... extraNaming )
    {
        Hashtable<String, String> properties = new Hashtable<>();
        properties.put( "instance", "kernel#" + instanceId );
        properties.put( "name", beanName );
        for ( int i = 0; i < extraNaming.length; i++ )
        {
            properties.put( "name" + i, extraNaming[i] );
        }
        try
        {
            return new ObjectName( "org.neo4j", properties );
        }
        catch ( MalformedObjectNameException e )
        {
            return null;
        }
    }

    protected ObjectName createObjectName( String instanceId, String beanName, boolean query, String... extraNaming )
    {
        Hashtable<String, String> properties = new Hashtable<String, String>();
        properties.put( "instance", "kernel#" + instanceId );
        properties.put( "name", beanName );
        for ( int i = 0; i < extraNaming.length; i++ )
        {
            properties.put( "name" + i, extraNaming[i] );
        }
        try
        {
            return new ObjectName( "org.neo4j", properties );
        }
        catch ( MalformedObjectNameException e )
        {
            return null;
        }
    }

Replace Generic With Diamond Hashtable<String,String> with Hashtable<> in method protected createObjectName(instanceId String, beanName String, query boolean, extraNaming String...) : ObjectName from class org.neo4j.jmx.impl.ManagementSupport


    private ComExceptionHandler getNoOpComExceptionHandler()
    {
        return exception ->
        {
            if ( ComException.TRACE_HA_CONNECTIVITY )
            {
                String noOpComExceptionHandler = "NoOpComExceptionHandler";
                //noinspection ThrowableResultOfMethodCallIgnored
                traceComException( exception, noOpComExceptionHandler );
            }
        };
    }

    private ComExceptionHandler getNoOpComExceptionHandler()
    {
        return new ComExceptionHandler()
        {
            @Override
            public void handle( ComException exception )
            {
                if ( ComException.TRACE_HA_CONNECTIVITY )
                {
                    String noOpComExceptionHandler = "NoOpComExceptionHandler";
                    //noinspection ThrowableResultOfMethodCallIgnored
                    traceComException( exception, noOpComExceptionHandler );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.com.Client.getNoOpComExceptionHandler.new ComExceptionHandler with exception -> {if(ComException.TRACE_HA_CONNECTIVITY){String noOpComExceptionHandler="NoOpComExceptionHandler"; in method private getNoOpComExceptionHandler() : ComExceptionHandler from class org.neo4j.com.Client


    @Override
    public void start()
    {
        bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory(
                newCachedThreadPool( daemon( getClass().getSimpleName() + "-boss@" + destination ) ),
                newCachedThreadPool( daemon( getClass().getSimpleName() + "-worker@" + destination ) ) ) );
        bootstrap.setPipelineFactory( this );

        channelPool = new ResourcePool<ChannelContext>( maxUnusedChannels,
                new ResourcePool.CheckStrategy.TimeoutCheckStrategy( DEFAULT_CHECK_INTERVAL, Clocks.systemClock() ),
                new LoggingResourcePoolMonitor( msgLog ) )
        {
            @Override
            protected ChannelContext create()
            {
                msgLog.info( threadInfo() + "Trying to open a new channel from " + origin + " to " + destination,
                        true );
                // We must specify the origin address in case the server has multiple IPs per interface
                ChannelFuture channelFuture = bootstrap.connect( destination, origin );
                channelFuture.awaitUninterruptibly( 5, TimeUnit.SECONDS );
                if ( channelFuture.isSuccess() )
                {
                    msgLog.info( threadInfo() + "Opened a new channel from " +
                            channelFuture.getChannel().getLocalAddress() + " to " +
                            channelFuture.getChannel().getRemoteAddress() );

                    return new ChannelContext( channelFuture.getChannel(), ChannelBuffers.dynamicBuffer(),
                            ByteBuffer.allocate( 1024 * 1024 ) );
                }

                Throwable cause = channelFuture.getCause();
                String msg = Client.this.getClass().getSimpleName() + " could not connect from " + origin + " to " +
                        destination;
                msgLog.debug( msg, true );
                throw traceComException( new ComException( msg, cause ), "Client.start" );
            }

            @Override
            protected boolean isAlive( ChannelContext context )
            {
                return context.channel().isConnected();
            }

            @Override
            protected void dispose( ChannelContext context )
            {
                Channel channel = context.channel();
                if ( channel.isConnected() )
                {
                    msgLog.info( threadInfo() + "Closing: " + context + ". " +
                            "Channel pool size is now " + currentSize() );
                    channel.close();
                }
            }

            private String threadInfo()
            {
                return "Thread[" + Thread.currentThread().getId() + ", " + Thread.currentThread().getName() + "] ";
            }
        };
        /*
         * This is here to couple the channel releasing to Response.close() itself and not
         * to TransactionStream.close() as it is implemented here. The reason is that a Response
         * that is returned without a TransactionStream will still hold the channel and should
         * release it eventually. Also, logically, closing the channel is not dependent on the
         * TransactionStream.
         */
        resourcePoolReleaser = () ->
        {
            if ( channelPool != null)
            {
                channelPool.release();
            }
        };
    }

    @Override
    public void start()
    {
        bootstrap = new ClientBootstrap( new NioClientSocketChannelFactory(
                newCachedThreadPool( daemon( getClass().getSimpleName() + "-boss@" + destination ) ),
                newCachedThreadPool( daemon( getClass().getSimpleName() + "-worker@" + destination ) ) ) );
        bootstrap.setPipelineFactory( this );

        channelPool = new ResourcePool<ChannelContext>( maxUnusedChannels,
                new ResourcePool.CheckStrategy.TimeoutCheckStrategy( DEFAULT_CHECK_INTERVAL, Clocks.systemClock() ),
                new LoggingResourcePoolMonitor( msgLog ) )
        {
            @Override
            protected ChannelContext create()
            {
                msgLog.info( threadInfo() + "Trying to open a new channel from " + origin + " to " + destination,
                        true );
                // We must specify the origin address in case the server has multiple IPs per interface
                ChannelFuture channelFuture = bootstrap.connect( destination, origin );
                channelFuture.awaitUninterruptibly( 5, TimeUnit.SECONDS );
                if ( channelFuture.isSuccess() )
                {
                    msgLog.info( threadInfo() + "Opened a new channel from " +
                            channelFuture.getChannel().getLocalAddress() + " to " +
                            channelFuture.getChannel().getRemoteAddress() );

                    return new ChannelContext( channelFuture.getChannel(), ChannelBuffers.dynamicBuffer(),
                            ByteBuffer.allocate( 1024 * 1024 ) );
                }

                Throwable cause = channelFuture.getCause();
                String msg = Client.this.getClass().getSimpleName() + " could not connect from " + origin + " to " +
                        destination;
                msgLog.debug( msg, true );
                throw traceComException( new ComException( msg, cause ), "Client.start" );
            }

            @Override
            protected boolean isAlive( ChannelContext context )
            {
                return context.channel().isConnected();
            }

            @Override
            protected void dispose( ChannelContext context )
            {
                Channel channel = context.channel();
                if ( channel.isConnected() )
                {
                    msgLog.info( threadInfo() + "Closing: " + context + ". " +
                            "Channel pool size is now " + currentSize() );
                    channel.close();
                }
            }

            private String threadInfo()
            {
                return "Thread[" + Thread.currentThread().getId() + ", " + Thread.currentThread().getName() + "] ";
            }
        };
        /*
         * This is here to couple the channel releasing to Response.close() itself and not
         * to TransactionStream.close() as it is implemented here. The reason is that a Response
         * that is returned without a TransactionStream will still hold the channel and should
         * release it eventually. Also, logically, closing the channel is not dependent on the
         * TransactionStream.
         */
        resourcePoolReleaser = new ResourceReleaser()
        {
            @Override
            public void release()
            {
                if ( channelPool != null)
                {
                    channelPool.release();
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.com.Client.start.new ResourceReleaser with () -> {if(channelPool != null){channelPool.release(); in method public start() : void from class org.neo4j.com.Client


    @Override
    public ChannelPipeline getPipeline() throws Exception
    {
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast( MONITORING_CHANNEL_HANDLER_NAME, new MonitorChannelHandler( byteCounterMonitor ) );
        addLengthFieldPipes( pipeline, frameLength );
        BlockingReadHandler<ChannelBuffer> reader =
                new BlockingReadHandler<>( new ArrayBlockingQueue<>( 100, false ) );
        pipeline.addLast( BLOCKING_CHANNEL_HANDLER_NAME, reader );
        return pipeline;
    }

    @Override
    public ChannelPipeline getPipeline() throws Exception
    {
        ChannelPipeline pipeline = Channels.pipeline();
        pipeline.addLast( MONITORING_CHANNEL_HANDLER_NAME, new MonitorChannelHandler( byteCounterMonitor ) );
        addLengthFieldPipes( pipeline, frameLength );
        BlockingReadHandler<ChannelBuffer> reader =
                new BlockingReadHandler<>( new ArrayBlockingQueue<ChannelEvent>( 100, false ) );
        pipeline.addLast( BLOCKING_CHANNEL_HANDLER_NAME, reader );
        return pipeline;
    }

Replace Generic With Diamond BlockingReadHandler<> with BlockingReadHandler<> in method public getPipeline() : ChannelPipeline from class org.neo4j.com.Client


    private ChannelBuffer readNext()
    {
        try
        {
            ChannelBuffer result = reader.read( timeoutMillis, TimeUnit.MILLISECONDS );
            if ( result == null )
            {
                throw new ComException( "Channel has been closed" );
            }
            return result;
        }
        catch ( IOException | InterruptedException e )
        {
            throw new ComException( e );
        }
    }

    protected ChannelBuffer readNext()
    {
        try
        {
            ChannelBuffer result = reader.read( timeoutMillis, TimeUnit.MILLISECONDS );
            if ( result == null )
            {
                throw new ComException( "Channel has been closed" );
            }
            return result;
        }
        catch ( IOException e )
        {
            throw new ComException( e );
        }
        catch ( InterruptedException e )
        {
            throw new ComException( e );
        }
    }

Merge Catch [catch(IOException e), catch(InterruptedException e)] to catch(IOException|InterruptedException e) in method private readNext() : ChannelBuffer from class org.neo4j.com.DechunkingChannelBuffer


                @Override
                public Visitor<CommittedTransactionRepresentation,Exception> transactions()
                {
                    return transaction ->
                    {
                        long txId = transaction.getCommitEntry().getTxId();
                        if ( firstTxId.compareAndSet( BASE_TX_ID, txId ) )
                        {
                            monitor.startReceivingTransactions( txId );
                        }
                        writer.append( transaction.getTransactionRepresentation(), txId );
                        return false;
                    };
                }

                @Override
                public Visitor<CommittedTransactionRepresentation,Exception> transactions()
                {
                    return new Visitor<CommittedTransactionRepresentation,Exception>()
                    {
                        @Override
                        public boolean visit( CommittedTransactionRepresentation transaction ) throws IOException
                        {
                            long txId = transaction.getCommitEntry().getTxId();
                            if ( firstTxId.compareAndSet( BASE_TX_ID, txId ) )
                            {
                                monitor.startReceivingTransactions( txId );
                            }
                            writer.append( transaction.getTransactionRepresentation(), txId );
                            return false;
                        }
                    };
                }

Replace Anonymous With Lambda org.neo4j.com.storecopy.StoreCopyClient.writeTransactionsToActiveLogFile.accept.new Response.Handler.transactions.new Visitor<CommittedTransactionRepresentation,Exception> with transaction -> {long txId=transaction.getCommitEntry().getTxId(); in method public transactions() : Visitor<CommittedTransactionRepresentation,Exception> from class org.neo4j.com.storecopy.StoreCopyClient.writeTransactionsToActiveLogFile.accept.new Response.Handler


    @Override
    public Response<Integer> multiply( final int value1, final int value2 )
    {
        Serializer serializer = buffer ->
        {
            buffer.writeInt( value1 );
            buffer.writeInt( value2 );
        };
        return sendRequest( MadeUpServer.MadeUpRequestType.MULTIPLY, getRequestContext(), serializer,
                Protocol.INTEGER_DESERIALIZER );
    }

    @Override
    public Response<Integer> multiply( final int value1, final int value2 )
    {
        return sendRequest( MadeUpServer.MadeUpRequestType.MULTIPLY, getRequestContext(), new Serializer()
        {
            @Override
            public void write( ChannelBuffer buffer ) throws IOException
            {
                buffer.writeInt( value1 );
                buffer.writeInt( value2 );
            }
        }, Protocol.INTEGER_DESERIALIZER );
    }

Replace Anonymous With Lambda org.neo4j.com.MadeUpClient.multiply.sendRequest.new Serializer with buffer -> {buffer.writeInt(value1); in method public multiply(value1 int, value2 int) : Response<Integer> from class org.neo4j.com.MadeUpClient


    @Override
    public Response<Void> sendDataStream( final ReadableByteChannel data )
    {
        Serializer serializer = buffer ->
        {
            try ( BlockLogBuffer writer = new BlockLogBuffer( buffer,
                    new Monitors().newMonitor( ByteCounterMonitor.class ) ) )
            {
                writer.write( data );
            }
        };
        return sendRequest( MadeUpServer.MadeUpRequestType.SEND_DATA_STREAM, getRequestContext(), serializer,
                Protocol.VOID_DESERIALIZER );
    }

    @Override
    public Response<Void> sendDataStream( final ReadableByteChannel data )
    {
        return sendRequest( MadeUpServer.MadeUpRequestType.SEND_DATA_STREAM, getRequestContext(), new Serializer()
        {
            @Override
            public void write( ChannelBuffer buffer ) throws IOException
            {
                try ( BlockLogBuffer writer = new BlockLogBuffer( buffer, new Monitors().newMonitor( ByteCounterMonitor.class ) ) )
                {
                    writer.write( data );
                }
            }
        }, Protocol.VOID_DESERIALIZER );
    }

Replace Anonymous With Lambda org.neo4j.com.MadeUpClient.sendDataStream.sendRequest.new Serializer with buffer -> {try(BlockLogBuffer writer=new BlockLogBuffer(buffer,new Monitors().newMonitor(ByteCounterMonitor.class)))writer.write(data); in method public sendDataStream(data ReadableByteChannel) : Response<Void> from class org.neo4j.com.MadeUpClient


    public static <T, E extends Exception> ThrowingFunction<T,Void,E> fromConsumer( ThrowingConsumer<T,E> consumer )
    {
        return t ->
        {
            consumer.accept( t );
            return null;
        };
    }

    public static <T, E extends Exception> ThrowingFunction<T,Void,E> fromConsumer( final ThrowingConsumer<T,E> consumer )
    {
        return new ThrowingFunction<T,Void,E>()
        {
            @Override
            public Void apply( T t ) throws E
            {
                consumer.accept( t );
                return null;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.function.ThrowingFunctions.fromConsumer.new ThrowingFunction<T,Void,E> with t -> {consumer.accept(t); in method public fromConsumer(consumer ThrowingConsumer<T,E>) : ThrowingFunction<T,Void,E> from class org.neo4j.function.ThrowingFunctions


    @Test
    public void shouldParseDataInParallel() throws Exception
    {
        // GIVEN
        int entities = 500;
        Data<InputNode> data = testData( entities );
        Configuration config = new Configuration.Overridden( COMMAS )
        {
            @Override
            public int bufferSize()
            {
                return 100;
            }
        };
        IdType idType = ACTUAL;
        Collector badCollector = mock( Collector.class );
        Groups groups = new Groups();
        Set<Thread> observedProcessingThreads = new CopyOnWriteArraySet<>();
        int threads = 4;
        DeserializerFactory<InputNode> deserializerFactory = (header,chunk,decorator,validator) ->
        {
            observedProcessingThreads.add( Thread.currentThread() );
            // Make sure there will be 4 different processing threads doing this
            while ( observedProcessingThreads.size() < threads );
            return new InputEntityDeserializer<>( header, chunk, config.delimiter(),
                    new InputNodeDeserialization( header, chunk, groups, idType.idsAreExternal() ), decorator,
                    validator, badCollector );
        };
        try ( ParallelInputEntityDeserializer<InputNode> deserializer = new ParallelInputEntityDeserializer<>( data,
                defaultFormatNodeFileHeader(), config, idType, threads, deserializerFactory,
                Validators.<InputNode>emptyValidator(), InputNode.class ) )
        {
            deserializer.processors( threads );

            // WHEN/THEN
            long previousLineNumber = -1;
            long previousPosition = -1;
            for ( long i = 0; i < entities; i++ )
            {
                assertTrue( deserializer.hasNext() );
                InputNode entity = deserializer.next();
                assertEquals( i, ((Long) entity.id()).longValue() );
                assertEquals( "name", entity.properties()[0] );
                assertTrue( entity.properties()[1].toString().startsWith( i + "-" ) );

                assertTrue( entity.lineNumber() > previousLineNumber );
                previousLineNumber = entity.lineNumber();

                assertTrue( entity.position() > previousPosition );
                previousPosition = entity.position();
            }
            assertFalse( deserializer.hasNext() );
            assertEquals( threads, observedProcessingThreads.size() );
        }
    }

    @Test
    public void shouldParseDataInParallel() throws Exception
    {
        // GIVEN
        int entities = 500;
        Data<InputNode> data = testData( entities );
        Configuration config = new Configuration.Overriden( COMMAS )
        {
            @Override
            public int bufferSize()
            {
                return 100;
            }
        };
        IdType idType = ACTUAL;
        Collector badCollector = mock( Collector.class );
        Groups groups = new Groups();
        Set<Thread> observedProcessingThreads = new CopyOnWriteArraySet<>();
        int threads = 4;
        DeserializerFactory<InputNode> deserializerFactory = (chunk,header,decorator,validator) ->
        {
            observedProcessingThreads.add( Thread.currentThread() );
            // Make sure there will be 4 different processing threads doing this
            while ( observedProcessingThreads.size() < threads );
            return new InputEntityDeserializer<>( header, chunk, config.delimiter(),
                    new InputNodeDeserialization( chunk, header, groups, idType.idsAreExternal() ), decorator,
                    validator, badCollector );
        };
        try ( ParallelInputEntityDeserializer<InputNode> deserializer = new ParallelInputEntityDeserializer<>( data,
                defaultFormatNodeFileHeader(), config, idType, threads, deserializerFactory,
                Validators.<InputNode>emptyValidator(), InputNode.class ) )
        {
            deserializer.processors( threads );

            // WHEN/THEN
            long previousLineNumber = -1;
            long previousPosition = -1;
            for ( long i = 0; i < entities; i++ )
            {
                assertTrue( deserializer.hasNext() );
                InputNode entity = deserializer.next();
                assertEquals( i, ((Long) entity.id()).longValue() );
                assertEquals( "name", entity.properties()[0] );
                assertTrue( entity.properties()[1].toString().startsWith( i + "-" ) );

                assertTrue( entity.lineNumber() > previousLineNumber );
                previousLineNumber = entity.lineNumber();

                assertTrue( entity.position() > previousPosition );
                previousPosition = entity.position();
            }
            assertFalse( deserializer.hasNext() );
            assertEquals( threads, observedProcessingThreads.size() );
        }
    }

Replace Anonymous With Lambda org.neo4j.unsafe.impl.batchimport.input.csv.ParallelInputEntityDeserializerTest.shouldParseDataInParallel.config.new Configuration.Overriden with (header, chunk, decorator, validator) -> {observedProcessingThreads.add(Thread.currentThread()); in method public shouldParseDataInParallel() : void from class org.neo4j.unsafe.impl.batchimport.input.csv.ParallelInputEntityDeserializerTest


    private TransactionLogModule buildTransactionLogs(
            File storeDir,
            Config config,
            LogProvider logProvider,
            JobScheduler scheduler,
            FileSystemAbstraction fileSystemAbstraction,
            StorageEngine storageEngine, LogEntryReader<ReadableClosablePositionAwareChannel> logEntryReader,
            SynchronizedArrayIdOrderingQueue legacyIndexTransactionOrdering,
            TransactionIdStore transactionIdStore, LogVersionRepository logVersionRepository )
    {
        TransactionMetadataCache transactionMetadataCache = new TransactionMetadataCache( 100_000 );
        LogHeaderCache logHeaderCache = new LogHeaderCache( 1000 );
        final PhysicalLogFiles logFiles = new PhysicalLogFiles( storeDir, PhysicalLogFile.DEFAULT_NAME,
                fileSystemAbstraction );

        final PhysicalLogFile logFile = life.add( new PhysicalLogFile( fileSystemAbstraction, logFiles,
                config.get( GraphDatabaseSettings.logical_log_rotation_threshold ),
                transactionIdStore::getLastCommittedTransactionId, logVersionRepository, physicalLogMonitor,
                logHeaderCache ) );

        final PhysicalLogFileInformation.LogVersionToTimestamp logInformation = version ->
        {
            LogPosition position = LogPosition.start( version );
            try ( ReadableLogChannel channel = logFile.getReader( position ) )
            {
                LogEntry entry;
                while ( (entry = logEntryReader.readLogEntry( channel )) != null )
                {
                    if ( entry instanceof LogEntryStart )
                    {
                        return entry.<LogEntryStart>as().getTimeWritten();
                    }
                }
            }
            return -1;
        };
        final LogFileInformation logFileInformation =
                new PhysicalLogFileInformation( logFiles, logHeaderCache, transactionIdStore::getLastCommittedTransactionId, logInformation );

        String pruningConf = config.get(
                config.get( GraphDatabaseFacadeFactory.Configuration.ephemeral )
                ? GraphDatabaseFacadeFactory.Configuration.ephemeral_keep_logical_logs
                : GraphDatabaseSettings.keep_logical_logs );

        LogPruneStrategy logPruneStrategy = fromConfigValue( fs, logFileInformation, logFiles, pruningConf );

        final LogPruning logPruning = new LogPruningImpl( logPruneStrategy, logProvider );

        final LogRotation logRotation =
                new LogRotationImpl( monitors.newMonitor( LogRotation.Monitor.class ), logFile, databaseHealth );

        final TransactionAppender appender = life.add( new BatchingTransactionAppender(
                logFile, logRotation, transactionMetadataCache, transactionIdStore, legacyIndexTransactionOrdering,
                databaseHealth ) );
        final LogicalTransactionStore logicalTransactionStore =
                new PhysicalLogicalTransactionStore( logFile, transactionMetadataCache, logEntryReader );

        int txThreshold = config.get( GraphDatabaseSettings.check_point_interval_tx );
        final CountCommittedTransactionThreshold countCommittedTransactionThreshold =
                new CountCommittedTransactionThreshold( txThreshold );

        long timeMillisThreshold = config.get( GraphDatabaseSettings.check_point_interval_time );
        TimeCheckPointThreshold timeCheckPointThreshold =
                new TimeCheckPointThreshold( timeMillisThreshold, Clocks.systemClock() );

        CheckPointThreshold threshold =
                CheckPointThresholds.or( countCommittedTransactionThreshold, timeCheckPointThreshold );

        final CheckPointerImpl checkPointer = new CheckPointerImpl(
                transactionIdStore, threshold, storageEngine, logPruning, appender, databaseHealth, logProvider,
                tracers.checkPointTracer, ioLimiter );

        long recurringPeriod = Math.min( timeMillisThreshold, TimeUnit.SECONDS.toMillis( 10 ) );
        CheckPointScheduler checkPointScheduler = new CheckPointScheduler( checkPointer, scheduler, recurringPeriod );

        life.add( checkPointer );
        life.add( checkPointScheduler );

        return new TransactionLogModule()
        {
            @Override
            public LogicalTransactionStore logicalTransactionStore()
            {
                return logicalTransactionStore;
            }

            @Override
            public LogFileInformation logFileInformation()
            {
                return logFileInformation;
            }

            @Override
            public PhysicalLogFiles logFiles()
            {
                return logFiles;
            }

            @Override
            public LogFile logFile()
            {
                return logFile;
            }

            @Override
            public LogRotation logRotation()
            {
                return logRotation;
            }

            @Override
            public CheckPointer checkPointing()
            {
                return checkPointer;
            }

            @Override
            public TransactionAppender transactionAppender()
            {
                return appender;
            }

            @Override
            public IdOrderingQueue legacyIndexTransactionOrderingQueue()
            {
                return legacyIndexTransactionOrdering;
            }
        };
    }

    private TransactionLogModule buildTransactionLogs(
            File storeDir,
            Config config,
            LogProvider logProvider,
            JobScheduler scheduler,
            FileSystemAbstraction fileSystemAbstraction,
            StorageEngine storageEngine, LogEntryReader<ReadableClosablePositionAwareChannel> logEntryReader,
            SynchronizedArrayIdOrderingQueue legacyIndexTransactionOrdering,
            TransactionIdStore transactionIdStore, LogVersionRepository logVersionRepository )
    {
        TransactionMetadataCache transactionMetadataCache = new TransactionMetadataCache( 100_000 );
        LogHeaderCache logHeaderCache = new LogHeaderCache( 1000 );
        final PhysicalLogFiles logFiles = new PhysicalLogFiles( storeDir, PhysicalLogFile.DEFAULT_NAME,
                fileSystemAbstraction );

        final PhysicalLogFile logFile = life.add( new PhysicalLogFile( fileSystemAbstraction, logFiles,
                config.get( GraphDatabaseSettings.logical_log_rotation_threshold ),
                transactionIdStore::getLastCommittedTransactionId, logVersionRepository, physicalLogMonitor,
                logHeaderCache ) );

        final PhysicalLogFileInformation.LogVersionToTimestamp
                logInformation = new PhysicalLogFileInformation.LogVersionToTimestamp()
        {
            @Override
            public long getTimestampForVersion( long version ) throws IOException
            {
                LogPosition position = LogPosition.start( version );
                try ( ReadableLogChannel channel = logFile.getReader( position ) )
                {
                    LogEntry entry;
                    while ( (entry = logEntryReader.readLogEntry( channel )) != null )
                    {
                        if ( entry instanceof LogEntryStart )
                        {
                            return entry.<LogEntryStart>as().getTimeWritten();
                        }
                    }
                }
                return -1;
            }
        };
        final LogFileInformation logFileInformation =
                new PhysicalLogFileInformation( logFiles, logHeaderCache, transactionIdStore::getLastCommittedTransactionId, logInformation );

        String pruningConf = config.get(
                config.get( GraphDatabaseFacadeFactory.Configuration.ephemeral )
                ? GraphDatabaseFacadeFactory.Configuration.ephemeral_keep_logical_logs
                : GraphDatabaseSettings.keep_logical_logs );

        LogPruneStrategy logPruneStrategy = fromConfigValue( fs, logFileInformation, logFiles, pruningConf );

        final LogPruning logPruning = new LogPruningImpl( logPruneStrategy, logProvider );

        final LogRotation logRotation =
                new LogRotationImpl( monitors.newMonitor( LogRotation.Monitor.class ), logFile, databaseHealth );

        final TransactionAppender appender = life.add( new BatchingTransactionAppender(
                logFile, logRotation, transactionMetadataCache, transactionIdStore, legacyIndexTransactionOrdering,
                databaseHealth ) );
        final LogicalTransactionStore logicalTransactionStore =
                new PhysicalLogicalTransactionStore( logFile, transactionMetadataCache, logEntryReader );

        int txThreshold = config.get( GraphDatabaseSettings.check_point_interval_tx );
        final CountCommittedTransactionThreshold countCommittedTransactionThreshold =
                new CountCommittedTransactionThreshold( txThreshold );

        long timeMillisThreshold = config.get( GraphDatabaseSettings.check_point_interval_time );
        TimeCheckPointThreshold timeCheckPointThreshold =
                new TimeCheckPointThreshold( timeMillisThreshold, Clocks.systemClock() );

        CheckPointThreshold threshold =
                CheckPointThresholds.or( countCommittedTransactionThreshold, timeCheckPointThreshold );

        final CheckPointerImpl checkPointer = new CheckPointerImpl(
                transactionIdStore, threshold, storageEngine, logPruning, appender, databaseHealth, logProvider,
                tracers.checkPointTracer, ioLimiter );

        long recurringPeriod = Math.min( timeMillisThreshold, TimeUnit.SECONDS.toMillis( 10 ) );
        CheckPointScheduler checkPointScheduler = new CheckPointScheduler( checkPointer, scheduler, recurringPeriod );

        life.add( checkPointer );
        life.add( checkPointScheduler );

        return new TransactionLogModule()
        {
            @Override
            public LogicalTransactionStore logicalTransactionStore()
            {
                return logicalTransactionStore;
            }

            @Override
            public LogFileInformation logFileInformation()
            {
                return logFileInformation;
            }

            @Override
            public PhysicalLogFiles logFiles()
            {
                return logFiles;
            }

            @Override
            public LogFile logFile()
            {
                return logFile;
            }

            @Override
            public LogRotation logRotation()
            {
                return logRotation;
            }

            @Override
            public CheckPointer checkPointing()
            {
                return checkPointer;
            }

            @Override
            public TransactionAppender transactionAppender()
            {
                return appender;
            }

            @Override
            public IdOrderingQueue legacyIndexTransactionOrderingQueue()
            {
                return legacyIndexTransactionOrdering;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.NeoStoreDataSource.buildTransactionLogs.logInformation.new PhysicalLogFileInformation.LogVersionToTimestamp with version -> {LogPosition position=LogPosition.start(version); in method private buildTransactionLogs(storeDir File, config Config, logProvider LogProvider, scheduler JobScheduler, fileSystemAbstraction FileSystemAbstraction, storageEngine StorageEngine, logEntryReader LogEntryReader<ReadableClosablePositionAwareChannel>, legacyIndexTransactionOrdering SynchronizedArrayIdOrderingQueue, transactionIdStore TransactionIdStore, logVersionRepository LogVersionRepository) : TransactionLogModule from class org.neo4j.kernel.NeoStoreDataSource


        private ThrowingFunction<Void,Void,RuntimeException> createOffender()
        {
            return aVoid ->
            {
                try ( Transaction tx = db.beginTx() )
                {
                    createOffender( db, KEY );
                    tx.success();
                }
                return null;
            };
        }

        private ThrowingFunction<Void,Void,RuntimeException> createOffender()
        {
            return new ThrowingFunction<Void,Void,RuntimeException>()
            {
                @Override
                public Void apply( Void aVoid ) throws RuntimeException
                {
                    try ( Transaction tx = db.beginTx() )
                    {
                        createOffender( db, KEY );
                        tx.success();
                    }
                    return null;
                }
            };
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.PropertyExistenceConstraintVerificationIT.AbstractPropertyExistenceConstraintVerificationIT.createOffender.new ThrowingFunction<Void,Void,RuntimeException> with aVoid -> {try(Transaction tx=db.beginTx())createOffender(db,KEY); in method private createOffender() : ThrowingFunction<Void,Void,RuntimeException> from class org.neo4j.kernel.impl.api.integrationtest.PropertyExistenceConstraintVerificationIT.AbstractPropertyExistenceConstraintVerificationIT


        private ThrowingFunction<Void,Void,RuntimeException> createConstraint()
        {
            return aVoid ->
            {
                try ( Transaction tx = db.beginTx() )
                {
                    createConstraint( db, KEY, PROPERTY );
                    tx.success();
                }
                return null;
            };
        }

        private ThrowingFunction<Void,Void,RuntimeException> createConstraint()
        {
            return new ThrowingFunction<Void,Void,RuntimeException>()
            {
                @Override
                public Void apply( Void aVoid ) throws RuntimeException
                {
                    try ( Transaction tx = db.beginTx() )
                    {
                        createConstraint( db, KEY, PROPERTY );
                        tx.success();
                    }
                    return null;
                }
            };
        }

Replace Anonymous With Lambda org.neo4j.kernel.impl.api.integrationtest.PropertyExistenceConstraintVerificationIT.AbstractPropertyExistenceConstraintVerificationIT.createConstraint.new ThrowingFunction<Void,Void,RuntimeException> with aVoid -> {try(Transaction tx=db.beginTx())createConstraint(db,KEY,PROPERTY); in method private createConstraint() : ThrowingFunction<Void,Void,RuntimeException> from class org.neo4j.kernel.impl.api.integrationtest.PropertyExistenceConstraintVerificationIT.AbstractPropertyExistenceConstraintVerificationIT