Skip to content

Instantly share code, notes, and snippets.

@yanglikun
Created February 27, 2019 03:11
Show Gist options
  • Save yanglikun/1d85ab5f0c2b1abfa9dd32f7153fe700 to your computer and use it in GitHub Desktop.
Save yanglikun/1d85ab5f0c2b1abfa9dd32f7153fe700 to your computer and use it in GitHub Desktop.
偏向锁
/**
* 使用如下命令运行:
* java -XX:+UseBiasedLocking //开启偏向锁,如果关闭用 -XX:-UseBiasedLocking
* -XX:+UnlockDiagnosticVMOptions //打开诊断模式,才能使用PrintBiasedLockingStatistics打印偏向锁信息
* -XX:+PrintBiasedLockingStatistics//在C1中打印偏向锁信息
* -XX:TieredStopAtLevel=1 //设置JIT编译器为C1
* -XX:BiasedLockingStartupDelay=0 //关闭偏向锁启动延时,jdk6有4秒延时,4秒内用lightweight,4秒后才开始启动biased lock
* BiasedLockAndHashCodeTest
*/
public class BiasedLockAndHashCodeTest {
static MyLock myLock = new MyLock();
static int counter = 0;
public static void foo() {synchronized (myLock) {counter++;}}
public static void main(String[] args) {
// myLock.hashCode(); // Step 2
// System.identityHashCode(myLock); // Step 4
for (int i = 0; i < 1_000_000; i++) {foo();}
}
static class MyLock {
// public int hashCode() {return 123;} // Step 3
}
}
@yanglikun
Copy link
Author

  • 开启偏向锁
    image
  • 关闭偏向锁
    image
  • 放开注释:step 2
    image
  • 放开注释:step 3
    image
  • 放开注释:step 4
    image
    总结
    1、step2:没有重写hashCode():会关闭偏向锁
    没有重写hashCode(),会调用父类的hashCode方法,(这里是Object),Object也会调用 System.identityHashCode()
    2、step3: 重写hashCode():不会关闭偏向锁
    重写后,就不会调用System.identityHashCode()
    3、step4:显示调用System.identityHashCode():会关闭偏向锁

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment