Bạn có thể thực hiện các công cụ qua các phương thức JdbcTemplate
cho phép bạn chuyển vào một số PreparedStatementCreator
. Bạn luôn có thể sử dụng điều này để chặn các lời gọi (có thể sử dụng một số Proxy
) gây ra một số cancel
xảy ra trên một sợi riêng biệt bởi một số cond
trở thành true
.
public Results respondToUseRequest(Request req) {
final AtomicBoolean cond = new AtomicBoolean(false);
requestRegister.put(req, cond);
return jdbcTemplate.query(new PreparedStatementCreator() {
public PreparedStatement createPreparedStatement(Connection conn) {
PreparedStatement stmt = conn.prepareStatement();
return proxyPreparedStatement(stmt, cond);
}
},
new ResultSetExtractor() { ... });
}
canceller
có thể tự hủy khi hoàn tất thành công; ví dụ
private final static ScheduledExecutorService scheduler =
Executors.newSingleThreadedScheduledExecutor();
PreparedStatement proxyPreparedStatement(final PreparedStatement s, AtomicBoolean cond) {
//InvocationHandler delegates invocations to the underlying statement
//but intercepts a query
InvocationHandler h = new InvocationHandler() {
public Object invoke(Object proxy, Method m, Object[] args) {
if (m.getName().equals("executeQuery") {
Runnable cancel = new Runnable() {
public void run() {
try {
synchronized (cond) {
while (!cond.get()) cond.wait();
s.cancel();
}
} catch (InterruptedException e) { }
}
}
Future<?> f = scheduler.submit(cancel);
try {
return m.invoke(s, args);
} finally {
//cancel the canceller upon succesful completion
if (!f.isDone()) f.cancel(true); //will cause interrupt
}
}
else {
return m.invoke(s, args);
}
}
}
return (PreparedStatement) Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class[]{PreparedStatement.class},
h);
Vì vậy, bây giờ là mã được đáp ứng để hủy của người dùng sẽ trông như thế:
cond.set(true);
synchronized (cond) { cond.notifyAll(); }
Nguồn
2009-06-28 12:17:49
Ví dụ thú vị và kỳ lạ, không hoàn toàn chắc chắn về cách có thể áp dụng cho sự cố trong tầm tay. Rõ ràng là tự động hủy 10 giây sẽ cần thay thế bằng thứ gì đó được kích hoạt bên ngoài. – skaffman
Tại sao nó phải được kích hoạt bên ngoài? OP đã không đề cập đến bất cứ điều gì về nó, nói, người dùng định nghĩa –
OP ở đây: thực sự, tôi muốn hủy bỏ được kích hoạt để đáp ứng với hành động của người dùng. –