【发布时间】:2014-11-30 02:01:26
【问题描述】:
我有一些服务既从入站队列消费又产生到某个出站队列(由该服务创建的另一个线程接收消息并将它们“传输”到目的地)。
目前我使用两个普通的Threads,如下面的代码所示,但我知道通常你不应该再使用它们,而是使用更高级别的抽象,比如ExecutorService。
这对我来说有意义吗?更具体地说,我的意思是->
- 会减少代码吗?
- 让代码在失败时更加健壮?
- 允许更平滑的线程终止? (这在运行测试时很有帮助)
我在这里遗漏了什么重要的东西吗? (也许来自 java.util.concurrent 的一些其他类)
// called on service startup
private void init() {
// prepare everything here
startInboundWorkerThread();
startOutboundTransporterWorkerThread();
}
private void startInboundWorkerThread() {
InboundWorkerThread runnable = injector.getInstance(InboundWorkerThread.class);
inboundWorkerThread = new Thread(runnable, ownServiceIdentifier);
inboundWorkerThread.start();
}
// this is the Runnable for the InboundWorkerThread
// the runnable for the transporter thread looks almost the same
@Override
public void run() {
while (true) {
InboundMessage message = null;
TransactionStatus transaction = null;
try {
try {
transaction = txManager.getTransaction(new DefaultTransactionDefinition());
} catch (Exception ex) {
// logging
break;
}
// blocking consumer
message = repository.takeOrdered(template, MESSAGE_POLL_TIMEOUT_MILLIS);
if (message != null) {
handleMessage(message);
commitTransaction(message, transaction);
} else {
commitTransaction(transaction);
}
} catch (Exception e) {
// logging
rollback(transaction);
} catch (Throwable e) {
// logging
rollback(transaction);
throw e;
}
if (Thread.interrupted()) {
// logging
break;
}
}
// logging
}
// called when service is shutdown
// both inbound worker thread and transporter worker thread must be terminated
private void interruptAndJoinWorkerThread(final Thread workerThread) {
if (workerThread != null && workerThread.isAlive()) {
workerThread.interrupt();
try {
workerThread.join(TimeUnit.SECONDS.toMillis(1));
} catch (InterruptedException e) {
// logging
}
}
}
【问题讨论】:
标签: java multithreading concurrency blocking java.util.concurrent