javanettysendasync

Netty - sendAsync() group null pointer exception


I am trying to send messages between two processes in Java, using Atomix and Netty. I have a program called Starter that is responsible to send a Message to all the running processes that are waiting for that message.

This is Starter:

Address[] network = {
            Address.from("localhost:23450"),
            Address.from("localhost:23451"),
            Address.from("localhost:23452"),
            Address.from("localhost:23453")
    };

    Serializer s = new SerializerBuilder().build();

    ExecutorService es = Executors.newSingleThreadExecutor();

    ManagedMessagingService ms = NettyMessagingService.builder()
            .withAddress(Address.from("localhost:23459"))
            .build();

    ms.registerHandler("start", (o,m)->{
        System.out.println("Hello "+s.decode(m)+" from "+o);
    }, es);

    ms.sendAsync(Address.from("localhost:23459"), "start", s.encode("start"));

    for (int i = 0; i < network.length; i++) {
        ms.sendAsync(network[i], "start", s.encode("start"));
    }

This is the process:

Address[] network = {
        Address.from("localhost:23450"),
        Address.from("localhost:23451"),
        Address.from("localhost:23452"),
        Address.from("localhost:23453")
    };

    int id = Integer.parseInt(args[0]);

    Serializer s = new SerializerBuilder().addType(Msg.class).build();

    ManagedMessagingService ms = NettyMessagingService.builder()
                    .withAddress(network[id])
                    .build();

    ExecutorService es = Executors.newSingleThreadExecutor();
    ExecutorService es2 = Executors.newSingleThreadExecutor();

    ms.registerHandler("leader", (o,m) -> {
        int i = s.decode(m);

        if(leader < i){
            leader = i;
            System.out.println("Leader updated to: " + i);
        }
        else{
            System.out.println("Received: " + i + ". Not updated.");
        }
    }, es);

    ms.registerHandler("start", (o,m) -> {
        for(int i=0; i < network.length ; i++ ){
            ms.sendAsync(network[i],"leader", s.encode(id));
        }
        System.out.println("Started");
    },es2);

Each of the running processes has an ID (passed as argument). The addresses are known.

I've got two problems.

The first one is that the processes that should be waiting are terminating.

The second one, the Starter can't send messages to other processes. I get:

Exception in thread "main" java.lang.NullPointerException: group

What I am doing wrong? Should change the approach to the problem?


Solution

  • I resolved the problem adding ms.start(); in both files. The final result is:

    ManagedMessagingService ms = NettyMessagingService.builder()
                    .withAddress(network[id])
                    .build();
    
    //(...)
    ms.start();
    
    ms.registerHandler("leader", (o,m) -> {
        //...
    });