add demo for constant pool
add demo for fix deadlock
This commit is contained in:
14
src/main/java/jvm/ConstantPoolDemo.java
Normal file
14
src/main/java/jvm/ConstantPoolDemo.java
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package jvm;
|
||||||
|
|
||||||
|
public class ConstantPoolDemo {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
//this will be equal since it is first time to create
|
||||||
|
String greeting = new StringBuilder("Hello ").append("Jason").toString();
|
||||||
|
System.out.println(greeting == greeting.intern());
|
||||||
|
|
||||||
|
//This will not be equal since it is already created before and cached in constant pool
|
||||||
|
String java = new StringBuilder("ja").append("va").toString();
|
||||||
|
System.out.println(java == java.intern());
|
||||||
|
}
|
||||||
|
}
|
||||||
41
src/main/java/threaddemo/DeadLockFixDemo.java
Normal file
41
src/main/java/threaddemo/DeadLockFixDemo.java
Normal file
@@ -0,0 +1,41 @@
|
|||||||
|
package threaddemo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* fix deadlock by keeping the lock in the same order
|
||||||
|
*/
|
||||||
|
public class DeadLockFixDemo {
|
||||||
|
private static final Object resource1 = new Object();
|
||||||
|
private static final Object resource2 = new Object();
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new Thread(() -> {
|
||||||
|
synchronized (resource1) {
|
||||||
|
System.out.println(STR."\{Thread.currentThread()}get resource1");
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
System.out.println(STR."\{Thread.currentThread()} waiting get resource2");
|
||||||
|
synchronized (resource2) {
|
||||||
|
System.out.println(STR."\{Thread.currentThread()} get resource2");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},"t1").start();
|
||||||
|
|
||||||
|
new Thread(() -> {
|
||||||
|
synchronized (resource1) {
|
||||||
|
System.out.println(Thread.currentThread() + "get resource1");
|
||||||
|
try {
|
||||||
|
Thread.sleep(1000);
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
|
||||||
|
System.out.println(Thread.currentThread() + "waiting get resource2");
|
||||||
|
synchronized (resource2) {
|
||||||
|
System.out.println(Thread.currentThread() + "get resource2");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},"t2").start();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user