0

There is a spring-mvc web project. If the user does something important, the application must record log and send a message to the user's email in the service layer (btw, the user will do many important things). The code like below:

private static final Logger LOGGER = LoggerFactory.getLogger(MessageServiceImpl.class);

private static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);

fixedThreadPool.execute(new Runnable() {
    @Override
    public void run() {
        if (emailParams != null && EmailUtil.sendEmail(emailParams)) {
            LOGGER.info("send email succeed");
        } else {
            LOGGER.warn("send email failed");
        }
    }
});

There is two question I have met:

  1. Can I use static LOGGER object in fixedThreadPool?

    If I use static logger object in fixedThreadPool, what will happen? Deadlock? Race condition? or nothing?

  2. Should I define the fixedThreadPool static or not static?

    In my opinion:

    if fixedThreadPool is static and I don't invoke its shutdown(), so it will exist util web project is shutdown.

    if fixedThreadPool is not static and every request may produce one fixedThreadPool. Finally, this web project will have many useless fixedThreadPool, may produce Out-Of-Memery.

Cristian Ramon-Cortes
  • 1,838
  • 1
  • 19
  • 32
shengbang he
  • 128
  • 9

2 Answers2

1

It depends on the logging framework implementation. Most of the implementations are thread-safe however they can also be blocking. Log4j is thread-safe.

See Is SLF4J thread-safe?.

Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
  • my project use slf4j + log4j – shengbang he Mar 06 '18 at 09:49
  • you are right, the first question is reduplicate with https://stackoverflow.com/questions/18543642/is-slf4j-thread-safe . I have marked it. what about the second question ? Can you help me? – shengbang he Mar 06 '18 at 10:07
  • `static` code is generaly harder to test and should be discouraged because of it e.g. how would you write a test for `shutdown()` being called during JVM shutdown. – Karol Dowbecki Mar 06 '18 at 10:26
0

I assume that you use org.slf4j.Logger right? SLF4j provides only an interface for a logger. So like @kdowbecki said it depends on which logger implementation you are using. For example java.util.logging.Logger is thread safe...

From the JavaDocs:

All methods on Logger are multi-thread safe.

Here is a post that lists some examples: Is SLF4J thread-safe?

R. Daumann
  • 86
  • 1
  • 6