3

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?

Community
  • 1
  • 1
dluga
  • 67
  • 1
  • 8
  • _...I check to see if the Thread is alive. If not, I restart it._ +1 for thinking about availability, but if you want a thread to always be available, a better strategy is to write a thread that never dies. (I'm assuming that this `mailThread` does not execute any foreign code. If you _do_ need to execute foreign code, you're probably better off sandboxing it in its own, separate process.) – Solomon Slow Feb 22 '16 at 14:48

2 Answers2

1

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.

Cyril
  • 2,376
  • 16
  • 21
0

According to the docs:

A reentrant mutual exclusion Lock with the same basic behavior and semantics as the implicit monitor lock accessed using synchronized methods and statements, but with extended capabilities. A ReentrantLock is owned by the thread last successfully locking, but not yet unlocking it. A thread invoking lock will return, successfully acquiring the lock, when the lock is not owned by another thread. The method will return immediately if the current thread already owns the lock. This can be checked using methods isHeldByCurrentThread(), and getHoldCount().

So a ReentrantLock must be safe enough.