I have a requirement where the same text file is to be used and written by multiple threads. I use BufferedWriter (I use a static variable to know whether the file is open or close, so with this only the first thread has to open and write the file, others have to just write into the file) , so just a synchronization on the BufferedWriter object will suffice ?.
Will this alone make my code safe ?. Thanks in advance.
Regards,
Saravanan.V.
Ulf Dittmer
Marshal
Joined: Mar 22, 2005
Posts: 32767
posted
0
A synchronization on the BufferedWriter object would work, but that's not what the code you posted is doing. Whether it's thread-safe depends on what "this" is - is it guaranteed that only a single instance of the class that contains the code will exist? If not, then it's not thread-safe.
Thanks alot for the reply. Yes, with in the thread there will only one instance of the class where the method resides. I hope this will make the code thread-safe.
The point is your saying your synchronizing on 'out' but your code snipper synchronizes on this so if this == out for instance your ok, or you always synchronize on the same this where ever you use out.
Your post is a bit confusing as to what you intend.
"Eagles may soar but weasels don't get sucked into jet engines" SCJP 1.6, SCWCD 1.4, SCJD 1.5,SCBCD 5
Saravanan Venkat
Greenhorn
Joined: Apr 17, 2010
Posts: 5
posted
0
Thanks for the reply. Yes, I am synchronizing 'this' where ever I use out.
Sandra Wilson
Greenhorn
Joined: Nov 17, 2011
Posts: 1
posted
0
Hi, so what has fixed it finally? Am looking for a solution to the same scenario. Posting the solution here would be of great help.
Jeff Verdegan
Bartender
Joined: Jan 03, 2004
Posts: 3133
posted
0
Sandra Wilson wrote:Hi, so what has fixed it finally? Am looking for a solution to the same scenario. Posting the solution here would be of great help.
The complete answer is already in this thread. And why would you expect the original poster to still be monitoring this thread a year and a half after his problem was solved?
If you're still having problems, please post details about what you tried and where you're stuck. And remember, this site is NotACodeMill.
Nomaan Butt
Ranch Hand
Joined: Oct 19, 2011
Posts: 54
posted
0
Sandra Wilson wrote:Hi, so what has fixed it finally? Am looking for a solution to the same scenario. Posting the solution here would be of great help.
as Jeff has said this site is NotACodeMill so i will not give the complete code, this is just to help you(Sandra)
Below class 'Data' is based on singleton pattern and write to file is synchronised in writeToFile() method on the instance of Data class, here there is no need to synchronize on the PrintWriter Object
Now the runnable code for the multiple threads execution,
Now create multiple threads through Pool or directly and check the execution.