Search code examples
javamultithreadingsynchronizedstatic-membersreentrantlock

Is a ReentrantLock safe enough to protect multithreaded access to a static variable


I have a class with static variables, and multiple threads will have instances of this class.

The static variable I'm concerned with is a Thread, that will pop a message from a queue and send it in an email, until the queue is empty. Every time a message is added to the queue, I check to see if the Thread is alive. If not, I restart it.

if (mailThread == null)
{
    mailThread = new Thread(mailSender);
    mailThread.start();
}
else if (!mailThread.isAlive())
{
    mailThread = new Thread(mailSender);
    mailThread.start();
}

In another question, it was said that static variables should be used within a synchronized block.

My question is, would it be safe to just use a ReentrantLock for these if checks? Or do I need to use synchronized? Or both?


Solution

  • You can use either ReentrantLock or a synchronized block. Both are equally safe. Although there is a difference in performance in certain situations. Check out these benchmarks: Benchmark 1 Benchmark 2.