This week's book giveaway is in the Agile and Other Processes forum. We're giving away four copies of Real-World Software Development: A Project-Driven Guide to Fundamentals in Java and have Dr. Raoul-Gabriel Urma & Richard Warburton on-line! See this thread for details.
The code listed below uses Java's (jdk 1.4) logging utility. A new log file is created for each day and messages are appended to the file. In a single thread the code works as per the above defined requirement. However in a multithreaded test case, the program does not create a single file. Messages from mutiple threads are written to multiple files. The behaviour is as listed. Say there are 5 messages from five threads. The logger creates five log files and five lock files. All five messages are posted to the first log. Four messages are posted to the second file. Three to the next and so on. The last file contains one message. Any help in resolving the issue is appreciated.
Ugh. I added [code] tags above to imporve readability, but the indentation is rather strange. It would really help if you made the indentation more consistent. Don't use tabs - they look different in various formats. Use spaces. It's hard to tell for sure right now, but it seems the problem most likely is the first part of logProcessMessage(). Since there's no synchronization here, one thread may still be executing checkFileName(), createFileName(), or initialize(), when another thread comes along and tries checkFileName(). The second thread may find that checkFileName() returns false, because the first thread's initialize() has not completed. This will lead to the second thread running initialize() as well, and creating a new logger in response. This is probably how you're getting so many extra log files. To fix it, the simplest response is to put a synchronized (this) block around the first part of logProcessMessage(), to ensure that no other threads can start checkFileName() until the first thread has completed initialize(). You may also be able to redesign your code a bit. The checkFileName() method looks farily slow, for somethign that's going to be called each time you log something. Perhaps when you first create a logger you could also calculate the time (in milliseconds since 1/1/70) at which it will be necessary to change to another logger, and save that. Then when logProcessMessage() is called, just compare System.currentTimeMillis() to the saved time, and if the current time is less, that means your existing log file is still good. Otherwise, create close the old log file and start a new one. I expect the whole process can be much faster than it is now.
"I'm not back." - Bill Harding, Twister
Thank you my well lotioned goddess! Here, have my favorite tiny ad!