I have a multithreaded server project to implement in Java.
How the message is stored:
Every message that is produced by the clients and comes through the sockets to the server is stored in a String variable called "commandString" which is a member variable of class "Command". Every time a message arrives at the server, a new "Command" object is created and the message is stored in "commandString".
How the message is appended to the file:
So, the server is keeping an ArrayList of the Commands which is passed to a thread whose only purpose is to append every new Command object of the ArrayList to a Database.txt file. It is really important that every Command object is written to the txt file one by one as soon as the object is created.
What is happening instead:
When I try to run the project, the file writing feature does not work at all, meaning that nothing is ever written in the file, while the thread is created and being run just fine. But when I launch the debugger with a breakpoint as shown below, every object is being written as soon as the next message arrives. This means I am going to miss the last message which won't be written to the file.
How can I make it write to the file every object as soon as it is created?
public class DataBase implements Runnable {
ArrayList<Command> cmdQueue;
public int lastSize;
@Override
public void run() {
try {
this.setLastSize(this.getCmdQueue().size());
FileWriter fw = new FileWriter(BlackBox.createBlackBox(),true);
BufferedWriter bfw = new BufferedWriter(fw);
this.setLastSize(0);
while(true) {
if(lastSize <this.cmdQueue.size() && this.cmdQueue.size() !=0) {
bfw.write(this.cmdQueue.get(this.cmdQueue.size()-1).getCommandString());
bfw.flush();
this.setLastSize(this.cmdQueue.size());
bfw.close();
}
}
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
ioe.printStackTrace();
}
}//end of run()
In App.java:
//the "server" object receives the messages using threads that are already created
DataBase = new DataBase(server.cmdQueue);
dBase.setCmdQueue(server.cmdQueue);
Thread bBoxThread = new Thread(bBase);
bBoxThread.start();
Feel free to speak you minds.Thank for your time.