有关JAVA的同步
使用synchronized
在编写一个类时,如果该类中的代码可能运行于多线程环境下,那么就要考虑同步的问题。在Java中内置了语言级的同步原语--synchronized,这也大大简化了Java中多线程同步的使用。我们首先编写一个非常简单的多线程的程序,是模拟银行中的多个线程同时对同一个储蓄账户进行存款、取款操作的。
在程序中我们使用了一个简化版本的Account类,代表了一个银行账户的信息。在主程序中我们首先生成了1000个线程,然后启动它们,每一个线程都对John的账户进行存100元,然后马上又取出100元。这样,对于John的账户来说,最终账户的余额应该是还是1000元才对。然而运行的结果却超出我们的想像,首先来看看我们的演示代码:







































































注意,上面在Account的deposit和withdraw方法中之所以要把对amount的运算使用一个临时变量首先存储,sleep一段时间,然后,再赋值给amount,是为了模拟真实运行时的情况。因为在真实系统中,账户信息肯定是存储在持久媒介中,比如RDBMS中,此处的睡眠的时间相当于比较耗时的数据库操作,最后把临时变量tmp的值赋值给amount相当于把amount的改动写入数据库中。运行AccountTest,结果如下(每一次结果都会不同):
E:\java\exer\bin>java AccountTest
Finally, John's balance is:3900.0
E:\java\exer\bin>java AccountTest
Finally, John's balance is:4900.0
E:\java\exer\bin>java AccountTest
Finally, John's balance is:4700.0
E:\java\exer\bin>java AccountTest
Finally, John's balance is:3900.0
E:\java\exer\bin>java AccountTest
Finally, John's balance is:3900.0
E:\java\exer\bin>java AccountTest
Finally, John's balance is:5200.0
为什么会出现这样的问题?这就是多线程中的同步的问题。在我们的程序中,Account中的amount会同时被多个线程所访问,这就是一个竞争资源,通常称作竞态条件。对于这样的多个线程共享的资源我们必须进行同步,以避免一个线程的改动被另一个线程所覆盖。在我们这个程序中,Account中的amount是一个竞态条件,所以所有对amount的修改访问都要进行同步,我们将deposit()和withdraw()方法进行同步,修改为:


























此时,再运行,我们就能够得到正确的结果了。Account中的getBalance()也访问了amount,为什么不对getBalance()同步呢?因为getBalance()并不会修改amount的值,所以,同时多个线程对它访问不会造成数据的混乱。
Metux的设计及使用
Mutex是互斥体,广泛地应用在多线程编程中。本文以广为流程的Doug Lea的concurrent工具包的Mutex实现为例,进行一点探讨。在Doug Lea的concurrent工具包中,Mutex实现了Sync接口,该接口是concurrent工具包中所有锁(lock)、门(gate)和条件变量(condition)的公共接口,Sync的实现类主要有:Mutex、Semaphore及其子类、Latch、CountDown、ReentrantLock等。这也体现了面向抽象编程的思想,使我们可以在不改变代码或者改变少量代码的情况下,选择使用Sync的不同实现。下面是Sync接口的定义:





通过使用Sync可以替代Java synchronized关键字,并提供更加灵活的同步控制。当然,并不是说concurrent工具包是和Java synchronized独立的技术,其实concurrent工具包也是在synchronized的基础上搭建的,从下面对Mutex源码的解析即可以看到这一点。synchronized关键字仅在方法内或者代码块内有效,而使用Sync却可以跨越方法甚至通过在对象之间传递,跨越对象进行同步。这是Sync及concurrent工具包比直接使用synchronized更加强大的地方。
注意Sync中的acquire()和attempt()都会抛出InterruptedException,所以使用Sync及其子类时,调用这些方法一定要捕获InterruptedException。而release()方法并不会抛出InterruptedException,这是因为在acquire()和attempt()方法中可能会调用wait()等待其它线程释放锁。而release()在实现上进行了简化,直接释放锁,不管是否真的持有。所以,你可以对一个并没有acquire()的线程调用release()这也不会有什么问题。而由于release()不会抛出InterruptedException,所以我们可以在catch或finally子句中调用release()以保证获得的锁能够被正确释放。比如:
























Mutex是一个非重入的互斥锁。Mutex广泛地用在需要跨越方法的before/after类型的同步环境中。下面是Doug Lea的concurrent工具包中的Mutex的实现。





























































为什么要在acquire()和attempt(0方法的开始都要检查当前线程的中断标志呢?这是为了在当前线程已经被打断时,可以立即返回,而不会仍然在锁标志上等待。调用一个线程的interrupt()方法根据当前线程所处的状态,可能产生两种不同的结果:当线程在运行过程中被打断,则设置当前线程的中断标志为true;如果当前线程阻塞于wait()、sleep()、join(),则当前线程的中断标志被清空,同时抛出InterruptedException。所以在上面代码的位置(2)也捕获了InterruptedException,然后再次抛出InterruptedException。
release()方法简单地重置inuse_标志,并通知其它线程。
attempt()方法是利用Java的Object.wait(long)进行计时的,由于Object.wait(long)不是一个精确的时钟,所以attempt(long)方法也是一个粗略的计时。注意代码中位置(3),在超时时返回。
Mutex是Sync的一个基本实现,除了实现了Sync接口中的方法外,并没有添加新的方法。所以,Mutex的使用和Sync的完全一样。在concurrent包的API中Doug给出了一个精细锁定的List的实现示例,我们这儿也给出,作为对Mutex和Sync使用的一个例子:































































ThreadLocal的设计与使用
引言
在上面几篇中我们已经分析了Java中对多线程进行同步的几种机制,包括语言级别的synchronized关键字支持、Mutex/Simaphore等高层的同步包的设计和使用。但是,其实早在Java 1.2推出之时,Java平台中就引入了一个新的支持:java.lang.ThreadLocal,给我们在编写多线程程序时提供了一种新的选择。使用这个工具类可以很简洁地编写出优美的多线程程序,虽然ThreadLocal非常有用,但是似乎现在了解它、使用它的朋友还不多。
ThreadLocal是什么
ThreadLocal是什么呢?其实ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是thread local variable(线程局部变量)。也许把它命名为ThreadLocalVar更加合适。线程局部变量(ThreadLocal)其实的功用非常简单,就是为每一个使用该变量的线程都提供一个变量值的副本,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。从线程的角度看,就好像每一个线程都完全拥有该变量。线程局部变量并不是Java的新发明,在其它的一些语言编译器实现(如IBM XL FORTRAN)中,它在语言的层次提供了直接的支持。因为Java中没有提供在语言层次的直接支持,而是提供了一个ThreadLocal的类来提供支持,所以,在Java中编写线程局部变量的代码相对比较笨拙,这也许是线程局部变量没有在Java中得到很好的普及的一个原因吧。
ThreadLocal的设计
首先看看ThreadLocal的接口:
Object get() ; // 返回当前线程的线程局部变量副本
protected Object initialValue(); // 返回该线程局部变量的当前线程的初始值
void set(Object value); // 设置当前线程的线程局部变量副本的值
ThreadLocal有3个方法,其中值得注意的是initialValue(),该方法是一个protected的方法,显然是为了子类重写而特意实现的。该方法返回当前线程在该线程局部变量的初始值,这个方法是一个延迟调用方法,在一个线程第1次调用get()或者set(Object)时才执行,并且仅执行1次。ThreadLocal中的确实实现直接返回一个null:
protected Object initialValue() {
return null;
}
ThreadLocal是如何做到为每一个线程维护变量的副本的呢?其实实现的思路很简单,在ThreadLocal类中有一个Map,用于存储每一个线程的变量的副本。比如下面的示例实现:
public class ThreadLocal {
private Map values = Collections.synchronizedMap(new HashMap());
public Object get() {
Thread curThread = Thread.currentThread();
Object o = values.get(curThread);
if (o == null && !values.containsKey(curThread)) {
o = initialValue();
values.put(curThread, o);
}
return o;
}
public void set(Object newValue) {
values.put(Thread.currentThread(), newValue);
}
public Object initialValue() {
return null;
}
}
当然,这并不是一个工业强度的实现,但JDK中的ThreadLocal的实现总体思路也类似于此。
ThreadLocal的使用
如果希望线程局部变量初始化其它值,那么需要自己实现ThreadLocal的子类并重写该方法,通常使用一个内部匿名类对ThreadLocal进行子类化,比如下面的例子,SerialNum类为每一个类分配一个序号:
public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;
private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};
public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}
SerialNum类的使用将非常地简单,因为get()方法是static的,所以在需要获取当前线程的序号时,简单地调用:
int serial = SerialNum.get();
即可。
在线程是活动的并且ThreadLocal对象是可访问的时,该线程就持有一个到该线程局部变量副本的隐含引用,当该线程运行结束后,该线程拥有的所以线程局部变量的副本都将失效,并等待垃圾收集器收集。
ThreadLocal与其它同步机制的比较
ThreadLocal和其它同步机制相比有什么优势呢?ThreadLocal和其它所有的同步机制都是为了解决多线程中的对同一变量的访问冲突,在普通的同步机制中,是通过对象加锁来实现多个线程对同一变量的安全访问的。这时该变量是多个线程共享的,使用这种同步机制需要很细致地分析在什么时候对变量进行读写,什么时候需要锁定某个对象,什么时候释放该对象的锁等等很多。所有这些都是因为多个线程共享了资源造成的。ThreadLocal就从另一个角度来解决多线程的并发访问,ThreadLocal会为每一个线程维护一个和该线程绑定的变量的副本,从而隔离了多个线程的数据,每一个线程都拥有自己的变量副本,从而也就没有必要对该变量进行同步了。ThreadLocal提供了线程安全的共享对象,在编写多线程代码时,可以把不安全的整个变量封装进ThreadLocal,或者把该对象的特定于线程的状态封装进ThreadLocal。
由于ThreadLocal中可以持有任何类型的对象,所以使用ThreadLocal get当前线程的值是需要进行强制类型转换。但随着新的Java版本(1.5)将模版的引入,新的支持模版参数的ThreadLocal<T>类将从中受益。也可以减少强制类型转换,并将一些错误检查提前到了编译期,将一定程度地简化ThreadLocal的使用。
总结
当然ThreadLocal并不能替代同步机制,两者面向的问题领域不同。同步机制是为了同步多个线程对相同资源的并发访问,是为了多个线程之间进行通信的有效方式;而ThreadLocal是隔离多个线程的数据共享,从根本上就不在多个线程之间共享资源(变量),这样当然不需要对多个线程进行同步了。所以,如果你需要进行多个线程之间进行通信,则使用同步机制;如果需要隔离多个线程之间的共享冲突,可以使用ThreadLocal,这将极大地简化你的程序,使程序更加易读、简洁。
可重入锁的设计及使用
有的时候我们需要锁能够像Java语言的synchronized那样,同一个线程可以重新进入,只要已经拥有了该锁,而不用在该锁上阻塞。我们可以对上篇中的Mutex的实现进行改造,实现一个可重入的锁--ReentrantLock。这需要ReentrantLock中记录当前锁的拥有者(线程),同时设置一个整型变量,记录当前线程进入的次数。
public class ReentrantLock implements Sync {
protected Thread owner_ = null;
protected long holds_ = 0;
//......
}
在获取、释放锁时,首先判断该线程是否是锁的拥有者。如果是当前线程已经拥有该锁,则在每一次acquire()时增1,在release()时减1在次数减少到0时,说明该锁的当前拥有者已经完全释放该锁,不再拥有该锁。所以,将拥有者设置为null。如果当前线程不是锁的拥有者,那么在企图获取锁时在该锁上wait(),在release()方法中,如果拥有者已经完全释放锁,那么就将拥有者清零,并notify()其它线程。
public void acquire() throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
Thread caller = Thread.currentThread();
synchronized(this) { // 在this上同步
if (caller == owner_)
++holds_;
else {
try {
while (owner_ != null) wait();
owner_ = caller;
holds_ = 1;
}
catch (InterruptedException ex) {
notify();
throw ex;
}
}
}
}
public synchronized void release() { //在this上同步
if (Thread.currentThread() != owner_)
throw new Error("Illegal Lock usage");
if (--holds_ == 0) {
owner_ = null;
notify();
}
}
注意上面的代码要对owner_和holds_在this上进行同步,以解决在这两个变量上的竞态条件。attempt()方法实现和Mutex类似,也添加了锁拥有者的检查及计数:
public boolean attempt(long msecs) throws InterruptedException {
if (Thread.interrupted()) throw new InterruptedException();
Thread caller = Thread.currentThread();
synchronized(this) {
if (caller == owner_) {
++holds_;
return true;
}
else if (owner_ == null) {
owner_ = caller;
holds_ = 1;
return true;
}
else if (msecs <= 0)
return false;
else {
long waitTime = msecs;
long start = System.currentTimeMillis();
try {
for (;;) {
wait(waitTime);
if (caller == owner_) {
++holds_;
return true;
}
else if (owner_ == null) {
owner_ = caller;
holds_ = 1;
return true;
}
else {
waitTime = msecs - (System.currentTimeMillis() - start);
if (waitTime <= 0)
return false;
}
}
}
catch (InterruptedException ex) {
notify();
throw ex;
}
}
}
}
由于ReentrantLock增加了对拥有者的计数,所以,也提供了额外的两个方法:holds()和release(long),用于返回当前线程进入的次数(如果当前线程不拥有该锁,则holds()返回0),以及一次性释放多个锁:
public synchronized long holds() {
if (Thread.currentThread() != owner_) return 0;
return holds_;
}
public synchronized void release(long n) {
if (Thread.currentThread() != owner_ || n > holds_)
throw new Error("Illegal Lock usage");
holds_ -= n;
if (holds_ == 0) {
owner_ = null;
notify();
}
}
使用实例
Doug Lea的concurrent包现在已经给广泛使用,在JBoss的org.jboss.mx.loading.UnifiedLoaderRepository 中就使用了concurrent包中的ReentrantLock进行JBoss中的类装载中的同步控制。下面看org.jboss.mx.loading.UnifiedLoaderRepository中对ReentrantLock的使用:
public class UnifiedLoaderRepository
extends LoaderRepository
implements NotificationBroadcaster, UnifiedLoaderRepositoryMBean
{
private ReentrantLock reentrantLock = new ReentrantLock(); //生成一个重入锁
public Class loadClass(String name, boolean resolve, ClassLoader cl)
throws ClassNotFoundException
{
try
{
try
{
// Only one thread at a time can load classes
// Pass the classloader to release its lock when blocking the thread
// We cannot use synchronized (this), as we MUST release the lock
// on the classloader. Change this only after discussion on the
// developer's list !
synchronize(cl); //对传入的ClassLoader上进行同步
// This syncronized block is necessary to synchronize with add/removeClassLoader
// See comments in add/removeClassLoader; we iterate on the classloaders, must avoid
// someone removes or adds a classloader in the meanwhile.
synchronized (this)
{
// Try the cache before anything else.
Class cls = loadClassFromCache(name, cl);
// Found in cache, we're done
if (cls != null) {return cls;}
// Not found in cache, ask the calling classloader
cls = loadClassFromClassLoader(name, resolve, cl);
// The calling classloader sees the class, we're done
if (cls != null) {return cls;}
// Not visible by the calling classloader, iterate on the other classloaders
cls = loadClassFromRepository(name, resolve, cl);
// Some other classloader sees the class, we're done
if (cls != null) {return cls;}
// This class is not visible
throw new ClassNotFoundException(name);
}
}
finally
{
unsynchronize(cl); //使用完毕后释放重入锁
}
}
catch (ClassCircularityError x)
{
//........
}
}
//.........
}
上面代码中的synchronize()和unsynchronize()方法如下:
private void synchronize(ClassLoader cl)
{
// This method
// 1- must allow only one thread at a time,
// 2- must allow a re-entrant thread,
// 3- must unlock the given classloader waiting on it,
// 4- must not hold any other lock.
// If these 4 are not done, deadlock will happen.
// Point 3 is necessary to fix Jung's RFE#4670071
// Beware also that is possible that a classloader arrives here already locked
// (for example via loadClassInternal()) and here we cannot synchronize on 'this'
// otherwise we deadlock in loadClass() where we first synchronize on 'this' and
// then on the classloader (resource ordering problem).
// We solve this by using a reentrant lock.
// Save and clear the interrupted state of the incoming thread
boolean threadWasInterrupted = Thread.currentThread().interrupted();
try
{
// Only one thread can pass this barrier
// Other will accumulate here and let passed one at a time to wait on the classloader,
// like a dropping sink
reentrantLock.acquire();
while (!isThreadAllowed(Thread.currentThread()))
{
// This thread is not allowed to run (another one is already running)
// so I release() to let another thread to enter (will come here again)
// and they will wait on the classloader to release its lock.
// It is important that the wait below is not wait(0) since it may be
// possible that a notifyAll arrives before the wait.
// It is also important that this release() is outside the sync block on
// the classloader, to avoid deadlock with threads that triggered
// loadClassInternal(), locking the classloader
reentrantLock.release();
synchronized (cl)
{
// Threads will wait here on the classloader object.
// Waiting on the classloader is fundamental to workaround Jung's RFE#4670071
// However, we cannot wait(0), since it is possible that 2 threads will try to load
// classes with different classloaders, so one will enter, the other wait, but
// since they're using different classloaders, nobody will wake up the waiting one.
// So we wait for some time and then try again.
try {cl.wait(137);}
catch (InterruptedException ignored) {}
}
// A notifyAll() has been issued, all threads will accumulate here
// and only one at a time will pass, exactly equal to the barrier
// before the 'while' statement (dropping sink).
// Must be outside the synchronized block on the classloader to avoid that
// waiting on the reentrant lock will hold the lock on the classloader
try
{
reentrantLock.acquire();
}
catch (InterruptedException ignored)
{
}
}
}
catch(InterruptedException ignored)
{
}
finally
{
// I must keep track of the threads that entered, also of the reentrant ones,
// see unsynchronize()
increaseThreadsCount();
// I release the lock, allowing another thread to enter.
// This new thread will not be allowed and will wait() on the classloader object,
// releasing its lock.
reentrantLock.release();
// Restore the interrupted state of the thread
if( threadWasInterrupted )
Thread.currentThread().interrupt();
}
}
private void unsynchronize(ClassLoader cl)
{
// Save and clear the interrupted state of the incoming thread
boolean threadWasInterrupted = Thread.currentThread().interrupted();
try
{
reentrantLock.acquire();
// Reset the current thread only if we're not reentrant
if (decreaseThreadsCount() == 0)
{
setCurrentThread(null);
}
}
catch (InterruptedException ignored)
{
}
finally
{
reentrantLock.release();
// Notify all threads waiting on this classloader
// This notification must be after the reentrantLock's release() to avoid this scenario:
// - Thread A is loading a class in the ULR
// - Thread B triggers a loadClassInternal which locks the UCL
// - Thread A calls unsynchronize, locks the reentrantLock
// and waits to acquire the lock on the UCL
// - Thread B calls synchronize and waits to lock the reentrantLock
synchronized (cl)
{
cl.notifyAll();
}
// Restore the interrupted state of the thread
if( threadWasInterrupted )
Thread.currentThread().interrupt();
}
}
同步代码等同于断面
同步经常作为断面被引用。断面是指一次只能有一个线程执行它。多个线程同时执行同步代码是有可能的。
这个误解是因为很多程序员认为同步关键字锁住了它所包围的代码。但是实际情况不是这样的。同步加锁的是对象,而不是代码。因此,如果你的类中有一个同步方法,这个方法可以被两个不同的线程同时执行,只要每个线程自己创建一个的该类的实例即可。
参考下面的代码:
class Foo extends Thread
{
private int val;
public Foo(int v)
{
val = v;
}
public synchronized void printVal(int v)
{
while(true)
System.out.println(v);
}
public void run()
{
printVal(val);
}
}
class SyncTest
{
public static void main(String args[])
{
Foo f1 = new Foo(1);
f1.start();
Foo f2 = new Foo(3);
f2.start();
}
}
运行SyncTest产生的输出是1和3交叉的。如果printVal是断面,你看到的输出只能是1或者只能是3而不能是两者同时出现。程序运行的结果证明两个线程都在并发的执行printVal方法,即使该方法是同步的并且由于是一个无限循环而没有终止。
要实现真正的断面,你必须同步一个全局对象或者对类进行同步。下面的代码给出了一个这样的范例。
class Foo extends Thread
{
private int val;
public Foo(int v)
{
val = v;
}
public void printVal(int v)
{
synchronized(Foo.class) {
while(true)
System.out.println(v);
}
}
public void run()
{
printVal(val);
}
}
上面的类不再对个别的类实例同步而是对类进行同步。对于类Foo而言,它只有唯一的类定义,两个线程在相同的锁上同步,因此只有一个线程可以执行printVal方法。
这个代码也可以通过对公共对象加锁。例如给Foo添加一个静态成员。两个方法都可以同步这个对象而达到线程安全。
面笔者给出一个参考实现,给出同步公共对象的两种通常方法:
1、
class Foo extends Thread
{
private int val;
private static Object lock=new Object();
public Foo(int v)
{
val = v;
}
public void printVal(int v)
{
synchronized(lock) {
while(true)
System.out.println(v);
}
}
public void run()
{
printVal(val);
}
}
上面的这个例子比原文给出的例子要好一些,因为原文中的加锁是针对类定义的,一个类只能有一个类定义,而同步的一般原理是应该尽量减小同步的粒度以到达更好的性能。笔者给出的范例的同步粒度比原文的要小。
2、
class Foo extends Thread
{
private String name;
private String val;
public Foo(String name,String v)
{
this.name=name;
val = v;
}
public void printVal()
{
synchronized(val) {
while(true) System.out.println(name+val);
}
}
public void run()
{
printVal();
}
}
public class SyncMethodTest
{
public static void main(String args[])
{
Foo f1 = new Foo("Foo 1:","printVal");
f1.start();
Foo f2 = new Foo("Foo 2:","printVal");
f2.start();
}
}
上面这个代码需要进行一些额外的说明,因为JVM有一种优化机制,因为String类型的对象是不可变的,因此当你使用""的形式引用字符串时,如果JVM发现内存已经有一个这样的对象,那么它就使用那个对象而不再生成一个新的String对象,这样是为了减小内存的使用。
上面的main方法其实等同于:
public static void main(String args[])
{
String value="printVal";
Foo f1 = new Foo("Foo 1:",value);
f1.start();
Foo f2 = new Foo("Foo 2:",value);
f2.start();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决