Hi everyone, this is my first post to JavaRanch! I have been struggling with threading and concurrency and wondered if I could get some advice from you seasoned Java programmers. I have a SimpleLog class that is used to log information to a Notes document. I want a thread to save the Notes document every 5 seconds or so while other classes write entries to the document. To further complicate things, as the log is likely to be large, every 3000 lines the SimpleLog should create a new Notes document. I thought about what things would need to be synchronised - the changeover from one document to another (as a 2nd thread writing to a null document causes a server PANIC), the write method and the save method. What I am confused about is how to implement this. Should there be a Log class with synchronised methods and a secondary LogWorker class which does the saving? Should I use semaphores? What happens if there is an exception and a semaphore is not reset, would this result in deadlock? I've been working on this for ages now and I feel like I am banging my head against a brick wall! Any advice most gratefully received
Joined: Jan 29, 2003
I might try some kind of FIFO queue where any number of worker threads can put() info to be logged, and the logger thread gets(). You could synchronize the get and put methods on a common object to keep them out of each other's hair. It might be a little tricky to make the logger thread wait when the queue is empty and start back up when something arrives in the queue. Sounds like good fun ... keep us posted on your progress.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Joined: Dec 01, 2003
Should I use semaphores? What happens if there is an exception and a semaphore is not reset, would this result in deadlock?
I don't think you need to worry about semaphores. Java provides all the synchronization you should need. Then you don't have to worry about deadlocks caused by exceptions either. I would say that you have a classic example of the producer-consumer problem. Try googling for that and see if that doesn't help.