object FuturesCallbacks extends App {
import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.io.Source
def getUrlSpec(): Future[Seq[String]] = Future {
val f = Source.fromURL("http://www.w3.org/Addressing/URL/url-spec.txt")
try f.getLines.toList finally f.close()
}
val urlSpec: Future[Seq[String]] = getUrlSpec()
def find(lines: Seq[String], word: String) = lines.zipWithIndex collect {
case (line, n) if line.contains(word) => (n, line)
} mkString("\n")
urlSpec foreach {
lines => log(s"Found occurrences of 'telnet'\n${find(lines, "telnet")}\n")
}
urlSpec foreach {
lines => log(s"Found occurrences of 'password'\n${find(lines, "password")}\n")
}
log("callbacks installed, continuing with other work")
}
结果输出:
[info] Running org.learningconcurrency.ch4.FuturesCallbacks
run-main-0: callbacks installed, continuing with other work
[success] Total time: 4 s, completed 2016-3-20 9:21:34
> ForkJoinPool-1-worker-3: Found occurrences of 'telnet'
(207, telnet , rlogin and tn3270 )
(745, nntpaddress | prosperoaddress | telnetaddress
(806, telnetaddress t e l n e t : / / login )
(931, for a given protocol (for example, CR and LF characters for telnet
ForkJoinPool-1-worker-5: Found occurrences of 'password'
(107, servers). The password, is present, follows)
(109, the user name and optional password are)
(111, user of user name and passwords which are)
(222, User name and password)
(225, password for those systems which do not use the anonymous FTP)
(226, convention. The default, however, if no user or password is)
(234, is "anonymous" and the password the user's Internet-style mail)
(240, currently vary in their treatment of the anonymous password. )
(816, login [ user [ : password ] @ ] hostport )
(844, password alphanum2 [ password ] )
(938, The use of URLs containing passwords is clearly unwise. )