嗨,我是用 java 来称呼“你”的,所以需要一些关于此代码块的帮助 我正在从 pl/sql 调用 java 代码
XXX.execute(java.lang.String, java.lang.String, java.lang.String) return java.lang.String
public class XXX {
public static String execute(String executable, String workingdir, String input) {
String line = "";
try {
Command command = new Command(input, executable, "-a", workingdir + "ndrg.gg");
command.execute();
line = command.getErrorOutput();
if (line.contains("1 records processed")) {
line = command.getOutput();
if (line.length() > input.length() + 1) {
line = command.getOutput().substring(input.length() + 1);
} else {
line = "ERROR:1- " + line;
}
} else {
line = "ERROR: " + line;
}
} catch (Exception ex) {
ex.printStackTrace();
line = "ERROR: " + ex.getMessage();
};
return line;
}
}
我需要检查 command.execute 是否在 10 秒内没有响应,然后 XXX.execute 返回一个错误,我读到了有关 ExecutorService 和 Future 的内容,但是...:(
最佳答案
尝试这样做:
- 实现Callable接口(interface)并将代码放入call方法
- 将您的任务提交至ExecutorService并获取 Future 对象的实例
- 调用 get在 Future 对象上。该方法将阻塞直到返回响应,否则将抛出 TimeoutException。
解决方案:
public static String execute(final String executable,
final String workingdir, final String input) {
ExecutorService executor = Executors.newCachedThreadPool();
Callable<String> task = new Callable<String>() {
public String call() throws Exception {
// Execution in another thread.
String line = "";
try {
Command command = new Command(input, executable, "-a",
workingdir + "ndrg.gg");
command.execute();
line = command.getErrorOutput();
if (line.contains("1 records processed")) {
line = command.getOutput();
if (line.length() > input.length() + 1) {
line = command.getOutput().substring(
input.length() + 1);
} else {
line = "ERROR:1- " + line;
}
} else {
line = "ERROR: " + line;
}
} catch (Exception ex) {
ex.printStackTrace();
line = "ERROR: " + ex.getMessage();
}
return line;
}
};
Future<String> future = executor.submit(task);
String response = "";
try {
// Wait 10s for response.
response = future.get(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
// Write something meaningful
response = "InterruptedException"
} catch (ExecutionException e) {
e.printStackTrace();
// Write something meaningful
response = "ExecutionException"
} catch (TimeoutException e) {
e.printStackTrace();
// Do something if response is not ready within 10s.
response = "TimeoutException"
}
return response;
}
关于java - 如何使用executor和future,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20884891/