Reputation: 4556
I am writing to a file (Java) while I execute some code. Below you can find the code used, which is executed by the "Thread B", invoked by the JVM.
writer = new PrintWriter(new BufferedWriter(new FileWriter("table.csv")));
(...)
while ( (m_bEnExecution) && (!m_bFinTestRules) ) {
//Calculate new rule
CalculateNewRule(writer);
}
writer.close();
Inside the CalculateNewRule method, a new instantiation of an AssociationRule is created, which will receive the writer as an instance variable. One of the functions inside AssociationRule does the printing.
writer.println(outputRule);
writer.flush();
The problem seems to be that this function is invoked by an AWT thread, and the last line to be written to the file, inside the CalculateNewRule(writer) method will never be written, unless I explicitly force the execution of the thread to stop, after the while cycle. Any idea on what the problem might be? Is there any elegant way to deal with this problem?
In one answer I was suggested to set the printing thread as a daemon thread, but I don't know how to do that on that specific thread.
Upvotes: 0
Views: 95
Reputation: 11
Is that "(m_bEnExecution) && (!m_bFinTestRules)" always equals true??
I suggest that as below:
try {
while ( (m_bEnExecution) && (!m_bFinTestRules) ) {
//Calculate new rule
CalculateNewRule(writer);
writer.flush();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
writer.close();
}
But you still need to make sure that you will not make the infinite loop.
Upvotes: 1
Reputation: 647
It may be the calling thread is getting over before this thread finishes. Use a daemon thread if this is the case. Provide more details maybe we can help.
Upvotes: 1
Reputation: 5723
You are not providing much code but anyway.
What do you mean:
force the execution of the thread to stop
You are using a BufferedWriter
so unless you flush
, close
etc the writer you are not sure it has written everything in the buffer.
If you want to be sure just choose one of these methods.
Upvotes: 0