user373201
user373201

Reputation: 11455

java multithreading and static methods

I have a java application. I am using a log formater object. All log messages should have this object. for example

log.debug(new LogFormatter(x,y,z))

But I have to create new LogFormatter object each and everything i want to log. If I use static method for example

log.debug(LogFormatter.format(x,y,z))

Than I don't have to create new objects. But in a multithreaded application would it work right.

if two threads call with diff values, woud the logging get messed up.

Or is thread local the best way to go

Upvotes: 1

Views: 441

Answers (4)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85789

This would depend on the logger implementation. If you will use native Java classes, then you should handle the locks by using the synchronize keyword for the method or the code section that handles the log insertion.

IMO I would recommend to use a logging library like Log4J that is thread safe:

Note that some Java Application Servers like JBoss and GlassFish use Log4j to handle the logging work.

Upvotes: 1

Aubin
Aubin

Reputation: 14873

To avoid synchronization between thread only when logging is on, I'm used to associate one log chain per thread. The difficulty is to join several files to - off line - understand what's happening. Each line of log has a date, and a thread id.

Upvotes: 0

Isaac
Isaac

Reputation: 16736

That depends on two things:

  1. Whether the LogFormatter.format(x,y,z) method is thread safe.
  2. Whether your logger implementation is thread safe.

If these two conditions are true, then you can use your scheme in a multithreaded environment and expect no errors.

Specifically, your logger implementation should be thread-safe in the sense that it synchronizes access to the underlying output mechanism: for example, by ensuring that only one log record is printed at a time.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533870

I would use

private final LogFormatter logFormatter; // immutable object.

log.debug(logFormatter.format(x,y,z))

as the formatter is immutable it can be shared.

Upvotes: 1

Related Questions