`
leonzhx
  • 浏览: 786939 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Zz Biased Locking in Java SE 6.0

    博客分类:
  • Java
 
阅读更多

the original article is in : http://ceki.blogspot.com/2009/06/biased-locking-in-java-se-60.html

 

As a result of the ensuing discussion in response to this blog entry, it is now pretty clear that the issue described herein is not specific to Java SE 6. Please do not reach any conclusions without reading the entire post, including the comments, and especially the comments.

Joern Huxhorn recently informed logback developers that locking in Java SE 6.0 was unfair. Indeed, Java documentation regularly mentions that one should not make assumptions about Java's thread scheduler. For example, the last paragraph of Thread Priority on the Solaris™ Platform , states:
Likewise, no assumptions should be made about the order in which threads are granted ownership of a monitor or the order in which threads wake in response to the notify or notifyAll method. An excellent reference for these topics is Chapter 9, "Threads," in Joshua Bloch's book "Effective Java Programming Language Guide."
If you actually bother to read the book, in Item 51, Joshua Bloch writes:
When multiple threads are runnable, the thread scheduler determines which threads get run and for how long. Any reasonable JVM implementation will attempt some sort of fairness when making this determination.
While Joshua Bloch's statement above is specifically about the JVM scheduler, I think that the notion of "some sort of fairness" applies to locks as well. The general principle is the same.

Here is a small java application called LockingInJava which illustrates the locking behavior in question.
public class LockingInJava implements Runnable {
	static int THREAD_COUNT = 5;
	static Object LOCK = new Object();
	static Runnable[] RUNNABLE_ARRAY = new Runnable[THREAD_COUNT];
	static Thread[] THREAD_ARRAY = new Thread[THREAD_COUNT];
	private int counter = 0;

	public static void main(String args[]) throws InterruptedException {
		printEnvironmentInfo();
		execute();
		printResults();
	}

	public static void printEnvironmentInfo() {
		System.out.println("java.runtime.version = "
				+ System.getProperty("java.runtime.version"));
		System.out.println("java.vendor          = "
				+ System.getProperty("java.vendor"));
		System.out.println("java.version         = "
				+ System.getProperty("java.version"));
		System.out.println("os.name              = "
				+ System.getProperty("os.name"));
		System.out.println("os.version           = "
				+ System.getProperty("os.version"));
	}

	public static void execute() throws InterruptedException {
		for (int i = 0; i < THREAD_COUNT; i++) {
			RUNNABLE_ARRAY[i] = new LockingInJava();
			THREAD_ARRAY[i] = new Thread(RUNNABLE_ARRAY[i]);
		}
		for (Thread t : THREAD_ARRAY) {
			t.start();
		} // let the threads run for a while
		Thread.sleep(10000);
		for (int i = THREAD_COUNT - 1; i >= 0; i--) {
			THREAD_ARRAY[i].interrupt();
		}
		Thread.sleep(100); // wait a moment for termination, too lazy for join
							// ;)
	}

	public static void printResults() {
		for (int i = 0; i < RUNNABLE_ARRAY.length; i++) {
			System.out.println("runnable[" + i + "]: " + RUNNABLE_ARRAY[i]);
		}
	}

	public void run() {
		for (;;) {
			synchronized (LOCK) {
				counter++;
				try {
					Thread.sleep(10);
				} catch (InterruptedException ex) {
					break;
				}
			}
		}
	}

	public String toString() {
		return "counter=" + counter;
	}
}
 
When run under Sun's JDK version 1.6.0_11 on a 64bit Dual Core AMD Opteron running Linux, here is what gets printed on the console.
java.runtime.version = 1.6.0_11-b03
java.vendor          = Sun Microsystems Inc.
java.version         = 1.6.0_11
os.name              = Linux
os.version           = 2.6.25-gentoo-r6
runnable[0]: counter=1002
runnable[1]: counter=0
runnable[2]: counter=0
runnable[3]: counter=0
runnable[4]: counter=0
 
Notice how only the first thread gets any work done. All the other threads are completely starved while waiting for the lock. The same application run with JDK 1.5 or older will have much more uniform results. Some threads will get more often access to the lock than others, but all threads will get some access. With JDK 1.6, access to locks is dispensed in a biased fashion . In other words, the thread currently holding the lock will always be favored compared to other competing threads. Sun calls it biased locking. It purportedly makes better use of CPU capabilities.

As for the argument about no guarantees offered about fairness, while true in letter, it is invalid in spirit. The argument is too punctilious and formalistic. Any developer reading the documentation will naturally assume that while there are no guarantees, the synchronization mechanism will not actively impede fairness.

Biased locking, as introduced in JDK 1.6, will affect thousands of unsuspecting applications. The fact that the bias is intentional does not make it less damaging. It's still a bug.
分享到:
评论

相关推荐

    Biased Locking in HotSpot

    HotSpot虚拟机作为Java平台的主流虚拟机之一,提供了多种锁优化策略,其中之一就是“偏见锁”(Biased Locking)。本文将深入探讨HotSpot中的偏见锁机制,以及它如何提高并发性能。 偏见锁是一种针对轻量级锁的优化...

    Biased Locking in HotSpot - Dave - 2006.pdf

    知识点一:偏向锁(Biased Locking)的起源 偏向锁的概念源自于一篇由Dave、Mark Moir和Bill Scherer共同撰写的论文。作者们指出,传统的Java监控锁(即synchronized锁)在执行CAS操作(比较并交换)时会带来显著的...

    深入理解Java虚拟机笔记(带目录).docx

    * 使用偏向锁机制(Biased Locking):让线程在锁竞争时停在安全点上。 垃圾收集器 Java 中的垃圾收集器有以下几种: * Serial 垃圾收集器:单线程的垃圾收集器。 * Parallel 垃圾收集器:多线程的垃圾收集器。 *...

    JVM基础JVM基础JVM基础

    Java中的锁机制主要有两种:偏向锁(Biased Locking)、轻量级锁(Lightweight Locking)和重量级锁(Heavyweight Locking)。此外,Java还提供了各种同步机制来确保多线程环境下的数据安全性,如synchronized关键字、...

    小议偏向锁

    Eliminating Synchronization-Related Atomic Operations with Biased Locking and Bulk Rebiasing 博文链接:https://xieyj.iteye.com/blog/322089

    java并发编程综合讲解

    - **偏向锁(Biased Locking)**:当一个线程连续持有锁时,可以优化为偏向锁,减少锁状态转换的开销。 - **适应性⾃旋(Adaptive Spinning)**:根据系统负载动态调整自旋等待的时间,以平衡锁等待和上下文切换的...

    JAVA锁优化和膨胀过程.docx

    这些技术包括自适应自旋(Adaptive Spinning)、锁删除(Lock Elimination)、锁膨胀(Lock Coarsening)、轻量级锁(Lightweight Locking)和偏向锁(Biased Locking)。 自适应自旋是一种技术,通过多次尝试,...

    Java分布式应用学习笔记03JVM对线程的资源同步和交互机制

    2. **偏向锁(Biased Locking)**:这是一种轻量级的锁机制,用于减少无竞争情况下的同步开销。当一个线程首次访问一个对象的锁时,JVM会尝试使用偏向锁。如果在后续的访问中没有其他线程竞争,那么这个线程就可以...

    Lock-in Amplifier.pdf

    subject there follows a simple intuitive account biased towards light measurement applications. All lock-in amplifiers, whether analogue or digital, rely on the concept of phase sensitive detection...

    bcr.rar_BCR_Biased

    "BCR"(Biased Coin Randomization)是一种在随机化过程中采用的方法,其核心在于模拟偏倚硬币抛掷的过程来分配受试者到不同的治疗组。标题中的“bcr.rar_BCR_Biased”可能是一个包含BCR算法实现和相关资料的压缩...

    invest-email-biased.csv

    invest-email-biased.csv

    浅谈Java虚拟机对内部锁的四种优化方式

    3. **偏向锁(Biased Locking)** 偏向锁是一种优化策略,适用于大多数情况下只有一个线程访问同步块的情况。当一个线程进入同步块并获得锁时,JVM会在对象头中记录这个线程的标识,之后只要这个线程再次尝试获取该...

    秩偏重叠列表相似性度量 的 Python 实现_python_代码_下载

    一个小的 Python 模块,用于计算rank-biased overlay,衡量参差不齐的、可能无限的排名列表之间的相似性,这些列表可能包含也可能不包含相同的项目(直到实际评估的深度或根本不包含)。参见 W. Webber、A. Moffat ...

    并发面试专题.docx

    Synchronized 相关问题 Synchronized 是 Java 语言中的一种实现...现代 JDK 中做了大量的优化,包括使用自旋锁、偏向锁(Biased Locking)、轻量级锁、重量级锁等,这些优化使得 JDK 能够优化 Synchronized 的运行。

    顶尖的Java多线程、锁、内存模型面试题!.docx

    - **偏向锁(Biased Locking):** 当一个对象被首次锁定时,JVM 使用偏向锁。在这种模式下,对象头被设置为指向当前持有锁的线程。如果之后没有其他线程试图获取该锁,那么该线程就可以无锁地访问对象。这减少了无...

    2020-5-A biased randomised algorithm for the capacitated facility location problem with soft constraints.pdf

    biased-randomised algorithm for the capacitated facility location problem with soft constraints 在运筹学领域中,设施位置问题(Facility Location Problem,FLP)是一个经典的优化问题。它的目标是确定设施...

    第16讲synchronized底层如何实现?什么是锁...1

    1. **偏斜锁(Biased Locking)**:在没有竞争的情况下,synchronized会尝试使用偏斜锁,这是一种优化策略。JVM会在对象头的Mark Word中存储当前线程ID,表示对象偏向于该线程。如果只有一个线程访问,避免了锁的...

    Traps and Pitfalls of Topic-Biased PageRank-计算机科学

    Traps and Pitfalls of Topic-Biased PageRankPaolo Boldi∗ Roberto Posenato† Massimo Santini Sebastiano Vigna Dipartimento di Scienze dell’Informazione, Università degli Studi di Milano, Italyand† ...

    JEDEC JESD226:2013 RF BIASED LIFE (RFBL) TEST METHOD - 完整英文电子版(17页).pdf

    JEDEC JESD226:2013 RF BIASED LIFE (RFBL) TEST METHOD JEDEC JESD226:2013 RF BIASED LIFE (RFBL) TEST METHOD 是一份关于射频偏置生命试验方法的技术标准,发布于2013年,由JEDEC Solid State Technology ...

    Effective Computation of Biased Quantiles over Data Streams (bquant)-计算机科学

    AT&T Labs–Researchdivesh@research.att.comAbstractSkew is prevalent in many data sourcessuchas IP traffic streams. To continually summarize the distribution of such data, a high- biased set of ...

Global site tag (gtag.js) - Google Analytics