What I want to do is to use Future
to open a thread to handle an async task that could be called frequently.
But in the async task
. I also call two Future
function to get the information from different data source.
I write a program to simulate this situation.
import scala.concurrent.{ExecutionContext, Future}
import scala.util.{Success, Failure}
import scala.util.control.Breaks
import ExecutionContext.Implicits.global
object AsyncTest {
def main(args: Array[String]) {
try {
println("Run...")
aSyncTask
} catch {
case e => e.printStackTrace()
}
Thread.sleep(999999)
}
//dataSource1
def getInfo1 : Future[String] = Future{
"A"
}
//dataSource2 let it wait 3 seconds...
def getInfo2 : Future[String] = Future{
Thread.sleep(3000)
"B"
}
def aSyncTask = Future{
getInfo1
getInfo2
var result1 : String = null
var result2 : String = null
getInfo1.onComplete{
case Success(value) => result1 = value
case Failure(t) => println {
"An error has occured: " + t.getMessage
}
}
getInfo2.onComplete{
case Success(value) => result2 = value
case Failure(t) => println {
"An error has occured: " + t.getMessage
}
}
/*I want to wait both Future function completed then
I can do some business logic */
Breaks.breakable{
while (true) {
if (result1 != null && result2 != null)
Breaks.break
}
}
println("----------------------")
println("result1:"+result1)
println("result2:"+result2)
println("----------------------")
}
}
After I compiled and executed this program, it output nothing. just wait.
Run...
I expected that I could see output :
Run...
----------------------
result1:A
result2:B
----------------------
So, I added some code in while
loop for debugging .
Breaks.breakable{
while (true) {
println(result1)
println(result2)
if (result1 != null && result2 != null)
Breaks.break
}
}
Then it output :
Run...
A
null
A
null
A
null
A
null
A
null
(After 3 seconds...)
A
B
----------------------
result1:A
result2:B
----------------------
What's going on?? I just add two println
to see the two variables.
Why the program could be executed as I expected when I just print it?