Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static vs. instance method for shared use

Here's what I am trying to determine...

I have a utility class to append lines to a text file. This must be used by a number of other classes, like a common logging file.

In my first implementation, I had all the classes that wanted to use it make a reference-less instance, e.g.

new Logger(logline,logname);

The constructor creates a PrintWriter, appends the line and closes the file.

This seemed wasteful, since a new instance gets made for every line appended.

The alternative was to use a static method, called "writeln" in this common class, since I had understood that static methods and data re-use the same memory over & over...but

this static method creates an instance of PrintWriter to do its job, so doesn't that mean that a new instance of PrintWriter is created for every line, like #1?

Anyway, (I am relatively new to Java ) is there a well-known, approved way of doing this, or do we just create away, and let the garbage-collector clean up after us?

Thanks

like image 593
javaphild Avatar asked Dec 28 '25 11:12

javaphild


1 Answers

The sensible answer is that you should use a "serious" logging package, such as Commons Logging.

However, to answer your question, in this case you should use a static method (unless you're wanting to maintain logging class instances in your code, in which case you should follow the other answers in this thread). Additionally, you should have a static field that's initialised to, say, a Map<String, PrintWriter>. (You don't have to use String as the key: if you want a finite number of logging target types, use an enum.)

Then, when your method sees a key that's not existent in the map yet, it'd create the PrintWriter on the spot, and sticks it in the map. You probably want to use a ConcurrentHashMap as the backing map type, so it's thread-safe.

You also need to provide a way to close a logging target (which will also clear the associated entry from the map).

Good luck!

like image 113
Chris Jester-Young Avatar answered Dec 31 '25 03:12

Chris Jester-Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!