So I have this assignment for my Java class, which is to write to a (single) file from multiple threads: the main thread and then multiple copies of a MyThread class. I spent an hour last night apparently way overcomplicating things, thinking that I would have to marshal the output somehow to prevent contention issues, but then a classmate comes along on Instant Messenger saying that he'd gotten it to work by just appending to the file. It was his initial IM that signalled to me I might need to work on this before too long, as it might be harder than the last few. Then again, he has said things "work" in the past without them actually working right, so I remain suspicious that this is correct. However, I cannot see how it is not behaving as specified.
The assignment specification is located
here. Basically, what I'm doing right now, because it seems to work, not because it makes perfect sense that this is what I should be doing, is not particularly taking any care about the multithreaded aspect of the assignment and just writing to the file as we were taught in class. That is:
BufferedWriter bw = new BufferedWriter(new FileWriter("file.log",true));
bw.write("This is a line.");
bw.newLine();
bw.flush();
bw.close();
etc. and so forth, both from the main thread and the secondary threads. The reason my initial attempt wasn't working, apparently, is because
FileWriter needs that
true flag at the end, for append. But given that, it seems to not care that the file is being touched from multiple threads, and it behaves correctly and consistently.
Am I thinking too much about this?