Search code examples
javaprocess

Error when reading a file used by two separate Java processes


I have to implement two player objects on separate JAVA processes. The player objects have to send each other messages back and forth and there has to be a common counter variable between them that should be appended with the message that is transmitted between these objects.

With each message, the counter variable should be incremented.

What have I implemented so far

I have 2 classes. ProcessPlayer class and a Main class.

Main class will create two processes. Each player belonging to one process.

In order to have a shared counter variable, I choose to use a simple text file which will have a counter variable and both processes will read the value, append to the message, update the value in the file for the next process. Below is the code for the Main.java class.

public class Main {
public static void main(String[] args) throws FileNotFoundException {
    System.out.println("Implementing players on different processes.\n");

    Utils.createFile();     // both players on different processes will use this common file.

    String classpath = Paths.get(".").toAbsolutePath().normalize().toString();
    classpath = classpath + "\\src";

    ProcessBuilder secondPlayerProcessBuilder = new ProcessBuilder(
            "java", "-cp", classpath, "ProcessPlayer", "Player2", "5003", "5002", "false"
    ).inheritIO();

    ProcessBuilder firstPlayerProcessBuilder = new ProcessBuilder(
            "java", "-cp", classpath, "ProcessPlayer", "Player1","5002", "5003", "true"
    ).inheritIO();

    try {
        Process secondPlayerProcess = secondPlayerProcessBuilder.start();
        Process firstPlayerProcess = firstPlayerProcessBuilder.start();

        secondPlayerProcess.waitFor();
        firstPlayerProcess.waitFor();

        secondPlayerProcess.destroy();
        firstPlayerProcess.destroy();

        System.out.println("First player process exited with code: " + firstPlayerProcess.exitValue());
        System.out.println("Second player process exited with code: " + secondPlayerProcess.exitValue());

        Utils.deleteFile();
    } catch (IOException | InterruptedException exception) {
        exception.printStackTrace();
    }
}

The above class;

  1. Creates a file with counter value as 0 initially
  2. Creates two processes where Objects of ´´ProcessPlayer´´ are running.

Below I am attaching the utility methods I am using in order to interact with the file.

public class Utils {
public static void createFile() {
    try {
        if (new File("messageCounter.txt").createNewFile()) {
            System.out.println("File Created");
            PrintWriter writer = new PrintWriter(new FileWriter("messageCounter.txt"));
            writer.print(0);
            writer.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void deleteFile() {
    boolean isDeleted = new File("messageCounter.txt").delete();
    if (isDeleted) {
        System.out.println("File removed!");
    }
}

public static void updateCounter(int newCounter) throws IOException {
    PrintWriter printWriter = new PrintWriter(new FileWriter("messageCounter.txt"));
    printWriter.print(newCounter);
    printWriter.close();
}

}

To be specific, ´´updateCounter´´ is the method that will be used by both processes during back and forth communication.

And finally bellow I am attaching the ´´ProcessPlayer.java´´ class.

public class ProcessPlayer {
int numberOfMessagesSent;
int maxMessages;
static int messageCounter = 0;

boolean isInitiator;
private String playerName;
int port;
int partnerPort;

private ProcessPlayer(ProcessPlayer.PlayerBuilder builder) {
    this.numberOfMessagesSent = builder.numberOfMessagesSent;
    this.maxMessages = builder.maxMessages;
    this.isInitiator = builder.isInitiator;
    this.playerName = builder.playerName;
    this.port = builder.port;
    this.partnerPort = builder.partnerPort;
}

public void start() {
    new Thread(this::receiveMessage).start();
    if (this.isInitiator) {
        sendMessage("HelloWorld!!", true);
    }
}

// read counter from file, append it to message and increment it. Update the file with incremented counter.
public void sendMessage(String message, boolean initialMessage) {
    try {
        Socket socket = new Socket("localhost", this.partnerPort);
        PrintWriter stream = new PrintWriter(socket.getOutputStream(), true);
        String senderInfo = "This message was sent from " + this.getPlayerName() + ":";

        FileReader fileReader = new FileReader("messageCounter.txt");
        int character;
        StringBuilder counterFromFile = new StringBuilder();

        while (counterFromFile.toString().isEmpty()) {
            while ((character = fileReader.read()) != -1) {
                counterFromFile.append((char) character);
            }
        }

        fileReader.close();

        if (numberOfMessagesSent < maxMessages) {
            numberOfMessagesSent++;
            if (initialMessage) {
                stream.println(senderInfo + message);
            }
            else if (Integer.parseInt(String.valueOf(counterFromFile)) == 0) {
                stream.println(senderInfo + message + counterFromFile);
                Utils.updateCounter(Integer.parseInt(counterFromFile.toString()) + 1);
            }
            else {
                stream.println(senderInfo + message + counterFromFile);
                Utils.updateCounter(Integer.parseInt(counterFromFile.toString()) + 1);
            }
        }
    } catch(Exception e) {
        e.printStackTrace();
    }
}

public void receiveMessage() {
    try {
        ServerSocket serverSocket = new ServerSocket(this.port);
        while(numberOfMessagesSent < maxMessages) {
            Socket s = serverSocket.accept();
            BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));
            String message = reader.readLine();
            System.out.println(message);
            message = message.substring(message.lastIndexOf(":") + 1);
            if (messageCounter < maxMessages) {
                sendMessage(message, false);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public String getPlayerName() {
    return playerName;
}

public static class PlayerBuilder {
    int numberOfMessagesSent;
    int maxMessages;
    boolean isInitiator;
    String playerName;
    int port;
    int partnerPort;

    public PlayerBuilder(int port, int partnerPort) {
        this.numberOfMessagesSent = 0;
        this.maxMessages = 10;
        this.port = port;
        this.partnerPort = partnerPort;
    }

    public ProcessPlayer.PlayerBuilder setInitiator(boolean isInitiator) {
        this.isInitiator = isInitiator;
        return this;
    }

    public ProcessPlayer.PlayerBuilder setName(String name) {
        this.playerName = name;
        return this;
    }

    public ProcessPlayer build() {
        return new ProcessPlayer(this);
    }
}

/**
 * This method initializes a player instance with the required parameters
 * (name, port, and partner's port) and starts the communication process.
 * This will be one of the two processes.
 * @param args - The value in args array will be passed from Main.java via ProcessBuilderObject
 */
public static void main(String[] args) {
    if (args.length != 4) {
        System.out.println("Usage: java Player <name> <port> <partnerPort> <isInitiator>");
        return;
    }
    String name = args[0];
    int port = Integer.parseInt(args[1]);
    int partnerPort = Integer.parseInt(args[2]);
    boolean isInitiator = Boolean.parseBoolean(args[3]);

    try {
        ProcessPlayer player = new ProcessPlayer.PlayerBuilder(port, partnerPort)
                .setInitiator(isInitiator)
                .setName(name).build();
        player.start();
    } catch (Exception e) {
        System.out.println("Exception caught");
        throw e;
    }
}

}

Problem

I get inconsistent behavior. If I completely re-compile both ´´Main.java´´ and ´´ProcessPlayer.java´´ class and run the application, I get the following output.

This message was sent from Player1:HelloWorld!!
This message was sent from Player2:HelloWorld!!0
This message was sent from Player1:HelloWorld!!01
This message was sent from Player2:HelloWorld!!011
This message was sent from Player1:HelloWorld!!0112
This message was sent from Player2:HelloWorld!!01123
This message was sent from Player1:HelloWorld!!011234
This message was sent from Player2:HelloWorld!!0112345
This message was sent from Player1:HelloWorld!!01123456
This message was sent from Player2:HelloWorld!!011234567

and so on. As you can see in the above output, 1 is being appended twice, that should also not happen. However, the second time when I run the program, I get the following error.

This message was sent from Player1:HelloWorld!!
This message was sent from Player2:HelloWorld!!0
java.lang.NumberFormatException: For input string: ""
    at 
    java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
    at java.base/java.lang.Integer.parseInt(Integer.java:565)
    at java.base/java.lang.Integer.parseInt(Integer.java:685)
    at ProcessPlayer.sendMessage(ProcessPlayer.java:61)
    at ProcessPlayer.receiveMessage(ProcessPlayer.java:85)
    at java.base/java.lang.Thread.run(Thread.java:1570)

And then I have to manually kill the child processes from CMD. If you see on method sendMessage of ProcessBuilder.java class, I am reading the file character by character and creating string from asciis, that is where this error originates from. If I use an object of Scanner class, it throws and Execption of java.util.NoSuchElementException when attempting to read the file indicating that the file is empty, when it is NOT. Thank you for your time and any help is much appreciated.


Solution

  • You have set up sendMessage incorrectly in these lines:

    stream.println(senderInfo + message + counterFromFile);
    Utils.updateCounter(Integer.parseInt(counterFromFile.toString()) + 1);
    

    This means you send a message to the other process before updating the file counter. However, the other process handler receiveMessage may receive the message and open the file before or during the updateCounter call of the sender - hence your observation of wrong count value or truncated value.

    The fix should be simple, swap the lines over so that you update the counters before sending the message to the pair process:

    Utils.updateCounter(Integer.parseInt(counterFromFile.toString()) + 1);
    stream.println(senderInfo + message + counterFromFile);
    

    Also, you should tidy up the code as it duplicates the above calls, you don't need the branch to check counter == 0:

    else if (Integer.parseInt(String.valueOf(counterFromFile)) == 0) {