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所在的类上同步是不好的做法。您的选择将取决于本课程中的其他内容以及您需要的性能。