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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật