有没有办法取消通过copyIn()
在单独的线程中调用方法启动的复制过程?
比如说,我有一个我需要从中复制的 csv 文件列表,以获得最大的数据库服务器功能。因此,我为 n 个文件创建了 n 个线程连接,但是如果例如选择了错误的文件,我找不到中止单个操作的方法。
杀死线程不起作用 - COPY 只是继续运行。
该类FutureTask<>
用于创建线程,因此有一个它们的列表 - 每个 csv 一个。
task.cancel(true)
就服务器上的复制过程而言,调用没有任何作用。只能System.exit()
用火杀死它。
有任何想法吗?
我的一些代码:
Uploader.java implements Callable
public static long uploadFile(final File file, final String tableName) {
long status = 0;
try {
CopyManager copyManager =
new CopyManager((BaseConnection) new DataSource().connect());
FileReader reader = new FileReader(file);
status = copyManager.copyIn(sql, reader);
} catch (SQLException | IOException e) {
...
}
return status;
}
@Override
public Long call() throws Exception {
return uploadFile(file, tableName);
}
Upload files method body
for (File file : files) {
FutureTask<Long> ftask =
new FutureTask<>(
new Uploader(defaultTableName, file)
);
tasks.add(ftask);
execService.execute(ftask);
}
解决了:
找到了解决方案,但是它需要对代码进行一些更改。
Upload files method body
现在看起来像这样
for (File file : files) {
Uploader uploader = new Uploader(defaultTableName, file);
uploaders.add(uploader);
Future<Long> f = execService.submit(uploader);
//save the Future to get the copy result when finished
}
有了这个,我们可以很容易地调用 someUploader
的方法,可以关闭数据库连接并正确处理异常。它将停止在服务器上复制。
我承认该解决方案可能不是最优雅的解决方案,但是它可以工作,运行速度很快,并且不需要太多代码。