Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java同步块:锁定块直到对象实例化_Java_Multithreading_Locking_Synchronized - Fatal编程技术网

Java同步块:锁定块直到对象实例化

Java同步块:锁定块直到对象实例化,java,multithreading,locking,synchronized,Java,Multithreading,Locking,Synchronized,我想同步我的代码块,并且仅当对象连接被实例化时才释放它,我如何才能做到这一点 public void myMethod() { Connection connection = null; synchronized (connection) { // Set configuration, block of code to synchronize } connection = getConnection(configuration); // Should be released af

我想同步我的代码块,并且仅当对象连接被实例化时才释放它,我如何才能做到这一点

public void myMethod() {

 Connection connection = null;

 synchronized (connection) {
 // Set configuration, block of code to synchronize
 }

 connection = getConnection(configuration); // Should be released after this
}

使用单独的东西作为显示器:

private final Object myMethodLock = new Object();

public void myMethod() {

 Connection connection = null;

 synchronized (myMethodLock) {
   connection = getConnection(configuration);
 }

 // myMethodLock has been released.
}

在非最终的对象上同步考虑在方法级别或MyPosiod所在的类上同步是不好的做法。您的选择将取决于本课程中的其他内容以及您需要的性能。