user710818
user710818

Reputation: 24248

Should be logger always final and static?

Class can be accessed from many threads. Must be logger in this case also be final and static? Thanks.

Upvotes: 19

Views: 12600

Answers (3)

ataylor
ataylor

Reputation: 66059

All major java logging packages (java.util.logging, log4j, etc.) are synchronized and thread safe. The standard pattern of a private final static logger per class is fine even if the class is called from multiple threads.

Upvotes: 30

John B
John B

Reputation: 32949

Making the logger final and or static will not in any way affect the thread-safety of the use of the logger. If the logger instance is being used from multiple threads than ensure you are using a thread-safe logger.

In general the logger should be private static final but do not assume that this makes it thread-safe. Most common logging frameworks are thread-safe so if you are using one of these you should be good.

Upvotes: 2

billygoat
billygoat

Reputation: 21984

Yes the logger should be static and final. Also preferably private. There needs be only one logger instance per class and also unless you are going to change the log preference dynamically, it is better to make it final.

Logger are thread safe and you do not have to worry about threading.

Upvotes: 5

Related Questions