Skip to content

Instantly share code, notes, and snippets.

@lichengwu
Last active December 10, 2015 01:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lichengwu/4362829 to your computer and use it in GitHub Desktop.
Save lichengwu/4362829 to your computer and use it in GitHub Desktop.
JVM's build-in lock is not safe enough, it may cause deadlock while the build-in lock acquired by other threads.
package oliver.test.conurrency;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* do not use build-in lock
*
* if a class use build-in lock ensure concurrence access it's field, thread
* will be blocked by other threads who had acquired the lock.
*
* @author lichengwu
* @version 1.0
* @created 2012-12-23 PM5:38
*/
public class DoNotUseBuildInLockTest {
public static void main(String[] args) throws InterruptedException {
// lock object use build-in lock in method get()
final LockObject object = new LockObject();
// a thread acquire the LockObject's build-in lock
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread 1 acquire lock : " + new Date().toString());
synchronized (object) {
try {
TimeUnit.SECONDS.sleep(10);
} catch (InterruptedException e) {
}
}
System.out.println("thread 1 release lock : " + new Date().toString());
}
}).start();
// sleep main thread ensure the thread above had been started.
TimeUnit.SECONDS.sleep(2);
// the other start and call get() method, but the build-in lock
// had been hold by the thread above.
// get() method must wait for the build-in lock.
new Thread(new Runnable() {
@Override
public void run() {
long begin = System.currentTimeMillis();
object.get();
System.out.println("get() method wait :" + (System.currentTimeMillis() - begin)
+ "ms");
}
}).start();
}
}
package oliver.test.conurrency;
/**
* a class with build-in lock method
*
* @author lichengwu
* @version 1.0
* @created 2012-12-23 PM5:39
*/
public class LockObject {
private int count = 0;
// access by build-in lock
public synchronized int get() {
return count++;
}
}
thread 1 acquire lock : Sun Dec 23 18:10:47 CST 2012
get() method wait :8019ms
thread 1 release lock : Sun Dec 23 18:10:57 CST 2012
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment