Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes Singleton and writing to a common file Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Reply locked New topic

Singleton and writing to a common file

Artemesia Lakener
Ranch Hand

Joined: Jun 21, 2005
Posts: 162
This is a follow-up to my previous post about "thread safe and writing to a common file". I changed the code to include singleton. Here is sample

public class LogWriter {

private static LogWriter lw = new LogWriter();
private LogWriter() {}
public static synchronized LogWriter getLogWriter() {
if(lw == null) lw = new LogWriter();
return lw;

private synchronized writeLog() {
// open file
// write file
// close file

Does this work ? I guess in this case I don't need to put "synchronized" keyword for an "object" inside the "writeLog()" method, right ? This is because I ensure only one static global instance is created. Please help me verify it.

thanks lot.
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Let's not have five different conversations about this, please. I'm closing this thread; follow-ups can go here. Thank you.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: Singleton and writing to a common file
It's not a secret anymore!