Reputation: 469
I am creating a multhreaded Client -Server chat application in Java. I want to store all the messages into a data structure and write it to a file (means I want to create logs of messages). Will StringBuffer be a good option? Or there are any other better alternatives ?
Upvotes: 0
Views: 124
Reputation: 1953
Depends on your further plans for those messages. Are they just logs? You can simply use some logging framework then. However, if you later plain to read them back into memory, you could consider a serialization library with plain text, json or xml format (or even binary if performace is important).
Upvotes: 0
Reputation: 46841
You don't want to option a lock on a log file till application is running.
The good option is use some In-Memory object It can be any thing but needs to enclosed in synchronized
block before doing any operation on it for thread safety.
After some time when its reached at its max memory then flush all the data in the log file mean while you have to maintain other messages in the background in a separate In-Memory object.
Finally swap the object and make it empty.
One more thing you can create a separate thread to write into log file for good performance.
Make synchronized
block as short as possible because it stops others thread to enter until and unless it is released.
Hope you understand.
Upvotes: 1