                @Override
                public void run()
                {
                    Cluster joinCluster = servers.get( joinServer - 1 ).newClient( Cluster.class );
                    for ( final Cluster cluster : out )
                    {
                        if ( cluster.equals( joinCluster ) )
                        {
                            out.remove( cluster );
                            logger.getLogger().fine( "Join:" + cluster.toString() );
                            if ( joinServers.length == 0 )
                            {
                                if ( in.isEmpty() )
                                {
                                    cluster.create( "default" );
                                }
                                else
                                {
                                    // Use test info to figure out who to join
                                    URI[] toJoin = new URI[servers.size()];
                                    for ( int i = 0; i < servers.size(); i++ )
                                    {
                                        toJoin[i] = servers.get( i ).getServer().boundAt();
                                    }
                                    final Future<ClusterConfiguration> result = cluster.join( "default", toJoin );
                                    Runnable joiner = () ->
                                    {
                                        try
                                        {
                                            ClusterConfiguration clusterConfiguration = result.get();
                                            logger.getLogger().fine( "**** Cluster configuration:" +
                                                    clusterConfiguration );
                                        }
                                        catch ( Exception e )
                                        {
                                            logger.getLogger().warning( "**** Node could not join cluster:" + e
                                                    .getMessage() );
                                            out.add( cluster );
                                        }
                                    };
                                    network.addFutureWaiter( result, joiner );
                                }
                            }
                            else
                            {
                                // List of servers to join was explicitly specified, so use that
                                URI[] instanceUris = new URI[joinServers.length];
                                for ( int i = 0; i < joinServers.length; i++ )
                                {
                                    int server = joinServers[i];
                                    instanceUris[i] = URI.create( "server" + server );
                                }

                                final Future<ClusterConfiguration> result = cluster.join( "default", instanceUris );
                                Runnable joiner = () ->
                                {
                                    try
                                    {
                                        ClusterConfiguration clusterConfiguration = result.get();
                                        logger.getLogger().fine( "**** Cluster configuration:" +
                                                clusterConfiguration );
                                    }
                                    catch ( Exception e )
                                    {
                                        logger.getLogger().warning(
                                                "**** Node " + joinServer + " could not join cluster:" + e
                                                        .getMessage()
                                        );
                                        if ( !(e.getCause() instanceof IllegalStateException) )
                                        {
                                            cluster.create( "default" );
                                        }
                                        else
                                        {
                                            logger.getLogger().warning( "*** Incorrectly configured cluster? "
                                                    + e.getCause().getMessage() );
                                        }
                                    }
                                };
                                network.addFutureWaiter( result, joiner );
                            }
                            break;
                        }
                    }
                }

                @Override
                public void run()
                {
                    Cluster joinCluster = servers.get( joinServer - 1 ).newClient( Cluster.class );
                    for ( final Cluster cluster : out )
                    {
                        if ( cluster.equals( joinCluster ) )
                        {
                            out.remove( cluster );
                            logger.getLogger().fine( "Join:" + cluster.toString() );
                            if ( joinServers.length == 0 )
                            {
                                if ( in.isEmpty() )
                                {
                                    cluster.create( "default" );
                                }
                                else
                                {
                                    // Use test info to figure out who to join
                                    URI[] toJoin = new URI[servers.size()];
                                    for ( int i = 0; i < servers.size(); i++ )
                                    {
                                        toJoin[i] = servers.get( i ).getServer().boundAt();
                                    }
                                    final Future<ClusterConfiguration> result = cluster.join( "default", toJoin );
                                    Runnable joiner = new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            try
                                            {
                                                ClusterConfiguration clusterConfiguration = result.get();
                                                logger.getLogger().fine( "**** Cluster configuration:" +
                                                        clusterConfiguration );
                                            }
                                            catch ( Exception e )
                                            {
                                                logger.getLogger().warning( "**** Node could not join cluster:" + e
                                                        .getMessage() );
                                                out.add( cluster );
                                            }
                                        }
                                    };
                                    network.addFutureWaiter( result, joiner );
                                }
                            }
                            else
                            {
                                // List of servers to join was explicitly specified, so use that
                                URI[] instanceUris = new URI[joinServers.length];
                                for ( int i = 0; i < joinServers.length; i++ )
                                {
                                    int server = joinServers[i];
                                    instanceUris[i] = URI.create( "server" + server );
                                }

                                final Future<ClusterConfiguration> result = cluster.join( "default", instanceUris );
                                Runnable joiner = new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        try
                                        {
                                            ClusterConfiguration clusterConfiguration = result.get();
                                            logger.getLogger().fine( "**** Cluster configuration:" +
                                                    clusterConfiguration );
                                        }
                                        catch ( Exception e )
                                        {
                                            logger.getLogger().warning(
                                                    "**** Node " + joinServer + " could not join cluster:" + e
                                                            .getMessage()
                                            );
                                            if ( !(e.getCause() instanceof IllegalStateException) )
                                            {
                                                cluster.create( "default" );
                                            }
                                            else
                                            {
                                                logger.getLogger().warning( "*** Incorrectly configured cluster? "
                                                        + e.getCause().getMessage() );
                                            }
                                        }
                                    }
                                };
                                network.addFutureWaiter( result, joiner );
                            }
                            break;
                        }
                    }
                }

Replace Anonymous With Lambda org.neo4j.cluster.protocol.cluster.ClusterMockTest.ClusterTestScriptDSL.join.addAction.new ClusterAction.run.joiner.new Runnable with () -> {tryClusterConfiguration clusterConfiguration=result.get(); in method public run() : void from class org.neo4j.cluster.protocol.cluster.ClusterMockTest.ClusterTestScriptDSL.join.addAction.new ClusterAction


        @Override
        public void tick( long time )
        {
            if ( time >= (rounds() - 100) * 10 )
            {
                return;
            }

            if ( time == 0 )
            {
                logger.getLogger().fine( "Random seed:" + seed + "L" );
            }

            if ( random.nextDouble() >= 0.8 )
            {
                double inOrOut = (in.size() - out.size()) / ((double) servers.size());
                double whatToDo = random.nextDouble() + inOrOut;
                logger.getLogger().fine( "What to do:" + whatToDo );

                if ( whatToDo < 0.5 && !out.isEmpty() )
                {
                    int idx = random.nextInt( out.size() );
                    final Cluster cluster = out.remove( idx );

                    if ( in.isEmpty() )
                    {
                        cluster.create( "default" );
                    }
                    else
                    {
                        final Future<ClusterConfiguration> result = cluster.join( "default",
                                URI.create( in.get( 0 ).toString() ) );
                        Runnable joiner = () ->
                        {
                            try
                            {
                                ClusterConfiguration clusterConfiguration = result.get();
                                logger.getLogger().fine( "**** Cluster configuration:" +
                                        clusterConfiguration );
                            }
                            catch ( Exception e )
                            {
                                logger.getLogger().fine( "**** Node could not join cluster:" + e
                                        .getMessage() );
                                out.add( cluster );
                            }
                        };
                        network.addFutureWaiter( result, joiner );
                    }
                    logger.getLogger().fine( "Enter cluster:" + cluster.toString() );

                }
                else if ( !in.isEmpty() )
                {
                    int idx = random.nextInt( in.size() );
                    Cluster cluster = in.remove( idx );
                    cluster.leave();
                    logger.getLogger().fine( "Leave cluster:" + cluster.toString() );
                }
            }
        }

        @Override
        public void tick( long time )
        {
            if ( time >= (rounds() - 100) * 10 )
            {
                return;
            }

            if ( time == 0 )
            {
                logger.getLogger().fine( "Random seed:" + seed + "L" );
            }

            if ( random.nextDouble() >= 0.8 )
            {
                double inOrOut = (in.size() - out.size()) / ((double) servers.size());
                double whatToDo = random.nextDouble() + inOrOut;
                logger.getLogger().fine( "What to do:" + whatToDo );

                if ( whatToDo < 0.5 && !out.isEmpty() )
                {
                    int idx = random.nextInt( out.size() );
                    final Cluster cluster = out.remove( idx );

                    if ( in.isEmpty() )
                    {
                        cluster.create( "default" );
                    }
                    else
                    {
                        final Future<ClusterConfiguration> result = cluster.join( "default",
                                URI.create( in.get( 0 ).toString() ) );
                        Runnable joiner = new Runnable()
                        {
                            @Override
                            public void run()
                            {
                                try
                                {
                                    ClusterConfiguration clusterConfiguration = result.get();
                                    logger.getLogger().fine( "**** Cluster configuration:" +
                                            clusterConfiguration );
                                }
                                catch ( Exception e )
                                {
                                    logger.getLogger().fine( "**** Node could not join cluster:" + e
                                            .getMessage() );
                                    out.add( cluster );
                                }
                            }
                        };
                        network.addFutureWaiter( result, joiner );
                    }
                    logger.getLogger().fine( "Enter cluster:" + cluster.toString() );

                }
                else if ( !in.isEmpty() )
                {
                    int idx = random.nextInt( in.size() );
                    Cluster cluster = in.remove( idx );
                    cluster.leave();
                    logger.getLogger().fine( "Leave cluster:" + cluster.toString() );
                }
            }
        }

Replace Anonymous With Lambda org.neo4j.cluster.protocol.cluster.ClusterMockTest.ClusterTestScriptRandom.tick.joiner.new Runnable with () -> {tryClusterConfiguration clusterConfiguration=result.get(); in method public tick(time long) : void from class org.neo4j.cluster.protocol.cluster.ClusterMockTest.ClusterTestScriptRandom


                @Override
                public void run()
                {
                    Cluster joinCluster = servers.get( joinServer - 1 );
                    for ( final Cluster cluster : out )
                    {
                        if ( cluster.equals( joinCluster ) )
                        {
                            out.remove( cluster );
                            logger.getLogger().fine( "Join:" + cluster.toString() );
                            if ( joinServers.length == 0 )
                            {
                                if ( in.isEmpty() )
                                {
                                    cluster.create( "default" );
                                }
                                else
                                {
                                    // Use test info to figure out who to join
                                    final Future<ClusterConfiguration> result = cluster.join( "default",
                                            URI.create( in.get( 0 ).toString() ) );
                                    executor.submit( () ->
                                    {
                                        try
                                        {
                                            ClusterConfiguration clusterConfiguration = result.get();
                                            logger.getLogger().fine( "**** Cluster configuration:" +
                                                    clusterConfiguration );
                                        }
                                        catch ( Exception e )
                                        {
                                            logger.getLogger().fine( "**** Node " + joinServer + " could not " +
                                                    "join cluster:" + e
                                                    .getMessage() );
                                            out.add( cluster );
                                        }
                                    } );
                                }
                            }
                            else
                            {
                                // List of servers to join was explicitly specified, so use that
                                URI[] instanceUris = new URI[joinServers.length];
                                for ( int i = 0; i < joinServers.length; i++ )
                                {
                                    int server = joinServers[i];
                                    instanceUris[i] = URI.create( servers.get( server - 1 ).toString() );
                                }

                                final Future<ClusterConfiguration> result = cluster.join( "default", instanceUris );
                                executor.submit( () ->
                                {
                                    try
                                    {
                                        ClusterConfiguration clusterConfiguration = result.get();
                                        logger.getLogger().fine( "**** Cluster configuration:" +
                                                clusterConfiguration );
                                    }
                                    catch ( Exception e )
                                    {
                                        if ( !(e.getCause() instanceof IllegalStateException) )
                                        {
                                            cluster.create( "default" );
                                        }
                                        else
                                        {
                                            logger.getLogger().fine( "*** Incorrectly configured cluster? "
                                                    + e.getCause().getMessage() );
                                        }
                                    }
                                } );
                            }
                            /*
                            if ( in.isEmpty() )
                            {
                                cluster.create( "default" );
                            }
                            else
                            {
                                try
                                {
                                    cluster.join( "default", new URI( in.get( 0 ).toString() ) );
                                }
                                catch ( URISyntaxException e )
                                {
                                    e.printStackTrace();
                                }
                            }*/
                            break;
                        }
                    }
                }

                @Override
                public void run()
                {
                    Cluster joinCluster = servers.get( joinServer - 1 );
                    for ( final Cluster cluster : out )
                    {
                        if ( cluster.equals( joinCluster ) )
                        {
                            out.remove( cluster );
                            logger.getLogger().fine( "Join:" + cluster.toString() );
                            if ( joinServers.length == 0 )
                            {
                                if ( in.isEmpty() )
                                {
                                    cluster.create( "default" );
                                }
                                else
                                {
                                    // Use test info to figure out who to join
                                    final Future<ClusterConfiguration> result = cluster.join( "default",
                                            URI.create( in.get( 0 ).toString() ) );
                                    executor.submit( new Runnable()
                                    {
                                        @Override
                                        public void run()
                                        {
                                            try
                                            {
                                                ClusterConfiguration clusterConfiguration = result.get();
                                                logger.getLogger().fine( "**** Cluster configuration:" +
                                                        clusterConfiguration );
                                            }
                                            catch ( Exception e )
                                            {
                                                logger.getLogger().fine( "**** Node " + joinServer + " could not " +
                                                        "join cluster:" + e
                                                        .getMessage() );
                                                out.add( cluster );
                                            }
                                        }
                                    } );
                                }
                            }
                            else
                            {
                                // List of servers to join was explicitly specified, so use that
                                URI[] instanceUris = new URI[joinServers.length];
                                for ( int i = 0; i < joinServers.length; i++ )
                                {
                                    int server = joinServers[i];
                                    instanceUris[i] = URI.create( servers.get( server - 1 ).toString() );
                                }

                                final Future<ClusterConfiguration> result = cluster.join( "default", instanceUris );
                                executor.submit( new Runnable()
                                {
                                    @Override
                                    public void run()
                                    {
                                        try
                                        {
                                            ClusterConfiguration clusterConfiguration = result.get();
                                            logger.getLogger().fine( "**** Cluster configuration:" +
                                                    clusterConfiguration );
                                        }
                                        catch ( Exception e )
                                        {
                                            if ( !(e.getCause() instanceof IllegalStateException) )
                                            {
                                                cluster.create( "default" );
                                            }
                                            else
                                            {
                                                logger.getLogger().fine( "*** Incorrectly configured cluster? "
                                                        + e.getCause().getMessage() );
                                            }
                                        }
                                    }
                                } );
                            }
                            /*
                            if ( in.isEmpty() )
                            {
                                cluster.create( "default" );
                            }
                            else
                            {
                                try
                                {
                                    cluster.join( "default", new URI( in.get( 0 ).toString() ) );
                                }
                                catch ( URISyntaxException e )
                                {
                                    e.printStackTrace();
                                }
                            }*/
                            break;
                        }
                    }
                }

Replace Anonymous With Lambda org.neo4j.cluster.protocol.cluster.ClusterNetworkTest.ClusterTestScriptDSL.join.joinAction.new ClusterAction.run.submit.new Runnable with () -> {tryClusterConfiguration clusterConfiguration=result.get(); in method public run() : void from class org.neo4j.cluster.protocol.cluster.ClusterNetworkTest.ClusterTestScriptDSL.join.joinAction.new ClusterAction


    @Test
    public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() throws Exception
    {
        final List<Message> sentOut = new LinkedList<Message>();

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.add( (Message) invocation.getArguments()[0] );
            return null;
        } ).when( holder ).offer( Matchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.INSTANCE_ID, "2" ).setHeader( Message.FROM, "ha://2" );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

    @Test
    public void shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() throws Exception
    {
        final List<Message> sentOut = new LinkedList<Message>();

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                sentOut.add( (Message) invocation.getArguments()[0] );
                return null;
            }
        } ).when( holder ).offer( Matchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.INSTANCE_ID, "2" ).setHeader( Message.FROM, "ha://2" );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

Replace Anonymous With Lambda org.neo4j.cluster.protocol.heartbeat.HeartbeatIAmAliveProcessorTest.shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat.offer.when.doAnswer.new Answer with invocation -> {sentOut.add((Message)invocation.getArguments()[0]); in method public shouldCorrectlySetTheInstanceIdHeaderInTheGeneratedHeartbeat() : void from class org.neo4j.cluster.protocol.heartbeat.HeartbeatIAmAliveProcessorTest


    @Test
    public void shouldRevertToInverseUriLookupIfNoInstanceIdHeader() throws Exception
    {
        final List<Message> sentOut = new LinkedList<Message>();
        String instance2UriString = "ha://2";

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( invocation ->
        {
            sentOut.add( (Message) invocation.getArguments()[0] );
            return null;
        } ).when( holder ).offer( Matchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getIdForUri( URI.create( instance2UriString ) ) ).thenReturn( new InstanceId( 2 ) );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.FROM, instance2UriString );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

    @Test
    public void shouldRevertToInverseUriLookupIfNoInstanceIdHeader() throws Exception
    {
        final List<Message> sentOut = new LinkedList<Message>();
        String instance2UriString = "ha://2";

        // Given
        MessageHolder holder = mock( MessageHolder.class );
        // The sender, which adds messages outgoing to the list above.
        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocation ) throws Throwable
            {
                sentOut.add( (Message) invocation.getArguments()[0] );
                return null;
            }
        } ).when( holder ).offer( Matchers.<Message<MessageType>>any() );

        ClusterContext mockContext = mock( ClusterContext.class );
        ClusterConfiguration mockConfiguration = mock( ClusterConfiguration.class );
        when( mockConfiguration.getIdForUri( URI.create( instance2UriString ) ) ).thenReturn( new InstanceId( 2 ) );
        when( mockConfiguration.getMembers() ).thenReturn(
                new HashMap<InstanceId, URI>()
                {{
                        put( new InstanceId( 1 ), URI.create( "ha://1" ) );
                        put( new InstanceId( 2 ), URI.create( "ha://2" ) );
                    }}
        );
        when( mockContext.getConfiguration() ).thenReturn( mockConfiguration );

        HeartbeatIAmAliveProcessor processor = new HeartbeatIAmAliveProcessor( holder, mockContext );

        Message incoming = Message.to( mock( MessageType.class ), URI.create( "ha://someAwesomeInstanceInJapan") )
                .setHeader( Message.FROM, instance2UriString );

        // WHEN
        processor.process( incoming );

        // THEN
        assertEquals( 1, sentOut.size() );
        assertEquals( HeartbeatMessage.i_am_alive, sentOut.get( 0 ).getMessageType() );
        assertEquals( new InstanceId( 2 ), ((HeartbeatMessage.IAmAliveState) sentOut.get( 0 ).getPayload() ).getServer() );
    }

Replace Anonymous With Lambda org.neo4j.cluster.protocol.heartbeat.HeartbeatIAmAliveProcessorTest.shouldRevertToInverseUriLookupIfNoInstanceIdHeader.offer.when.doAnswer.new Answer with invocation -> {sentOut.add((Message)invocation.getArguments()[0]); in method public shouldRevertToInverseUriLookupIfNoInstanceIdHeader() : void from class org.neo4j.cluster.protocol.heartbeat.HeartbeatIAmAliveProcessorTest


    @Override
    public Response<Integer> streamBackTransactions( int responseToSendBack, final int txCount )
    {
        TransactionStream transactions = visitor ->
        {
            for ( int i = 1; i <= txCount; i++ )
            {
                CommittedTransactionRepresentation transaction =
                        createTransaction( TransactionIdStore.BASE_TX_ID + i );
                visitor.visit( transaction );
            }
        };

        return new TransactionStreamResponse<>( responseToSendBack, storeIdToRespondWith, transactions,
                ResourceReleaser.NO_OP );
    }

    @Override
    public Response<Integer> streamBackTransactions( int responseToSendBack, final int txCount )
    {
        TransactionStream transactions = new TransactionStream()
        {
            @Override
            public void accept( Visitor<CommittedTransactionRepresentation,Exception> visitor ) throws Exception
            {
                for ( int i = 1; i <= txCount; i++ )
                {
                    CommittedTransactionRepresentation transaction =
                            createTransaction( TransactionIdStore.BASE_TX_ID + i );
                    visitor.visit( transaction );
                }
            }
        };

        return new TransactionStreamResponse<>( responseToSendBack, storeIdToRespondWith, transactions,
                ResourceReleaser.NO_OP );
    }

Replace Anonymous With Lambda org.neo4j.com.MadeUpServerImplementation.streamBackTransactions.transactions.new TransactionStream with visitor -> {for(int i=1; i <= txCount; i++){CommittedTransactionRepresentation transaction=createTransaction(TransactionIdStore.BASE_TX_ID + i); in method public streamBackTransactions(responseToSendBack int, txCount int) : Response<Integer> from class org.neo4j.com.MadeUpServerImplementation


    @Test
    public void serverContextVerificationCanThrowException() throws Throwable
    {
        final String failureMessage = "I'm failing";
        TxChecksumVerifier failingVerifier = ( txId, checksum ) ->
        {
            throw new FailingException( failureMessage );
        };

        MadeUpServer server = builder.verifier( failingVerifier ).server();
        MadeUpClient client = builder.client();
        addToLifeAndStart( server, client );

        try
        {
            client.multiply( 10, 5 );
            fail( "Should have failed" );
        }
        catch ( Exception e )
        {   // Good
            // TODO catch FailingException instead of Exception and make Server throw the proper
            // one instead of getting a "channel closed".
        }
    }

    @Test
    public void serverContextVerificationCanThrowException() throws Throwable
    {
        final String failureMessage = "I'm failing";
        TxChecksumVerifier failingVerifier = new TxChecksumVerifier()
        {
            @Override
            public void assertMatch( long txId, long checksum )
            {
                throw new FailingException( failureMessage );
            }
        };

        MadeUpServer server = builder.verifier( failingVerifier ).server();
        MadeUpClient client = builder.client();
        addToLifeAndStart( server, client );

        try
        {
            client.multiply( 10, 5 );
            fail( "Should have failed" );
        }
        catch ( Exception e )
        {   // Good
            // TODO catch FailingException instead of Exception and make Server throw the proper
            // one instead of getting a "channel closed".
        }
    }

Replace Anonymous With Lambda org.neo4j.com.TestCommunication.serverContextVerificationCanThrowException.failingVerifier.new TxChecksumVerifier with (txId, checksum) -> {throw new FailingException(failureMessage); in method public serverContextVerificationCanThrowException() : void from class org.neo4j.com.TestCommunication


            @Override
            public Visitor<CommittedTransactionRepresentation,Exception> transactions()
            {
                return element ->
                {
                    // THEN
                    long txId = element.getCommitEntry().getTxId();
                    assertThat( txId, lessThanOrEqualTo( targetTransactionId ) );
                    assertEquals( nextExpectedVisit.incrementAndGet(), txId );

                    // Move the target transaction id forward one step, effectively always keeping it out of reach
                    transactionIdStore.setLastCommittedAndClosedTransactionId(
                            transactionIdStore.getLastCommittedTransactionId() + 1, 0, BASE_TX_COMMIT_TIMESTAMP,
                            3, 4 );
                    return true;
                };
            }

            @Override
            public Visitor<CommittedTransactionRepresentation,Exception> transactions()
            {
                return new Visitor<CommittedTransactionRepresentation,Exception>()
                {
                    @Override
                    public boolean visit( CommittedTransactionRepresentation element )
                    {
                        // THEN
                        long txId = element.getCommitEntry().getTxId();
                        assertThat( txId, lessThanOrEqualTo( targetTransactionId ) );
                        assertEquals( nextExpectedVisit.incrementAndGet(), txId );

                        // Move the target transaction id forward one step, effectively always keeping it out of reach
                        transactionIdStore.setLastCommittedAndClosedTransactionId(
                                transactionIdStore.getLastCommittedTransactionId() + 1, 0, BASE_TX_COMMIT_TIMESTAMP,
                                3, 4 );
                        return true;
                    }
                };
            }

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


    @Test( timeout = TEST_TIMEOUT )
    public void shouldNotFreakOutIfTwoTransactionsDecideToEachAddTheSameProperty() throws Exception
    {
        // GIVEN
        final Barrier.Control barrier = new Barrier.Control();
        final Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            tx.success();
        }

        // WHEN
        t2.execute( (WorkerCommand<Void,Void>) state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                node.setProperty( PROPERTY_KEY, VALUE_1 );
                tx.success();
                barrier.reached();
            }
            return null;
        } );
        try ( Transaction tx = db.beginTx() )
        {
            barrier.await();
            node.setProperty( PROPERTY_KEY, VALUE_2 );
            tx.success();
            barrier.release();
        }

        try ( Transaction tx = db.beginTx() )
        {
            assertEquals( 1, count( node.getPropertyKeys() ) );
            tx.success();
        }
    }

    @Test( timeout = TEST_TIMEOUT )
    public void shouldNotFreakOutIfTwoTransactionsDecideToEachAddTheSameProperty() throws Exception
    {
        // GIVEN
        final Barrier.Control barrier = new Barrier.Control();
        final Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            tx.success();
        }

        // WHEN
        t2.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    node.setProperty( PROPERTY_KEY, VALUE_1 );
                    tx.success();
                    barrier.reached();
                }
                return null;
            }
        } );
        try ( Transaction tx = db.beginTx() )
        {
            barrier.await();
            node.setProperty( PROPERTY_KEY, VALUE_2 );
            tx.success();
            barrier.release();
        }

        try ( Transaction tx = db.beginTx() )
        {
            assertEquals( 1, count( node.getPropertyKeys() ) );
            tx.success();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.shouldNotFreakOutIfTwoTransactionsDecideToEachAddTheSameProperty.execute.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())node.setProperty(PROPERTY_KEY,VALUE_1); in method public shouldNotFreakOutIfTwoTransactionsDecideToEachAddTheSameProperty() : void from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    @Test( timeout = TEST_TIMEOUT )
    public void firstRemoveSecondChangeProperty() throws Exception
    {
        // GIVEN
        final Barrier.Control barrier = new Barrier.Control();
        final Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            node.setProperty( PROPERTY_KEY, VALUE_1 );
            tx.success();
        }

        // WHEN
        Future<Void> future = t2.execute( state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                node.removeProperty( PROPERTY_KEY );
                tx.success();
                barrier.reached();
            }
            return null;
        } );
        try ( Transaction tx = db.beginTx() )
        {
            barrier.await();
            node.setProperty( PROPERTY_KEY, VALUE_2 );
            tx.success();
            barrier.release();
        }

        future.get();
        try ( Transaction tx = db.beginTx() )
        {
            assertEquals( VALUE_2, node.getProperty( PROPERTY_KEY, VALUE_2 ) );
            tx.success();
        }
    }

    @Test( timeout = TEST_TIMEOUT )
    public void firstRemoveSecondChangeProperty() throws Exception
    {
        // GIVEN
        final Barrier.Control barrier = new Barrier.Control();
        final Node node;
        try ( Transaction tx = db.beginTx() )
        {
            node = db.createNode();
            node.setProperty( PROPERTY_KEY, VALUE_1 );
            tx.success();
        }

        // WHEN
        Future<Void> future = t2.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    node.removeProperty( PROPERTY_KEY );
                    tx.success();
                    barrier.reached();
                }
                return null;
            }
        } );
        try ( Transaction tx = db.beginTx() )
        {
            barrier.await();
            node.setProperty( PROPERTY_KEY, VALUE_2 );
            tx.success();
            barrier.release();
        }

        future.get();
        try ( Transaction tx = db.beginTx() )
        {
            assertEquals( VALUE_2, node.getProperty( PROPERTY_KEY, VALUE_2 ) );
            tx.success();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.firstRemoveSecondChangeProperty.future.execute.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())node.removeProperty(PROPERTY_KEY); in method public firstRemoveSecondChangeProperty() : void from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    @Test( timeout = TEST_TIMEOUT )
    public void removeNodeChangeNodeProperty() throws Exception
    {
        // GIVEN
        final Barrier.Control barrier = new Barrier.Control();
        final long nodeId;
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            nodeId = node.getId();
            node.setProperty( PROPERTY_KEY, VALUE_1 );
            tx.success();
        }

        // WHEN
        Future<Void> future = t2.execute( state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                db.getNodeById( nodeId ).delete();
                tx.success();
                barrier.reached();
            }
            return null;
        } );
        try
        {
            try ( Transaction tx = db.beginTx() )
            {
                barrier.await();
                db.getNodeById( nodeId ).setProperty( PROPERTY_KEY, VALUE_2 );
                tx.success();
                barrier.release();
            }
        }
        catch ( TransactionFailureException e )
        {
            // Node was already deleted, fine.
            assertThat( e.getCause(), instanceOf( InvalidRecordException.class ) );
        }

        future.get();
        try ( Transaction tx = db.beginTx() )
        {
            try
            {
                db.getNodeById( nodeId );
                assertEquals( VALUE_2, db.getNodeById( nodeId ).getProperty( PROPERTY_KEY, VALUE_2 ) );
            }
            catch ( NotFoundException e )
            {
                // Fine, its gone
            }
            tx.success();
        }
    }

    @Test( timeout = TEST_TIMEOUT )
    public void removeNodeChangeNodeProperty() throws Exception
    {
        // GIVEN
        final Barrier.Control barrier = new Barrier.Control();
        final long nodeId;
        try ( Transaction tx = db.beginTx() )
        {
            Node node = db.createNode();
            nodeId = node.getId();
            node.setProperty( PROPERTY_KEY, VALUE_1 );
            tx.success();
        }

        // WHEN
        Future<Void> future = t2.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    db.getNodeById( nodeId ).delete();
                    tx.success();
                    barrier.reached();
                }
                return null;
            }
        } );
        try
        {
            try ( Transaction tx = db.beginTx() )
            {
                barrier.await();
                db.getNodeById( nodeId ).setProperty( PROPERTY_KEY, VALUE_2 );
                tx.success();
                barrier.release();
            }
        }
        catch ( TransactionFailureException e )
        {
            // Node was already deleted, fine.
            assertThat( e.getCause(), instanceOf( InvalidRecordException.class ) );
        }

        future.get();
        try ( Transaction tx = db.beginTx() )
        {
            try
            {
                db.getNodeById( nodeId );
                assertEquals( VALUE_2, db.getNodeById( nodeId ).getProperty( PROPERTY_KEY, VALUE_2 ) );
            }
            catch ( NotFoundException e )
            {
                // Fine, its gone
            }
            tx.success();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.removeNodeChangeNodeProperty.future.execute.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())db.getNodeById(nodeId).delete(); in method public removeNodeChangeNodeProperty() : void from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    @Test( timeout = TEST_TIMEOUT )
    public void readOwnChangesFromRacingIndexNoBlock() throws Throwable
    {
        Future<Void> t2Future = t2.execute( state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                createNodeWithProperty( LABEL, PROPERTY_KEY, VALUE_1 );
                assertNodeWith( LABEL, PROPERTY_KEY, VALUE_1 );

                tx.success();
            }
            return null;
        } );

        Future<Void> t3Future = t3.execute( state ->
        {
            try ( Transaction tx = db.beginTx() )
            {
                createAndAwaitIndex( LABEL, PROPERTY_KEY );
                tx.success();
            }
            return null;
        } );

        t3Future.get();
        t2Future.get();

        assertInTxNodeWith( LABEL, PROPERTY_KEY, VALUE_1 );
    }

    @Test( timeout = TEST_TIMEOUT )
    public void readOwnChangesFromRacingIndexNoBlock() throws Throwable
    {
        Future<Void> t2Future = t2.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    createNodeWithProperty( LABEL, PROPERTY_KEY, VALUE_1 );
                    assertNodeWith( LABEL, PROPERTY_KEY, VALUE_1 );

                    tx.success();
                }
                return null;
            }
        } );

        Future<Void> t3Future = t3.execute( new WorkerCommand<Void,Void>()
        {
            @Override
            public Void doWork( Void state ) throws Exception
            {
                try ( Transaction tx = db.beginTx() )
                {
                    createAndAwaitIndex( LABEL, PROPERTY_KEY );
                    tx.success();
                }
                return null;
            }
        } );

        t3Future.get();
        t2Future.get();

        assertInTxNodeWith( LABEL, PROPERTY_KEY, VALUE_1 );
    }

Replace Anonymous With Lambda org.neo4j.kernel.impl.locking.DeferringLocksIT.readOwnChangesFromRacingIndexNoBlock.t2Future.execute.new WorkerCommand<Void,Void> with state -> {try(Transaction tx=db.beginTx())createNodeWithProperty(LABEL,PROPERTY_KEY,VALUE_1); in method public readOwnChangesFromRacingIndexNoBlock() : void from class org.neo4j.kernel.impl.locking.DeferringLocksIT


    @Override
    public void init() throws Throwable
    {
        if ( pullIntervalMillis > 0 )
        {
            intervalJobHandle = scheduler.scheduleRecurring( pullUpdates, () ->
            {
                try
                {
                    updatePuller.pullUpdates();
                }
                catch ( InterruptedException e )
                {
                    log.error( "Pull updates failed", e );
                }
            }, pullIntervalMillis, pullIntervalMillis, TimeUnit.MILLISECONDS );
        }
    }

    @Override
    public void init() throws Throwable
    {
        if ( pullIntervalMillis > 0 )
        {
            intervalJobHandle = scheduler.scheduleRecurring( pullUpdates, new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        updatePuller.pullUpdates();
                    }
                    catch ( InterruptedException e )
                    {
                        log.error( "Pull updates failed", e );
                    }
                }
            }, pullIntervalMillis, pullIntervalMillis, TimeUnit.MILLISECONDS );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.UpdatePullerScheduler.init.scheduleRecurring.new Runnable with () -> {tryupdatePuller.pullUpdates(); in method public init() : void from class org.neo4j.kernel.ha.UpdatePullerScheduler


            @Override
            public Iterable<Slave> prioritize( final Iterable<Slave> slaves )
            {
                final List<Slave> slaveList = sortSlaves( slaves, true );
                if ( slaveList.isEmpty() )
                {
                    return Iterables.empty();
                }
                return () -> new PrefetchingIterator<Slave>()
                {
                    private int start = index.getAndIncrement() % slaveList.size();
                    private int count;

                    @Override
                    protected Slave fetchNextOrNull()
                    {
                        int id = count++;
                        return id <= slaveList.size() ? slaveList.get( (start + id) % slaveList.size() ) : null;
                    }
                };
            }

            @Override
            public Iterable<Slave> prioritize( final Iterable<Slave> slaves )
            {
                final List<Slave> slaveList = sortSlaves( slaves, true );
                if ( slaveList.isEmpty() )
                {
                    return Iterables.empty();
                }
                return new Iterable<Slave>()
                {
                    @Override
                    public Iterator<Slave> iterator()
                    {
                        return new PrefetchingIterator<Slave>()
                        {
                            private int start = index.getAndIncrement() % slaveList.size();
                            private int count;

                            @Override
                            protected Slave fetchNextOrNull()
                            {
                                int id = count++;
                                return id <= slaveList.size() ? slaveList.get( (start + id) % slaveList.size() ) : null;
                            }
                        };
                    }
                };
            }

Replace Anonymous With Lambda org.neo4j.kernel.ha.com.master.SlavePriorities.roundRobin.new SlavePriority.prioritize.new Iterable<Slave> with () -> new PrefetchingIterator<Slave>(){ in method public prioritize(slaves Iterable<Slave>) : Iterable<Slave> from class org.neo4j.kernel.ha.com.master.SlavePriorities.roundRobin.new SlavePriority


    private Callable<Void> slaveCommitter( final Slave slave, final long txId, final CompletionNotifier notifier )
    {
        return () ->
        {
            try
            {
                // TODO Bypass the CommitPusher, now that we have a single thread pulling updates on each slave
                // The CommitPusher is all about batching transaction pushing to slaves, to reduce the overhead
                // of multiple threads pulling the same transactions on each slave. That should be fine now.
//                    slave.pullUpdates( txId );
                pusher.queuePush( slave, txId );

                return null;
            }
            finally
            {
                notifier.completed();
            }
        };
    }

    private Callable<Void> slaveCommitter( final Slave slave, final long txId, final CompletionNotifier notifier )
    {
        return new Callable<Void>()
        {
            @Override
            public Void call()
            {
                try
                {
                    // TODO Bypass the CommitPusher, now that we have a single thread pulling updates on each slave
                    // The CommitPusher is all about batching transaction pushing to slaves, to reduce the overhead
                    // of multiple threads pulling the same transactions on each slave. That should be fine now.
//                    slave.pullUpdates( txId );
                    pusher.queuePush( slave, txId );

                    return null;
                }
                finally
                {
                    notifier.completed();
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.transaction.TransactionPropagator.slaveCommitter.new Callable<Void> with () -> {trypusher.queuePush(slave,txId); in method private slaveCommitter(slave Slave, txId long, notifier CompletionNotifier) : Callable<Void> from class org.neo4j.kernel.ha.transaction.TransactionPropagator


    @Test
    public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable
    {
        final HighlyAvailableGraphDatabase master = cluster.getMaster();
        final HighlyAvailableGraphDatabase slave = cluster.getAnySlave();

        final long nodeId;
        try ( Transaction tx = master.beginTx() )
        {
            nodeId = master.createNode().getId();
            tx.success();
        }

        cluster.sync();

        // When
        final FutureTask<Boolean> result = new FutureTask<>( () ->
        {
            try ( Transaction tx = slave.beginTx() )
            {
                tx.acquireWriteLock( slave.getNodeById( nodeId ) );
            }
            catch ( Exception e )
            {
                return contains( e, TransactionFailureException.class );
            }
            // Fail otherwise
            return false;
        } );

        master.getDependencyResolver()
                .resolveDependency( LifeSupport.class )
                .addLifecycleListener( ( instance, from, to ) ->
                {
                    if ( instance.getClass().getName().contains( "DatabaseAvailability" ) &&
                         to == LifecycleStatus.STOPPED )
                    {
                        result.run();
                    }
                } );

        master.shutdown();

        // Then
        assertThat( result.get(), equalTo( true ) );
    }

    @Test
    public void givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() throws Throwable
    {
        final HighlyAvailableGraphDatabase master = cluster.getMaster();
        final HighlyAvailableGraphDatabase slave = cluster.getAnySlave();

        final long nodeId;
        try ( Transaction tx = master.beginTx() )
        {
            nodeId = master.createNode().getId();
            tx.success();
        }

        cluster.sync();

        // When
        final FutureTask<Boolean> result = new FutureTask<>( new Callable<Boolean>()
        {
            @Override
            public Boolean call() throws Exception
            {
                try ( Transaction tx = slave.beginTx() )
                {
                    tx.acquireWriteLock( slave.getNodeById( nodeId ) );
                }
                catch ( Exception e )
                {
                    return contains( e, TransactionFailureException.class );
                }
                // Fail otherwise
                return false;
            }
        } );

        master.getDependencyResolver()
                .resolveDependency( LifeSupport.class )
                .addLifecycleListener( new LifecycleListener()
                {
                    @Override
                    public void notifyStatusChanged( Object instance, LifecycleStatus from, LifecycleStatus to )
                    {
                        if ( instance.getClass().getName().contains( "DatabaseAvailability" ) &&
                             to == LifecycleStatus.STOPPED )
                        {
                            result.run();
                        }
                    }
                } );

        master.shutdown();

        // Then
        assertThat( result.get(), equalTo( true ) );
    }

Replace Anonymous With Lambda org.neo4j.ha.ClusterTransactionIT.givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave.result.new FutureTask<>.new Callable<Boolean> with () -> {try(Transaction tx=slave.beginTx())tx.acquireWriteLock(slave.getNodeById(nodeId)); in method public givenClusterWhenShutdownMasterThenCannotStartTransactionOnSlave() : void from class org.neo4j.ha.ClusterTransactionIT


    private Listener<Node> andIndexInto( final String indexName )
    {
        return node ->
        {
            Index<Node> index = node.getGraphDatabase().index().forNodes( indexName );
            for ( String key : node.getPropertyKeys() )
            {
                index.add( node, key, node.getProperty( key ) );
            }
        };
    }

    private Listener<Node> andIndexInto( final String indexName )
    {
        return new Listener<Node>()
        {
            @Override
            public void receive( Node node )
            {
                Index<Node> index = node.getGraphDatabase().index().forNodes( indexName );
                for ( String key : node.getPropertyKeys() )
                {
                    index.add( node, key, node.getProperty( key ) );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.ha.TestBranchedData.andIndexInto.new Listener<Node> with node -> {Index<Node> index=node.getGraphDatabase().index().forNodes(indexName); in method private andIndexInto(indexName String) : Listener<Node> from class org.neo4j.ha.TestBranchedData


    public static Future<LegacyDatabase> start( String classpath, File storeDir, Map<String, String> config )
            throws Exception
    {
        List<String> args = new ArrayList<String>();
        args.add( storeDir.getAbsolutePath() );
        int rmiPort = 7000 + parseInt( config.get( "ha.server_id" ) );
        args.add( "" + rmiPort );
        args.addAll( asList( new Args( config ).asArgs() ) );
        final Process process = execJava( appendNecessaryTestClasses( classpath ),
                LegacyDatabaseImpl.class.getName(), args.toArray( new String[0] ) );
        new ProcessStreamHandler( process, false ).launch();

        final RmiLocation rmiLocation = rmiLocation( rmiPort );
        ExecutorService executor = newSingleThreadExecutor();
        Future<LegacyDatabase> future = executor.submit( () ->
        {
            long endTime = currentTimeMillis() + SECONDS.toMillis( 10000 );
            while ( currentTimeMillis() < endTime )
            {
                try
                {
                    return (LegacyDatabase) rmiLocation.getBoundObject();
                }
                catch ( RemoteException e )
                {
                    // OK
                    sleep( 100 );
                }
            }
            process.destroy();
            throw new IllegalStateException( "Couldn't get remote to legacy database" );
        } );
        executor.shutdown();
        return future;
    }

    public static Future<LegacyDatabase> start( String classpath, File storeDir, Map<String, String> config )
            throws Exception
    {
        List<String> args = new ArrayList<String>();
        args.add( storeDir.getAbsolutePath() );
        int rmiPort = 7000 + parseInt( config.get( "ha.server_id" ) );
        args.add( "" + rmiPort );
        args.addAll( asList( new Args( config ).asArgs() ) );
        final Process process = execJava( appendNecessaryTestClasses( classpath ),
                LegacyDatabaseImpl.class.getName(), args.toArray( new String[0] ) );
        new ProcessStreamHandler( process, false ).launch();

        final RmiLocation rmiLocation = rmiLocation( rmiPort );
        ExecutorService executor = newSingleThreadExecutor();
        Future<LegacyDatabase> future = executor.submit( new Callable<LegacyDatabase>()
        {
            @Override
            public LegacyDatabase call() throws Exception
            {
                long endTime = currentTimeMillis() + SECONDS.toMillis( 10000 );
                while ( currentTimeMillis() < endTime )
                {
                    try
                    {
                        return (LegacyDatabase) rmiLocation.getBoundObject();
                    }
                    catch ( RemoteException e )
                    {
                        // OK
                        sleep( 100 );
                    }
                }
                process.destroy();
                throw new IllegalStateException( "Couldn't get remote to legacy database" );
            }
        } );
        executor.shutdown();
        return future;
    }

Replace Anonymous With Lambda org.neo4j.ha.upgrade.LegacyDatabaseImpl.start.future.submit.new Callable<LegacyDatabase> with () -> {long endTime=currentTimeMillis() + SECONDS.toMillis(10000); in method public start(classpath String, storeDir File, config Map<String,String>) : Future<LegacyDatabase> from class org.neo4j.ha.upgrade.LegacyDatabaseImpl


    private static Response<Void> voidResponseWithTransactionLogs()
    {
        return new TransactionStreamResponse<>( null, StoreId.DEFAULT, visitor ->
        {
            for ( int i = 1; i <= TX_LOG_COUNT; i++ )
            {
                visitor.visit( committedTransactionRepresentation( i ) );
            }
        }, ResourceReleaser.NO_OP );
    }

    private static Response<Void> voidResponseWithTransactionLogs()
    {
        return new TransactionStreamResponse<>( null, StoreId.DEFAULT, new TransactionStream()
        {
            @Override
            public void accept( Visitor<CommittedTransactionRepresentation,Exception> visitor ) throws Exception
            {
                for ( int i = 1; i <= TX_LOG_COUNT; i++ )
                {
                    visitor.visit( committedTransactionRepresentation( i ) );
                }
            }
        }, ResourceReleaser.NO_OP );
    }

Replace Anonymous With Lambda org.neo4j.ha.upgrade.MasterClientTest.voidResponseWithTransactionLogs.new TransactionStreamResponse<>.new TransactionStream with visitor -> {for(int i=1; i <= TX_LOG_COUNT; i++){visitor.visit(committedTransactionRepresentation(i)); in method private voidResponseWithTransactionLogs() : Response<Void> from class org.neo4j.ha.upgrade.MasterClientTest


    @Test
    public void concurrentStartupShouldWork() throws Exception
    {
        // Ensures that the instances don't race to create the test's base directory and only care about their own.
        testDirectory.directory( "nothingToSeeHereMoveAlong" );
        StringBuffer initialHostsBuffer = new StringBuffer( "127.0.0.1:5001" );
        for ( int i = 2; i <= INSTANCE_COUNT; i++ )
        {
            initialHostsBuffer.append( ",127.0.0.1:500" + i );
        }
        final String initialHosts = initialHostsBuffer.toString();
        final CyclicBarrier barrier = new CyclicBarrier( INSTANCE_COUNT );
        final List<Thread> daThreads = new ArrayList<Thread>( INSTANCE_COUNT );
        final HighlyAvailableGraphDatabase[] dbs = new HighlyAvailableGraphDatabase[INSTANCE_COUNT];

        for ( int i = 1; i <= INSTANCE_COUNT; i++ )
        {
            final int finalI = i;

            Thread t = new Thread( () ->
            {
                try
                {
                    barrier.await();
                    dbs[finalI - 1] = startDbAtBase( finalI, initialHosts );
                }
                catch ( InterruptedException | BrokenBarrierException e )
                {
                    throw new RuntimeException( e );
                }
            } );
            daThreads.add( t );
            t.start();
        }

        for ( Thread daThread : daThreads )
        {
            daThread.join();
        }

        boolean masterDone = false;

        for ( HighlyAvailableGraphDatabase db : dbs )
        {
            if ( db.isMaster() )
            {
                if ( masterDone )
                {
                    throw new Exception( "Two masters discovered" );
                }
                masterDone = true;
            }
            try ( Transaction tx = db.beginTx() )
            {
                db.createNode();
                tx.success();
            }
        }

        assertTrue( masterDone );

        for ( HighlyAvailableGraphDatabase db : dbs )
        {
            db.shutdown();
        }
    }

    @Test
    public void concurrentStartupShouldWork() throws Exception
    {
        // Ensures that the instances don't race to create the test's base directory and only care about their own.
        testDirectory.directory( "nothingToSeeHereMoveAlong" );
        StringBuffer initialHostsBuffer = new StringBuffer( "127.0.0.1:5001" );
        for ( int i = 2; i <= INSTANCE_COUNT; i++ )
        {
            initialHostsBuffer.append( ",127.0.0.1:500" + i );
        }
        final String initialHosts = initialHostsBuffer.toString();
        final CyclicBarrier barrier = new CyclicBarrier( INSTANCE_COUNT );
        final List<Thread> daThreads = new ArrayList<Thread>( INSTANCE_COUNT );
        final HighlyAvailableGraphDatabase[] dbs = new HighlyAvailableGraphDatabase[INSTANCE_COUNT];

        for ( int i = 1; i <= INSTANCE_COUNT; i++ )
        {
            final int finalI = i;

            Thread t = new Thread( new Runnable()
            {
                @Override
                public void run()
                {
                    try
                    {
                        barrier.await();
                        dbs[finalI - 1] = startDbAtBase( finalI, initialHosts );
                    }
                    catch ( InterruptedException | BrokenBarrierException e )
                    {
                        throw new RuntimeException( e );
                    }
                }
            } );
            daThreads.add( t );
            t.start();
        }

        for ( Thread daThread : daThreads )
        {
            daThread.join();
        }

        boolean masterDone = false;

        for ( HighlyAvailableGraphDatabase db : dbs )
        {
            if ( db.isMaster() )
            {
                if ( masterDone )
                {
                    throw new Exception( "Two masters discovered" );
                }
                masterDone = true;
            }
            try ( Transaction tx = db.beginTx() )
            {
                db.createNode();
                tx.success();
            }
        }

        assertTrue( masterDone );

        for ( HighlyAvailableGraphDatabase db : dbs )
        {
            db.shutdown();
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.ConcurrentInstanceStartupIT.concurrentStartupShouldWork.t.new Thread.new Runnable with () -> {trybarrier.await(); in method public concurrentStartupShouldWork() : void from class org.neo4j.kernel.ha.ConcurrentInstanceStartupIT


    @Test
    public void testMasterSwitchHappensOnKillMinus9() throws Exception
    {
        Process proc = null;
        HighlyAvailableGraphDatabase dbWithId2 = null;
        HighlyAvailableGraphDatabase dbWithId3 = null;
        HighlyAvailableGraphDatabase oldMaster = null;
        try
        {
            proc = run( 1 );
            dbWithId2 = startDb( 2, path( 2 ) );
            dbWithId3 = startDb( 3, path( 3 ) );

            waitUntilAllProperlyAvailable( dbWithId2, 1, MASTER, 2, SLAVE, 3, SLAVE );
            waitUntilAllProperlyAvailable( dbWithId3, 1, MASTER, 2, SLAVE, 3, SLAVE );

            final CountDownLatch newMasterAvailableLatch = new CountDownLatch( 1 );
            dbWithId2.getDependencyResolver().resolveDependency( ClusterClient.class ).addAtomicBroadcastListener(
                    value ->
                    {
                        try
                        {
                            Object event = new AtomicBroadcastSerializer( new ObjectStreamFactory(), new
                                    ObjectStreamFactory() ).receive( value );
                            if ( event instanceof MemberIsAvailable )
                            {
                                if ( HighAvailabilityModeSwitcher.MASTER.equals( ((MemberIsAvailable) event)
                                        .getRole() ) )
                                {
                                    newMasterAvailableLatch.countDown();
                                }
                            }
                        }
                        catch ( Exception e )
                        {
                            fail( e.toString() );
                        }
                    } );
            proc.destroy();
            proc = null;

            assertTrue( newMasterAvailableLatch.await( 60, SECONDS ) );

            assertTrue( dbWithId2.isMaster() );
            assertTrue( !dbWithId3.isMaster() );

            // Ensure that everyone has marked the killed instance as failed, otherwise it cannot rejoin
            waitUntilAllProperlyAvailable( dbWithId2, 1, UNKNOWN, 2, MASTER, 3, SLAVE );
            waitUntilAllProperlyAvailable( dbWithId3, 1, UNKNOWN, 2, MASTER, 3, SLAVE );

            oldMaster = startDb( 1, path( 1 ) );
            long oldMasterNode = createNamedNode( oldMaster, "Old master" );
            assertEquals( oldMasterNode, getNamedNode( dbWithId2, "Old master" ) );
        }
        finally
        {
            if ( proc != null )
            {
                proc.destroy();
            }
            if ( oldMaster != null )
            {
                oldMaster.shutdown();
            }
            if ( dbWithId2 != null )
            {
                dbWithId2.shutdown();
            }
            if ( dbWithId3 != null )
            {
                dbWithId3.shutdown();
            }
        }
    }

    @Test
    public void testMasterSwitchHappensOnKillMinus9() throws Exception
    {
        Process proc = null;
        HighlyAvailableGraphDatabase dbWithId2 = null;
        HighlyAvailableGraphDatabase dbWithId3 = null;
        HighlyAvailableGraphDatabase oldMaster = null;
        try
        {
            proc = run( 1 );
            dbWithId2 = startDb( 2, path( 2 ) );
            dbWithId3 = startDb( 3, path( 3 ) );

            waitUntilAllProperlyAvailable( dbWithId2, 1, MASTER, 2, SLAVE, 3, SLAVE );
            waitUntilAllProperlyAvailable( dbWithId3, 1, MASTER, 2, SLAVE, 3, SLAVE );

            final CountDownLatch newMasterAvailableLatch = new CountDownLatch( 1 );
            dbWithId2.getDependencyResolver().resolveDependency( ClusterClient.class ).addAtomicBroadcastListener(
                    new AtomicBroadcastListener()
                    {
                        @Override
                        public void receive( Payload value )
                        {
                            try
                            {
                                Object event = new AtomicBroadcastSerializer( new ObjectStreamFactory(), new
                                        ObjectStreamFactory() ).receive( value );
                                if ( event instanceof MemberIsAvailable )
                                {
                                    if ( HighAvailabilityModeSwitcher.MASTER.equals( ((MemberIsAvailable) event)
                                            .getRole() ) )
                                    {
                                        newMasterAvailableLatch.countDown();
                                    }
                                }
                            }
                            catch ( Exception e )
                            {
                                fail( e.toString() );
                            }
                        }
                    } );
            proc.destroy();
            proc = null;

            assertTrue( newMasterAvailableLatch.await( 60, SECONDS ) );

            assertTrue( dbWithId2.isMaster() );
            assertTrue( !dbWithId3.isMaster() );

            // Ensure that everyone has marked the killed instance as failed, otherwise it cannot rejoin
            waitUntilAllProperlyAvailable( dbWithId2, 1, UNKNOWN, 2, MASTER, 3, SLAVE );
            waitUntilAllProperlyAvailable( dbWithId3, 1, UNKNOWN, 2, MASTER, 3, SLAVE );

            oldMaster = startDb( 1, path( 1 ) );
            long oldMasterNode = createNamedNode( oldMaster, "Old master" );
            assertEquals( oldMasterNode, getNamedNode( dbWithId2, "Old master" ) );
        }
        finally
        {
            if ( proc != null )
            {
                proc.destroy();
            }
            if ( oldMaster != null )
            {
                oldMaster.shutdown();
            }
            if ( dbWithId2 != null )
            {
                dbWithId2.shutdown();
            }
            if ( dbWithId3 != null )
            {
                dbWithId3.shutdown();
            }
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.HardKillIT.testMasterSwitchHappensOnKillMinus9.addAtomicBroadcastListener.new AtomicBroadcastListener with value -> {tryObject event=new AtomicBroadcastSerializer(new ObjectStreamFactory(),new ObjectStreamFactory()).receive(value); in method public testMasterSwitchHappensOnKillMinus9() : void from class org.neo4j.kernel.ha.HardKillIT


        @Override
        public WorkerCommand<Object,Boolean> createConstraint( final HighlyAvailableGraphDatabase db, final String type,
                final String property )
        {
            return state ->
            {
                boolean constraintCreationFailed = false;

                try ( Transaction tx = db.beginTx() )
                {
                    db.schema().constraintFor( label( type ) ).assertPropertyIsUnique( property ).create();
                    tx.success();
                }
                catch ( ConstraintViolationException e )
                {
                /* Unable to create constraint since it is not consistent with existing data. */
                    constraintCreationFailed = true;
                }

                return constraintCreationFailed;
            };
        }

        @Override
        public WorkerCommand<Object,Boolean> createConstraint( final HighlyAvailableGraphDatabase db, final String type,
                final String property )
        {
            return new WorkerCommand<Object,Boolean>()
            {
                @Override
                public Boolean doWork( Object state ) throws Exception
                {
                    boolean constraintCreationFailed = false;

                    try ( Transaction tx = db.beginTx() )
                    {
                        db.schema().constraintFor( label( type ) ).assertPropertyIsUnique( property ).create();
                        tx.success();
                    }
                    catch ( ConstraintViolationException e )
                    {
                    /* Unable to create constraint since it is not consistent with existing data. */
                        constraintCreationFailed = true;
                    }

                    return constraintCreationFailed;
                }
            };
        }

Replace Anonymous With Lambda org.neo4j.kernel.ha.PropertyConstraintsStressIT.UNIQUE_PROPERTY_CONSTRAINT_OPS.new ConstraintOperations.createConstraint.new WorkerCommand<Object,Boolean> with state -> {boolean constraintCreationFailed=false; in method public createConstraint(db HighlyAvailableGraphDatabase, type String, property String) : WorkerCommand<Object,Boolean> from class org.neo4j.kernel.ha.PropertyConstraintsStressIT.UNIQUE_PROPERTY_CONSTRAINT_OPS.new ConstraintOperations


    /**
     * Inserts a bunch of new nodes with the label and property key currently set in the fields in this class, where
     * running this method twice will insert nodes with duplicate property values, assuming property key or label has
     * not changed.
     */
    private WorkerCommand<Object,Integer> performInserts( final HighlyAvailableGraphDatabase slave,
            final boolean constraintCompliant )
    {
        return state ->
        {
            int i = 0;

            try
            {
                for (; i < 100; i++ )
                {
                    try ( Transaction tx = slave.beginTx() )
                    {
                        constraintOps.createEntity( slave, labelOrRelType, property, "value" + i,
                                constraintCompliant );
                        tx.success();
                    }
                }
            }
            catch ( TransactionFailureException | TransientTransactionFailureException e )
            {
                // Swallowed on purpose, we except it to fail sometimes due to either
                //  - constraint violation on master
                //  - concurrent schema operation on master
            }
            catch ( ConstraintViolationException e )
            {
                // Constraint violation detected on slave while building transaction
            }
            catch ( ComException e )
            {
                // Happens sometimes, cause:
                // - The lock session requested to start is already in use.
                //   Please retry your request in a few seconds.
            }
            return i;
        };
    }

    /**
     * Inserts a bunch of new nodes with the label and property key currently set in the fields in this class, where
     * running this method twice will insert nodes with duplicate property values, assuming property key or label has
     * not changed.
     */
    private WorkerCommand<Object,Integer> performInserts( final HighlyAvailableGraphDatabase slave,
            final boolean constraintCompliant )
    {
        return new WorkerCommand<Object,Integer>()
        {
            @Override
            public Integer doWork( Object state ) throws Exception
            {
                int i = 0;

                try
                {
                    for (; i < 100; i++ )
                    {
                        try ( Transaction tx = slave.beginTx() )
                        {
                            constraintOps.createEntity( slave, labelOrRelType, property, "value" + i,
                                    constraintCompliant );
                            tx.success();
                        }
                    }
                }
                catch ( TransactionFailureException | TransientTransactionFailureException e )
                {
                    // Swallowed on purpose, we except it to fail sometimes due to either
                    //  - constraint violation on master
                    //  - concurrent schema operation on master
                }
                catch ( ConstraintViolationException e )
                {
                    // Constraint violation detected on slave while building transaction
                }
                catch ( ComException e )
                {
                    // Happens sometimes, cause:
                    // - The lock session requested to start is already in use.
                    //   Please retry your request in a few seconds.
                }
                return i;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.PropertyConstraintsStressIT.performInserts.new WorkerCommand<Object,Integer> with state -> {int i=0; in method private performInserts(slave HighlyAvailableGraphDatabase, constraintCompliant boolean) : WorkerCommand<Object,Integer> from class org.neo4j.kernel.ha.PropertyConstraintsStressIT


    private static WorkerCommand<Object,Boolean> createPropertyExistenceConstraintCommand(
            final GraphDatabaseService db, final String query )
    {
        return state ->
        {
            boolean constraintCreationFailed = false;

            try ( Transaction tx = db.beginTx() )
            {
                db.execute( query );
                tx.success();
            }
            catch ( QueryExecutionException e )
            {
                System.out.println( "Constraint failed: " + e.getMessage() );
                if ( Exceptions.rootCause( e ) instanceof ConstraintValidationException )
                {
                    // Unable to create constraint since it is not consistent with existing data
                    constraintCreationFailed = true;
                }
                else
                {
                    throw e;
                }
            }

            if ( !constraintCreationFailed )
            {
                System.out.println( "Constraint created: " + query );
            }

            return constraintCreationFailed;
        };
    }

    private static WorkerCommand<Object,Boolean> createPropertyExistenceConstraintCommand(
            final GraphDatabaseService db, final String query )
    {
        return new WorkerCommand<Object,Boolean>()
        {
            @Override
            public Boolean doWork( Object state ) throws Exception
            {
                boolean constraintCreationFailed = false;

                try ( Transaction tx = db.beginTx() )
                {
                    db.execute( query );
                    tx.success();
                }
                catch ( QueryExecutionException e )
                {
                    System.out.println( "Constraint failed: " + e.getMessage() );
                    if ( Exceptions.rootCause( e ) instanceof ConstraintValidationException )
                    {
                        // Unable to create constraint since it is not consistent with existing data
                        constraintCreationFailed = true;
                    }
                    else
                    {
                        throw e;
                    }
                }

                if ( !constraintCreationFailed )
                {
                    System.out.println( "Constraint created: " + query );
                }

                return constraintCreationFailed;
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.PropertyConstraintsStressIT.createPropertyExistenceConstraintCommand.new WorkerCommand<Object,Boolean> with state -> {boolean constraintCreationFailed=false; in method private createPropertyExistenceConstraintCommand(db GraphDatabaseService, query String) : WorkerCommand<Object,Boolean> from class org.neo4j.kernel.ha.PropertyConstraintsStressIT


    @Test
    public void shouldThrowIfPullerBecomesInactiveWhileWaitingStrict() throws Exception
    {
        // GIVEN
        Condition condition = mock( Condition.class );

        when( condition.evaluate( anyInt(), anyInt() ) ).thenAnswer( invocation ->
        {
            updatePuller.stop();
            return false;
        } );

        // WHEN
        try
        {
            updatePuller.pullUpdates( condition, true );
            fail( "Should have thrown" );
        }
        catch ( IllegalStateException e )
        {   // THEN Good
            verify( condition ).evaluate( anyInt(), anyInt() );
        }
    }

    @Test
    public void shouldThrowIfPullerBecomesInactiveWhileWaitingStrict() throws Exception
    {
        // GIVEN
        Condition condition = mock( Condition.class );

        when( condition.evaluate( anyInt(), anyInt() ) ).thenAnswer( new Answer<Boolean>()
        {
            @Override
            public Boolean answer( InvocationOnMock invocation ) throws Throwable
            {
                updatePuller.stop();
                return false;
            }
        } );

        // WHEN
        try
        {
            updatePuller.pullUpdates( condition, true );
            fail( "Should have thrown" );
        }
        catch ( IllegalStateException e )
        {   // THEN Good
            verify( condition ).evaluate( anyInt(), anyInt() );
        }
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.SlaveUpdatePullerTest.shouldThrowIfPullerBecomesInactiveWhileWaitingStrict.thenAnswer.new Answer<Boolean> with invocation -> {updatePuller.stop(); in method public shouldThrowIfPullerBecomesInactiveWhileWaitingStrict() : void from class org.neo4j.kernel.ha.SlaveUpdatePullerTest


    @Test
    public void updatesPulledAndPullingScheduledOnSwitchToSlave() throws Throwable
    {
        SwitchToSlaveCopyThenBranch switchToSlave = newSwitchToSlaveSpy();

        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
        JobScheduler jobScheduler = mock( JobScheduler.class );
        LifeSupport communicationLife = mock( LifeSupport.class );
        URI localhost = getLocalhostUri();
        final UpdatePullerScheduler pullerScheduler =
                new UpdatePullerScheduler( jobScheduler, NullLogProvider.getInstance(), updatePuller, 10L );

        when( pullerFactory.createUpdatePullerScheduler( updatePuller ) ).thenReturn( pullerScheduler );
        // emulate lifecycle start call on scheduler
        doAnswer( invocationOnMock ->
        {
            pullerScheduler.init();
            return null;
        } ).when( communicationLife ).start();

        switchToSlave.switchToSlave( communicationLife, localhost, localhost, mock( CancellationRequest.class ) );

        verify( updatePuller ).tryPullUpdates();
        verify( communicationLife ).add( pullerScheduler );
        verify( jobScheduler ).scheduleRecurring( eq( JobScheduler.Groups.pullUpdates ), any( Runnable.class ),
                eq( 10L ), eq( 10L ), eq( TimeUnit.MILLISECONDS ) );
    }

    @Test
    public void updatesPulledAndPullingScheduledOnSwitchToSlave() throws Throwable
    {
        SwitchToSlaveCopyThenBranch switchToSlave = newSwitchToSlaveSpy();

        when( fs.fileExists( any( File.class ) ) ).thenReturn( true );
        JobScheduler jobScheduler = mock( JobScheduler.class );
        LifeSupport communicationLife = mock( LifeSupport.class );
        URI localhost = getLocalhostUri();
        final UpdatePullerScheduler pullerScheduler =
                new UpdatePullerScheduler( jobScheduler, NullLogProvider.getInstance(), updatePuller, 10L );

        when( pullerFactory.createUpdatePullerScheduler( updatePuller ) ).thenReturn( pullerScheduler );
        // emulate lifecycle start call on scheduler
        doAnswer( new Answer()
        {
            @Override
            public Object answer( InvocationOnMock invocationOnMock ) throws Throwable
            {
                pullerScheduler.init();
                return null;
            }
        } ).when( communicationLife ).start();

        switchToSlave.switchToSlave( communicationLife, localhost, localhost, mock( CancellationRequest.class ) );

        verify( updatePuller ).tryPullUpdates();
        verify( communicationLife ).add( pullerScheduler );
        verify( jobScheduler ).scheduleRecurring( eq( JobScheduler.Groups.pullUpdates ), any( Runnable.class ),
                eq( 10L ), eq( 10L ), eq( TimeUnit.MILLISECONDS ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.SwitchToSlaveCopyThenBranchTest.updatesPulledAndPullingScheduledOnSwitchToSlave.start.when.doAnswer.new Answer with invocationOnMock -> {pullerScheduler.init(); in method public updatesPulledAndPullingScheduledOnSwitchToSlave() : void from class org.neo4j.kernel.ha.cluster.SwitchToSlaveCopyThenBranchTest


    private static Runnable slavesConsumingRunnable( final HighAvailabilitySlaves haSlaves )
    {
        return () ->
        {
            for ( Slave slave : haSlaves.getSlaves() )
            {
                assertNotNull( slave );
            }
        };
    }

    private static Runnable slavesConsumingRunnable( final HighAvailabilitySlaves haSlaves )
    {
        return new Runnable()
        {
            @Override
            public void run()
            {
                for ( Slave slave : haSlaves.getSlaves() )
                {
                    assertNotNull( slave );
                }
            }
        };
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.cluster.member.HighAvailabilitySlavesTest.slavesConsumingRunnable.new Runnable with () -> {for(Slave slave: haSlaves.getSlaves()){assertNotNull(slave); in method private slavesConsumingRunnable(haSlaves HighAvailabilitySlaves) : Runnable from class org.neo4j.kernel.ha.cluster.member.HighAvailabilitySlavesTest


    private void oneRound() throws Throwable
    {
        // GIVEN a cluster and a node
        final String key = "key";
        ManagedCluster cluster = clusterRule.startCluster();
        final GraphDatabaseService master = cluster.getMaster();
        final long nodeId = createNode( master );
        cluster.sync();

        // and a bunch of workers contending on that node, each changing it
        Workers<Runnable> transactors = new Workers<>( "Transactors" );
        final AtomicInteger successes = new AtomicInteger();
        final AtomicBoolean end = new AtomicBoolean();
        for ( int i = 0; i < 10; i++ )
        {
            transactors.start( () ->
            {
                Random random = ThreadLocalRandom.current();
                while ( !end.get() )
                {
                    boolean committed = true;
                    try ( Transaction tx = master.beginTx() )
                    {
                        Node node = master.getNodeById( nodeId );

                        // Acquiring lock, read int property value, increment, set incremented int property
                        // should not break under any circumstances.
                        tx.acquireWriteLock( node );
                        node.setProperty( key, (Integer) node.getProperty( key, 0 ) + 1 );
                        // Throw in relationship for good measure
                        node.createRelationshipTo( master.createNode(), TEST );

                        Thread.sleep( random.nextInt( 1_000 ) );
                        tx.success();
                    }
                    catch ( Throwable e )
                    {
                        // It's OK
                        committed = false;
                    }
                    if ( committed )
                    {
                        successes.incrementAndGet();
                    }
                }
            } );
        }

        // WHEN entering a period of induced cluster instabilities
        reelectTheSameMasterMakingItGoToPendingAndBack( cluster );

        // ... letting transactions run a bit after the role switch as well.
        long targetSuccesses = successes.get() + 20;
        while ( successes.get() < targetSuccesses )
        {
            Thread.sleep( 100 );
        }
        end.set( true );
        transactors.awaitAndThrowOnError( RuntimeException.class );

        // THEN verify that the count is equal to the number of successful transactions
        assertEquals( successes.get(), getNodePropertyValue( master, nodeId, key ) );
    }

    private void oneRound() throws Throwable
    {
        // GIVEN a cluster and a node
        final String key = "key";
        ManagedCluster cluster = clusterRule.startCluster();
        final GraphDatabaseService master = cluster.getMaster();
        final long nodeId = createNode( master );
        cluster.sync();

        // and a bunch of workers contending on that node, each changing it
        Workers<Runnable> transactors = new Workers<>( "Transactors" );
        final AtomicInteger successes = new AtomicInteger();
        final AtomicBoolean end = new AtomicBoolean();
        for ( int i = 0; i < 10; i++ )
        {
            transactors.start( new Runnable()
            {
                @Override
                public void run()
                {
                    Random random = ThreadLocalRandom.current();
                    while ( !end.get() )
                    {
                        boolean committed = true;
                        try ( Transaction tx = master.beginTx() )
                        {
                            Node node = master.getNodeById( nodeId );

                            // Acquiring lock, read int property value, increment, set incremented int property
                            // should not break under any circumstances.
                            tx.acquireWriteLock( node );
                            node.setProperty( key, (Integer) node.getProperty( key, 0 ) + 1 );
                            // Throw in relationship for good measure
                            node.createRelationshipTo( master.createNode(), TEST );

                            Thread.sleep( random.nextInt( 1_000 ) );
                            tx.success();
                        }
                        catch ( Throwable e )
                        {
                            // It's OK
                            committed = false;
                        }
                        if ( committed )
                        {
                            successes.incrementAndGet();
                        }
                    }
                }
            } );
        }

        // WHEN entering a period of induced cluster instabilities
        reelectTheSameMasterMakingItGoToPendingAndBack( cluster );

        // ... letting transactions run a bit after the role switch as well.
        long targetSuccesses = successes.get() + 20;
        while ( successes.get() < targetSuccesses )
        {
            Thread.sleep( 100 );
        }
        end.set( true );
        transactors.awaitAndThrowOnError( RuntimeException.class );

        // THEN verify that the count is equal to the number of successful transactions
        assertEquals( successes.get(), getNodePropertyValue( master, nodeId, key ) );
    }

Replace Anonymous With Lambda org.neo4j.kernel.ha.transaction.TransactionThroughMasterSwitchStressIT.oneRound.start.new Runnable with () -> {Random random=ThreadLocalRandom.current(); in method private oneRound() : void from class org.neo4j.kernel.ha.transaction.TransactionThroughMasterSwitchStressIT