org.springframework.scheduling.commonj.WorkManagerTaskExecutor
我有一个使用Spring 创建并在 Websphere Application Server 8 中运行的长时间运行的线程。
问题是即使应用程序已停止,该线程仍会继续运行。该线程也需要停止,但没有发生。我什至试图用它 Thread.currentThread().isInterrupted()
来检查当前线程是否被中断但它总是返回false
。因此,无法通过我的代码知道线程是否应该继续运行或停止。
这是我对 WorkManagerTaskExecutor 的 spring 配置:
<bean id="taskExecutor" class="org.springframework.scheduling.commonj.WorkManagerTaskExecutor">
<property name="workManagerName" value="wm/default" />
</bean>
线程是这样执行的:
Thread t = new EmailReaderThread(email);
workManagerTaskExecutor.execute(t);
- 我错过了什么?
- 我该怎么做才能在应用程序停止时应用程序的线程(由应用程序生成的线程)也停止?
我认为这不被视为非托管线程,因为我正在使用适当的WorkManager注册线程,容器将其作为 JNDI 公开的资源。
更新:这是创建线程的代码。
@Service
@Transactional
public class SmsServiceHypermedia implements SmsService {
@Autowired
private WorkManagerTaskExecutor workManagerTaskExecutor;
public SmsServiceHypermedia() {
createEmailReaderThread();
}
private void createEmailReaderThread() {
log.debug("Generating Email Reader Threads...");
Email email = getDefaultEmail(); //obtain the default Email object, not important for the problem.
EmailReaderThread r = new EmailReaderThread(email);
workManagerTaskExecutor.execute(r);
}
private class EmailReaderThread extends Thread {
private Email email;
private Session session;
public EmailReaderThread(Email email) {
this.email = email;
}
@Override
public void run() {
readEmails();
}
public void readEmails() {
final long delay = 30 * 1000; //delay between message poll.
log.debug("Starting to read emails for email: " + email.getAddress());
while(!Thread.currentThread().isInterrupted()) {
try {
log.debug("Current session: " + session);
Store store = session.getStore();
log.debug("Connecting using session: " + session);
store.connect();
Folder inbox = store.getFolder("INBOX");
inbox.open(Folder.READ_WRITE);
javax.mail.Message[] messages = inbox.search(
new FlagTerm(new Flags(Flags.Flag.SEEN), false));
for (javax.mail.Message message : messages) {
//Do something with the message
}
inbox.close(true);
store.close();
block(delay);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
//I know this could be implemented by calling Thread.sleep() is just that I ran out of options so I also tried it this way.
private void block(long millis) {
final long endTime = System.currentTimeMillis() + millis;
log.debug("Blocking for this amount of time: " + millis + " ms");
while (System.currentTimeMillis() < endTime) {
}
log.debug("End of blocking.");
}
}
}