JVM如何确保只有一个线程可以获取对象的锁? [英] How does JVM make sure only one thread can acquire the lock of an object?

查看:294
本文介绍了JVM如何确保只有一个线程可以获取对象的锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们大多数人都知道,只要线程访问对象的同步块,JVM就会将该对象的锁授予线程. JVM如何确保只有一个线程可以访问一个对象的锁?

Most of us know that whenever thread accesses a synchronized block of a object, JVM gives the lock of that object to the thread. How does JVM make sure that only one thread can have access to a lock of an object?

推荐答案

JVM使用操作系统提供的某些锁定功能,例如信号量对象.因此,问题就变成了操作系统如何实现.

The JVM uses some locking feature provided by the operating system, like a semaphore object. So the question now becomes how the operating system does it.

通常,这些东西都有硬件支持. CPU可以提供比较并设置指令,该指令在执行时设置CPU的引脚(在多CPU架构中有用)或CPU的内部线(对于单CPU多核架构),该指令告诉其他硬件:当前在地址总线上形成的存储位​​置不得由任何其他人更改.因此,硬件体系结构保证了该指令的原子性.

Usually there is hardware support for these things. The CPU may offer a compare-and-set instruction which, while executing, sets a pin of the CPU (useful in multi-CPU architectures) or an internal line of the CPU (for single-CPU multicore architectures) which tells other hardware that the memory location currently formed on the address bus is not to be altered by anyone else. So, the hardware architecture guarantees the atomicity of this instruction.

一旦您有了保证原子的比较并设置指令,其余的操作就相对容易了:锁对象有一个标志;希望获取锁的线程在该标志上执行比较置位指令,值为1;如果比较的结果为true,则该值已经为1,因此其他某个线程已经具有该锁.如果结果为假,则该值不为1,因此当前线程现在可以认为自己是该锁的所有者.

Once you have a guaranteed-atomic compare-and-set instruction, the rest is relatively easy: the lock object has a flag; the thread wishing to acquire the lock performs a compare-and-set instruction on that flag with a value of 1; if the result of the comparison is true, then the value was already 1, so some other thread already had the lock. If the result is false, then the value was not 1, so the current thread may consider itself to be the owner of the lock now.

如果操作系统无法代表线程获取锁,则它将线程置于等待锁"状态,在该状态下,线程将一直停留到释放锁为止.

If the operating system cannot acquire a lock on behalf of a thread, then it places the thread in a "waiting for lock" state, in which the thread will stay until the lock gets released.

这篇关于JVM如何确保只有一个线程可以获取对象的锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆