`
yanghuidang
  • 浏览: 908196 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Java 多线程同步问题的探究(三、Lock来了,大家都让开【2. Fair or Unfair? It is a question...】)

 
阅读更多
让我们继续前面有关ReentrantLock的话题。
首先,ReentrantLock有一个带布尔型参数的构造函数,在JDK官方文档中对它是这样描述的:
“此类的构造方法接受一个可选的公平 参数。当设置为 true 时,在多个线程的争用下,这些锁倾向于将访问权授予等待时间最长的线程。否则此锁将无法保证任何特定访问顺序。与采用默认设置(使用不公平锁)相比,使用公平锁的程序在许多线程访问时表现为很低的总体吞吐量(即速度很慢,常常极其慢),但是在获得锁和保证锁分配的均衡性时差异较小。不过要注意的是,公平锁不能保证线程调度的公平性。因此,使用公平锁的众多线程中的一员可能获得多倍的成功机会,这种情况发生在其他活动线程没有被处理并且目前并未持有锁时。还要注意的是,未定时的 tryLock 方法并没有使用公平设置。因为即使其他线程正在等待,只要该锁是可用的,此方法就可以获得成功。 ”

简单来讲:公平锁使线程按照请求锁的顺序依次获得锁;而不公平锁则允许讨价还价,在这种情况下,线程有时可以比先请求锁的其他线程先得到锁。

观察采用公平锁和非公平锁的例程运行效果发现:线程获得锁的顺序发生了一些变化(见下表)。
<style type="text/css"> <!-- page {margin:2cm} td p {margin-bottom:0cm} p {margin-bottom:0.21cm} --> </style>

Unfair:


1 is running!

1 got lock1@Step1!

3 is running!

2 is running!

1 first Reading count:1

1 release lock1@Step1!

3 got lock1@Step1!

1 got lock2@Step2!

thread 1 set age to:18

thread 1 first read age is:18

3 first Reading count:2

3 release lock1@Step1!

2 got lock1@Step1!

thread 1 second read age is:18

1 release lock2@Step2!

3 got lock2@Step2!

thread 3 set age to:34

thread 3 first read age is:34

2 first Reading count:3

2 release lock1@Step1!

thread 3 second read age is:34

3 release lock2@Step2!

2 got lock2@Step2!

thread 2 set age to:72

thread 2 first read age is:72

thread 2 second read age is:72

2 release lock2@Step2!

成功生成(总时间:20 秒)

Fair:


1 is running!

1 got lock1@Step1!

2 is running!

3 is running!

1 first Reading count:1

1 release lock1@Step1!

1 got lock2@Step2!

thread 1 set age to:82

thread 1 first read age is:82

2 got lock1@Step1!

2 first Reading count:2

2 release lock1@Step1!

3 got lock1@Step1!

thread 1 second read age is:82

1 release lock2@Step2!

2 got lock2@Step2!

thread 2 set age to:65

thread 2 first read age is:65

3 first Reading count:3

3 release lock1@Step1!

thread 2 second read age is:65

2 release lock2@Step2!

3 got lock2@Step2!

thread 3 set age to:31

thread 3 first read age is:31

thread 3 second read age is:31

3 release lock2@Step2!

成功生成(总时间:20 秒)

转载注明出处:http://x- spirit.javaeye.com/、http: //www.blogjava.net/zhangwei217245/
这样的变化告诉我们:
采用非公平的锁时,当一个线程释放了第一个锁以后,由于线程的抢占,刚刚被释放的锁马上被下一个线程占有。采用公平锁时,由于公平锁倾向于将访问权授予等待时间最长的线程,所以,当第一个锁被第一个线程释放以后,第二个锁马上将访问权授予第一个线程,而第一个锁将访问权授予了第二个线程。这里,公平锁在平衡分配方面耗费了一定的时间,这使得第一个线程获得第二个锁的时间优先于第二个线程获得第一个锁。这样,采用不同的锁,就出现了两种不同的结果。
转载注明出处:http://x- spirit.javaeye.com/、http: //www.blogjava.net/zhangwei217245/
为了看到公平锁和非公平锁性能上的差异,我们不妨将其中线程的睡眠时间设定为1毫秒,然后把循环产生的线程数提高到5000(修改后的代码已忽略,自行修改),可以发现,由于公平锁要维持锁分配的均衡性,所以,采用公平锁的程序总运行时间更长一些。
转载注明出处:http://x- spirit.javaeye.com/、http: //www.blogjava.net/zhangwei217245/
根据运行环境的差异,有些朋友可能并不一定能很直观的从运行结果中看到两种不同的锁带来的性能差异。不妨引用IBM开发者社区的一组测试结果来看一看就行有什么样的差异吧:
4CPU情况下的同步、非公平锁和公平锁吞吐量比较:

单CPU情况下,同步、非公平锁和公平锁的吞吐量:


可以看到,同步和公平锁的吞吐量都是最低的,公平锁更低一些。但是同步内置的监控器锁是不公平的,而且永远都是不公平的。而JVM 保证了所有线程最终都会得到它们所等候的锁。确保统计上的公平性,对多数情况来说,这就已经足够了,而这花费的成本则要比绝对的公平保证的低得多。
转载注明出处:http://x- spirit.javaeye.com/、http: //www.blogjava.net/zhangwei217245/
既然Lock这么近乎完美,那我们也许可以忘却synchronized了。

但是任何事物都是有两面性的。
1.使用Lock,你必须手动的在finally块中释放锁。锁的获得和释放是不受JVM控制的。这要求编程人员更加细心。
2.当 JVM 用 synchronized 管理锁定请求和释放时,JVM 在生成线程转储时能够包括锁定信息。这些对调试非常有价值,因为它们能标识死锁或者其他异常行为的来源。 <wbr>de&gt;Lock<wbr>de&gt; 类只是普通的类,JVM 不知道具体哪个线程拥有 <wbr>de&gt;Lock<wbr>de&gt; 对象。<br><span style="color:rgb(255,255,255)">转载注明出处:http://x- spirit.javaeye.com/、http: //www.blogjava.net/zhangwei217245/</span> <br> Lock提供了在多线程争用的情况下更好的并发性,但这是以牺牲一定的可维护性为代价的。<br><span style="color:rgb(255,255,255)">转载注明出处:http://x- spirit.javaeye.com/、http: //www.blogjava.net/zhangwei217245/</span> <br> 所以说,当大量线程发生争用的时候,Lock来了,大家都让开。</wbr></wbr></wbr></wbr>
分享到:
评论

相关推荐

    2008年6月大学英语六级A卷真题

    Ideally, such a source would be safe in that it could not be made into weapons and would not make hazardous or toxic waste or carbon dioxide, the main greenhouse gas blamed for global warming....

    计算机网络第六版答案

    (This is a little bit of a white lie, as modern routers sometimes act as firewalls or caching components, and process Transport layer as well.) Link layer switches process link and physical layers ...

    DbfDotNet_version_1.0_Source

    This library is a work in progress, I am looking for some feedback on this to see if there is a need for it. This article is also a work in progress please bookmark and come back later, if you want ...

    C++程序设计语言(特别版) 英文原版

    order so that a construct is used only after it has been defined.However,it is much easier to use a well-designed library than it is to understand the details of its implementation.Therefore,the stan-...

    c# sample15个例子

    An Excluded License is one that requires, as a condition of use, modification or distribution, that * the code be disclosed or distributed in source code form; or * others have the right to modify ...

    Autoruns-v9.1.3H

    It also applies even if Sysinternals knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your country may not allow the ...

    mips32 4ksd内核软件用户手册

    mips 的 4ksd芯片手册 Unpublished work (C) MIPS Technologies, Inc. All rights reserved....laws of the United States of America ...SEAD-2, SOC-it and YAMON are among the trademarks of MIPS Technologies, Inc.

    MIPS32(TM) 4KSd(TM) USIP Professional文档

    This document contains confidential information that is the strict property of Innova Card, and may only be disclosed with written permission from Innova Card itself. Any copy, reproduction, ...

    iTunesConnect_DeveloperGuide

    No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, mechanical, electronic, photocopying, recording, or otherwise, without prior ...

    Local Shannon entropy measure with statistical tests for image randomness.pdf

    In this paper we propose a new image randomness measure using Shannon entropy over local image blocks. The proposed local Shannon entropy measure overcomes several weaknesses of the conventional ...

    Blockchain Unfair Transaction Order Prediction

    关于Blockchain Unfair Transaction Order Prediction项目的中期答辩ppt

    chi-squared-test:用于计算卡方概率的节点模块

    // We expect a fair dievar expected = [2, 2, 2, 2, 2, 2];// Looks pretty unfair...var observed = [6, 3, 3, 0, 0, 0];// Reduction in degrees of freedom is 1, since knowing 5 categories determines the 6...

    Philosophical and Mathematical Logic (Springer原版超清)

    Social Choice Theory, in particular Majority Judgment) and finally, Fallacies and Unfair Discussion Methods. Throughout the text, the author provides some impressions of the historical development of...

    unfair:一个用SFML用C ++编写的简单的地狱游戏

    Q或右键单击炸弹每个子弹都有速度,加速度,角速度,角加速度等游戏内统计信息(玩过的游戏,获胜,失败,平均得分等) 成绩记录系统嵌入式时钟几种视觉选项(垂直同步,抗锯齿等) 游戏中的作弊技巧,可为您提供更...

    Development of calibration models for rapid determination of moisture content in rubber sheets using portable near-infrared spectrometers

    The quality of a rubber sheet can be visually examined by holding it against clear light to inspect for any specks and impurities inside, but its moisture content is di±cult to evaluate based on a ...

    承包“物联网”:探究巢穴-研究论文

    在讨论了有关物联网供应链的一般合同法问题之后,我们研究了这些法律中代表的权利和义务,并讨论了它们在多大程度上共同提供了一个连贯且可理解的私法框架。 然后,我们从解决两个特征性合同问题(责任归因和不公平...

    STM32F103驱动MAX7219.rar

    使用STM32F103ZET6主控,可使用其自带的硬件SPI或者使用软件模拟SPI的方式驱动MAX7219 8*8点阵。

    单片机软件模拟IIC/I2C,读写24C64

    24C64和24C02都为EEPROM,但是他们的容量大小不同,所以在使用时主要的区别是地址长度,其次是页写的字节数,其余读写时序一致。文件中是使用STM32F407进行模拟I2C时序,封装了包括字节读、写;全局读、写等函数,可...

    软件合同法的原则:版权法,消费者法和欧洲法不合时宜吗?-研究论文

    我将争辩说,起草过程并未充分考虑1990年代末提出的《统一商法典》第2B条,然后是《统一计算机信息交易法》(“ UCITA”),其中包括鼓励违反条款的条款。试图禁止公平使用或从公共领域撤回材料而构成版权或专利...

    cubeIDE配置STM32串口通信及调试问题

    cubeide配置STM32F407ZET6串口,完成串口收发功能,接收外部发送的指令并进行解析,完成对指示灯的亮灭控制

Global site tag (gtag.js) - Google Analytics