ReentrantLock 是否足够安全以保护对静态变量的多线程访问

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

我有一个带有静态变量的 class,多个线程将有这个 class 的实例。

我关心的静态变量是 Thread,它将从队列中弹出一条消息并通过电子邮件发送,直到队列为空。每次将消息添加到队列时,我都会检查线程是否还活着。如果不行,我重启一下。

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

another question中,据说静态变量应该在同步块中使用。

我的问题是,仅对这些 if 检查使用 ReentrantLock 是否安全?或者我需要使用 synchronized 吗?或者两者兼而有之?

根据 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().

所以ReentrantLock一定足够安全了。

您可以使用 ReentrantLock 或同步块。两者同样安全。虽然在某些情况下性能会有所不同。查看这些基准:Benchmark 1 Benchmark 2.