Reputation: 15
I have a class that has its own internal thread running over a queue of actions, it just loops all the time doing stuff. For that it reads a queue of notifications that tell it what action to do next. There is a notification to tell the class to stop all actions and kill itself. When another thread calls the notifyClose notification, its added to the queue and takes priority number 1. I want the method that adds the notification to return a Future.success when the other thread has processed the close notification.
The code run as follows:
def loop(): Future[Unit] = {
current = if(queue.contains(KILL)) disable() // <--- disable will set the state to Closed
else process() // <--- if queue is empty it will call loop(),
// if its not empty it will do de action and then call loop()
}
private def disable(): Future[Unit] = {
state = Closed
Future.unit
}
def close(): Future[Unit] = {
queue.add(KILL)
while (state != Closed) { /* Wait until state is NotAvailable */ }
Future.successful()
}
I want a better way to wait till the state changes to Closed in the close()
method. I fill that and empty loop is the worst idea ever.
The variable current holds the current Future being processed, maybe there is a way hooking my result to that Future? The thing is I don't know when disable()
method will actually start. Any help will be appreciated.
Thanks for taking the time of reading.
Upvotes: 1
Views: 194
Reputation: 48430
Try using Promise
as a kind of state, for example
def loop(): Future[Unit] = {
if(queue.contains(KILL)) Future.successful(disable.trySuccess())
else process()
}
private val disable = Promise[Unit]()
def close(): Future[Unit] = {
queue.add(KILL)
disable.future
}
This way Future
returned by close()
will complete only when loop()
actually invokes disable.trySuccess
.
Upvotes: 1