我有以下代码段:
public class Service<T> {
private ConcurrentMap<Integer, Integer> locks = new ConcurrentHashMap<Integer, Integer>();
public final ExecutorService exec = Executors.newFixedThreadPool(5);
public Future<Boolean> foo(T o, String fileName) throws IOException {
return exec.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws IOException {
File f = new File(fileName);
// synchronized (getCacheSyncObject(name.hashCode())) {
// try (OutputStream out = new FileOutputStream(f)) {
// //some actions
// }
// }
try (OutputStream out = new FileOutputStream(f)) {
//some actions
}
return true;
}
});
}
private Object getCacheSyncObject(final Integer id) {
locks.putIfAbsent(id, id);
return locks.get(id);
}
}
public class Main {
public static void main(String[] args) throws IOException {
Object obj = new Object();
Service<Object> service = new Service<>();
Future<Boolean> result1 = service.foo(obj, "filename"); // is there a deadlock?
service.exec.shutdown();
}
}
我想完成一项简单的任务。我需要一个独占文件锁定。为了得到这个,我把文件的文件名锁定到同步块。但在这种情况下,我从foo
方法中得不到任何东西。我的节目没有结束。
答案 0 :(得分:1)
如果您正在寻找服务范围内的锁定,则可以使用其字段来存储锁定。但我建议不要使用fileName.hashCode(),因为可能会发生冲突。改为使用整个名称:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
class Service<T> {
private final ConcurrentMap<String, Object> locks = new ConcurrentHashMap<>();
public final ExecutorService exec = Executors.newFixedThreadPool(5);
public Future<Boolean> foo(T o,
final String fileName) throws IOException {
return exec.submit(new Callable<Boolean>() {
@Override
public Boolean call() throws IOException {
File f = new File(fileName);
synchronized (getCacheSyncObject(fileName)) {
try (OutputStream out = new FileOutputStream(f)) {
out.write("hi".getBytes());
}
}
return true;
}
});
}
private Object getCacheSyncObject(final String name) {
Object result = locks.get(name);
if (result == null) {
result = new Object();
Object prevLock;
if ((prevLock = locks.putIfAbsent(name, result)) != null) {
result = prevLock;
}
}
return result;
}
}
public class Test {
public static void main(String[] args) throws Exception {
Object obj = new Object();
Service<Object> service = new Service<>();
Future<Boolean> result1 = service.foo(obj, "filename");
service.exec.shutdown();
System.out.println("result1 = " + result1.get());
}
}
顺便说一句,即使你与hashCode()发生冲突,你也可以在文件中得到意想不到的输出,但是如果你没有锁定那个尝试
try (OutputStream out = new FileOutputStream(f)) {
out.write("hi".getBytes());
}
你不应该陷入僵局。我建议检查一下你的“// some actions”