Терминал Intellij не запрашивает следующую команду после завершения основного метода в Java - PullRequest
0 голосов
/ 21 марта 2020

Здравствуйте, у меня есть следующий код, который содержит метод main. Код запускает некоторые процессы и потоки и в конце завершает каждый процесс (потоки также завершаются, как показано в выходных данных). Программа завершается, и обычный терминал работает нормально и запрашивает следующую команду, но терминал intellij застрял и не запрашивает следующую команду. Что может быть причиной этого? Спасибо!

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
//hashing imports
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class RunBrokers {
    /**
     * Starts brokers locally with different ports
     *              Usage RunBrokers <nBrokers>
     */
    public static void main(String[] args) throws IOException {
        //Usage RunBrokers <nBrokers>
        int nBrokers = Integer.parseInt(args[0]);
        String ip = "127.0.0.1";
        int port = 5000;
        String fileName = "brokers.txt";


        File brokersFile =  new File(fileName);
        PrintWriter pw = new PrintWriter(brokersFile);

        //Array list containing the processes created
        ArrayList<Process> brokers = new ArrayList<>();
        ArrayList<Component> brokerAddr = new ArrayList<> ();

        ArrayList<Process> publishers = new ArrayList<>();


        ArrayList<Process> consumers = new ArrayList<>();


        for (int i = 0 ; i < nBrokers ; i++){
            //Calculating hash of the broker
            int brokerHash = Utilities.getMd5(ip + port).hashCode();
            //Writing to brokers.txt
            pw.printf("%s %d %d%n" , ip , port , brokerHash);
            //Starting the brokers
            String command = String.format("java Broker %s %d %d %s" , ip , port , brokerHash , brokersFile);
            Process p = Runtime.getRuntime().exec(command);
            //Keeping information about the current broker
            brokers.add(p);
            brokerAddr.add(new Component(ip,port));
            System.out.println("[RUNBROKERS] EXEC : " + command);
            //Next node must be started on a new port
            //Running gobblers for the created process' stderr , stdout
            StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream());
            StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream());
            errorGobbler.start();
            outputGobbler.start();
            port++;
        }
        pw.close();

        Scanner sc = new Scanner(System.in);
        //Program loop watining for commands
        while(true) {
            String line = sc.nextLine();
            //If user typed exit break the loop and terminate created proesses
            if(line.trim().toLowerCase().equals("exit")){
                System.out.println("Bye");
                break;
            }
            else if(line.trim().toLowerCase().equals("start_publisher")) {
                //Starting a publisher
                String command = String.format("java Publisher %s %d %s" , ip , port , fileName);
                //Adding artists for whom the publisher is responsible to the command
                String[] artists = {"Bob" , "John" , "mpla"};
                for (String artist : artists ){
                    command += " " + artist;
                }
                //Starting the process
                Process p = Runtime.getRuntime().exec(command);
                System.out.println("[RUNBROKERS] EXEC : " + command);
                //Running gobblers for the created process' stderr , stdout
                StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream());
                StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream());
                errorGobbler.start();
                outputGobbler.start();
                port++;
                //System.out.println("[RUNBROKERS] EXEC : " + command);
            }
            //Display status of brokers
            else if(line.trim().toLowerCase().equals("broker_status")){
                for(Component c : brokerAddr){
                    System.out.printf("Broker %s %d status : %s%n" , c.getIp() , c.getPort() , brokerStatus(c));
                }
            }
            else{
                System.out.print("exit : exit the program\n" +
                        "start_publisher : start a publisher\n" +
                        "status : show brokers and the artists they are responsible for\n"
                );
            }
        }

        //Destroying the created processes and exiting after user input
        for(Process p : brokers){
            System.out.println("[RUNBROKERS] terminating a broker");
            p.destroy();
        }
        for(Process p : consumers){
            p.destroy();
        }
        for(Process p : publishers){
            p.destroy();
        }
        System.out.println("[RUNBROKERS] finished stuff");
        //Exiting
        Runtime.getRuntime().exit(0);


    }
    public static String brokerStatus(Component broker){
        String result = "";
        Socket s = null;
        ObjectOutputStream out = null;
        ObjectInputStream in = null;
        try {
            s = new Socket(broker.getIp() , broker.getPort());
            System.out.printf("[RUNBROKERS] Broker(%s,%d) connectionAvailable: %b %n" ,
                    broker.getIp() , broker.getPort() , s.isConnected());
            out =  new ObjectOutputStream(s.getOutputStream());
            String query = "status";
            out.writeObject(query);
            in = new ObjectInputStream(s.getInputStream());
            result = (String) in.readObject();
            result = "NumArtists: " + result.split(" ").length + " " + result;

        }
        catch(Exception e){
            result = "Unreachable exception : " + e.getMessage();
            e.printStackTrace();
        }
        finally{
            System.out.printf("[RUNBROKERS] closing connection with Broker(%s,%d)%n" ,
                    broker.getIp() , broker.getPort());
            try {
                if(in != null) in.close();
                if(out != null) out.close();
                if(s != null)  s.close();
            }
            catch(Exception e){
                throw new Error();
            }
        }
        return result;
    }

    static class StreamGobbler extends Thread {
        InputStream is;

        // reads everything from is until empty.
        StreamGobbler(InputStream is) {
            this.is = is;
        }

        public void run() {
            Scanner sc = new Scanner(is);
            String line = null;
            try {
                while ((line = sc.nextLine()) != null) {
                    System.out.println(line);
                }
            }
            //Sometimes no such element exception occurs when a process is destroyed
            catch(Exception e){
                System.out.println("Stream gobbler " + this + " terminating");
            }
        }
    }
}

Это вывод:

sm@Sm-Laptop:~/DistributedSystemsAssignment$ java RunBrokers 5
[RUNBROKERS] EXEC : java Broker 127.0.0.1 5000 701718257 brokers.txt
[RUNBROKERS] EXEC : java Broker 127.0.0.1 5001 -1309240166 brokers.txt
[RUNBROKERS] EXEC : java Broker 127.0.0.1 5002 2111031781 brokers.txt
[RUNBROKERS] EXEC : java Broker 127.0.0.1 5003 -1088753282 brokers.txt
[RUNBROKERS] EXEC : java Broker 127.0.0.1 5004 1958473143 brokers.txt
Broker listening on port 5000
Broker listening on port 5001
Broker listening on port 5002
Broker listening on port 5004
Broker listening on port 5003
start_publisher
[RUNBROKERS] EXEC : java Publisher 127.0.0.1 5005 brokers.txt Bob John mpla
Publisher(127.0.0.1,5005) notifying Broker(127.0.0.1,5000)
[PUBLISHER 5005] Connecting to broker on port 5000 , ip 127.0.0.1
[PUBLISHER 5005] Connected to broker on port 5000 , ip 127.0.0.1
[PUBLISHER 5005] Sending message "notify 127.0.0.1 5005 Bob mpla John" to broker on port 5000 , ip 127.0.0.1
Publisher(127.0.0.1,5005) notifying Broker(127.0.0.1,5001)
[Broker (127.0.0.1,5000)] GOT A MESSSAGE <notify 127.0.0.1 5005 Bob mpla John> 
[PUBLISHER 5005] Connecting to broker on port 5001 , ip 127.0.0.1
[PUBLISHER 5005] Connected to broker on port 5001 , ip 127.0.0.1
[PUBLISHER 5005] Sending message "notify 127.0.0.1 5005 Bob mpla John" to broker on port 5001 , ip 127.0.0.1
Publisher(127.0.0.1,5005) notifying Broker(127.0.0.1,5002)
[PUBLISHER 5005] Connecting to broker on port 5002 , ip 127.0.0.1
[PUBLISHER 5005] Connected to broker on port 5002 , ip 127.0.0.1
[PUBLISHER 5005] Sending message "notify 127.0.0.1 5005 Bob mpla John" to broker on port 5002 , ip 127.0.0.1
Publisher(127.0.0.1,5005) notifying Broker(127.0.0.1,5003)
[PUBLISHER 5005] Connecting to broker on port 5003 , ip 127.0.0.1
[PUBLISHER 5005] Connected to broker on port 5003 , ip 127.0.0.1
[PUBLISHER 5005] Sending message "notify 127.0.0.1 5005 Bob mpla John" to broker on port 5003 , ip 127.0.0.1
Publisher(127.0.0.1,5005) notifying Broker(127.0.0.1,5004)
[Broker (127.0.0.1,5001)] GOT A MESSSAGE <notify 127.0.0.1 5005 Bob mpla John> 
[PUBLISHER 5005] Connecting to broker on port 5004 , ip 127.0.0.1
[PUBLISHER 5005] Connected to broker on port 5004 , ip 127.0.0.1
Index = -5
Index = -3
[PUBLISHER 5005] Sending message "notify 127.0.0.1 5005 Bob mpla John" to broker on port 5004 , ip 127.0.0.1
Index = -4
Publisher listening on port 5005
[Broker (127.0.0.1,5004)] GOT A MESSSAGE <notify 127.0.0.1 5005 Bob mpla John> 
Index = -5
Index = -3
[Broker (127.0.0.1,5002)] GOT A MESSSAGE <notify 127.0.0.1 5005 Bob mpla John> 
Index = -4
[Broker (127.0.0.1,5003)] GOT A MESSSAGE <notify 127.0.0.1 5005 Bob mpla John> 
Index = -5
Index = -3
Index = -4
Index = -5
Index = -3
Index = -4
Index = -5
Index = -3
Index = -4
broker_status
[RUNBROKERS] Broker(127.0.0.1,5000) connectionAvailable: true 
[Broker (127.0.0.1,5000)] GOT A MESSSAGE <status> 
[RUNBROKERS] closing connection with Broker(127.0.0.1,5000)
Broker 127.0.0.1 5000 status : NumArtists: 1 mpla
[RUNBROKERS] Broker(127.0.0.1,5001) connectionAvailable: true 
[Broker (127.0.0.1,5001)] GOT A MESSSAGE <status> 
[RUNBROKERS] closing connection with Broker(127.0.0.1,5001)
Broker 127.0.0.1 5001 status : NumArtists: 1 
[RUNBROKERS] Broker(127.0.0.1,5002) connectionAvailable: true 
[Broker (127.0.0.1,5002)] GOT A MESSSAGE <status> 
[RUNBROKERS] closing connection with Broker(127.0.0.1,5002)
Broker 127.0.0.1 5002 status : NumArtists: 1 Bob
[RUNBROKERS] Broker(127.0.0.1,5003) connectionAvailable: true 
[Broker (127.0.0.1,5003)] GOT A MESSSAGE <status> 
[RUNBROKERS] closing connection with Broker(127.0.0.1,5003)
Broker 127.0.0.1 5003 status : NumArtists: 1 
[RUNBROKERS] Broker(127.0.0.1,5004) connectionAvailable: true 
[Broker (127.0.0.1,5004)] GOT A MESSSAGE <status> 
[RUNBROKERS] closing connection with Broker(127.0.0.1,5004)
Broker 127.0.0.1 5004 status : NumArtists: 1 John
exit
Bye
[RUNBROKERS] terminating a broker
[RUNBROKERS] terminating a broker
[RUNBROKERS] terminating a broker
[RUNBROKERS] terminating a broker
[RUNBROKERS] terminating a broker
[RUNBROKERS] finished stuff
Stream gobbler Thread[Thread-5,5,main] terminating
Stream gobbler Thread[Thread-1,5,main] terminating
Stream gobbler Thread[Thread-0,5,main] terminating
Stream gobbler Thread[Thread-8,5,main] terminating
Stream gobbler Thread[Thread-4,5,main] terminating
Stream gobbler Thread[Thread-9,5,main] terminating
Stream gobbler Thread[Thread-3,5,main] terminating
Stream gobbler Thread[Thread-2,5,main] terminating
Stream gobbler Thread[Thread-6,5,main] terminating
Stream gobbler Thread[Thread-7,5,main] terminating
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...