我有一个正在处理内存中队列的托管对象(Dropwizard)。当发送关闭信号时,我需要处理队列的结束。当我在没有加入线程的情况下将关闭信号设置为true时,我可以看到我是否在我的测试中暂停了项目的处理。但是,当我加入线程时,似乎停止线程死,而不是等待run方法完成。
class LedgerProcessor constructor(
private val ledgerProcessorQueue: LedgerProcessorQueue,
private val paymentDao: PaymentDao) : Managed {
private lateinit var pollingThread: Thread
private val shuttingDown: AtomicBoolean = AtomicBoolean(false)
override fun start() {
log.info { "Started Processing ledger requests" }
pollingThread = object : Thread() {
override fun run() {
while (checkStatus()) {
val payment = ledgerProcessorQueue.next()
log.info { "Upserting payment ${payment.tokenId} status: ${payment.status}" }
paymentDao.upsert(payment)
}
}
}
pollingThread.start()
}
private fun checkStatus(): Boolean {
val isShuttingDown = shuttingDown.get()
val hasMore = ledgerProcessorQueue.hasNext()
log.info { "isShuttingDown: $isShuttingDown, hasMore: $hasMore - ${!isShuttingDown || hasMore}" }
return !isShuttingDown || hasMore
}
override fun stop() {
shuttingDown.set(true)
pollingThread.join() // this seems to stop the run in process
}
当pollingThread.join()存在时,此测试失败,但在没有连接时传递
@Test
fun whenStartedButStoppedBeforeAllProcessedThenAllPaymentsInQueueShouldBeProcessedBeforeEnd(){
val payment0 = aPayment()
val payment1 = aPayment()
val payment2 = aPayment()
ledgerQueue.add(payment0)
ledgerQueue.add(payment1)
ledgerQueue.add(payment2)
whenever(paymentDao.upsert(payment0)).then {
ledgerProcessor.stop()
}
ledgerProcessor.start()
//Thread.sleep(5000)
verify(paymentDao).upsert(payment0)
verify(paymentDao).upsert(payment1)
verify(paymentDao).upsert(payment2)
}
使用Thread.join测试日志:
INFO [12:02:44.734] [main] c.w.p.d.l.LedgerProcessor - Started
Processing ledger requests
INFO [12:02:44.738] [Thread-0] c.w.p.d.l.LedgerProcessor -
isShuttingDown: false, hasMore: true - true
INFO [12:02:44.739] [Thread-0] c.w.p.d.l.LedgerProcessor - Upserting
payment 61a20508-37e6-4347-a7d1-2538fda8c470 status: Processing
使用Thread.join关闭测试日志:
INFO [12:04:41.994] [main] c.w.p.d.l.LedgerProcessor - Started Processing ledger requests
INFO [12:04:41.999] [Thread-0] c.w.p.d.l.LedgerProcessor - isShuttingDown: false, hasMore: true - true
INFO [12:04:41.999] [Thread-0] c.w.p.d.l.LedgerProcessor - Upserting payment 5de161b7-3158-4ee4-a5d7-a690b3b500d6 status: Processing
INFO [12:04:42.004] [Thread-0] c.w.p.d.l.LedgerProcessor - isShuttingDown: true, hasMore: true - true
INFO [12:04:42.004] [Thread-0] c.w.p.d.l.LedgerProcessor - Upserting payment 741ab5ee-48af-426c-b167-97641286e796 status: Processing
INFO [12:04:42.004] [Thread-0] c.w.p.d.l.LedgerProcessor - isShuttingDown: true, hasMore: true - true
INFO [12:04:42.004] [Thread-0] c.w.p.d.l.LedgerProcessor - Upserting payment 79546c86-5d02-4bd7-91b8-c2e0c5c4eb5f status: Processing
INFO [12:04:42.004] [Thread-0] c.w.p.d.l.LedgerProcessor - isShuttingDown: true, hasMore: false - false