Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Future

Fda899b3499ba4d6b2dbc763b3923759?s=47 s_edward
January 24, 2019

 Future

Fda899b3499ba4d6b2dbc763b3923759?s=128

s_edward

January 24, 2019
Tweet

Transcript

  1. 'VUVSF 4IJHFLJ4IPKJ

  2. r4DBMBεέʔϥϒϧϓϩάϥϛϯά lεϨουɺϩοΫɺϞχλʔͳͲ͸ɺσουϩοΫ ͱڝ߹ͷ஍ཕݪͰ͋Δz

  3. +BWB'VUVSF w +BWB͔Β͋Δɺ'VUVSF͸஋ΛऔΓग़͢ͱ͖ɺඇಉظ ܭࢉͷ݁ՌΛHFUϝιουͰऔಘ͢Δɻ͜ͷͱ͖ݺͼग़͠ ͍ͯΔεϨου͸ϒϩοΫ͞ΕΔɻܭࢉ݁ՌΛ࢖ͬͯ͞Β ʹܭࢉΛਐΊΔͨΊʹ͸ɺ׬ྃΛ଴ͭඞཁ͕͋Δɻ
 "844%,GPS+BWBܥͷ"TZOD͸͜ͷ'VUVSF͕ ࢖ΘΕ͍ͯΔɻ def process(jf:

    java.util.concurrent.Future[Int]): Int = { jf.get()
  4. $PNQMFUBCMF'VUVSF w +BWBͰಋೖ͞Εͨ৽͍͠'VUVSFɻ UIFO"QQMZ 'VODUJPO UIFO"DDFQU $POTVNFS ͳͲΛ ࢖ͬͯɺϒϩοΫ͞ΕΔ͜ͱͳ͘ɺNPOBEJDʹॲཧ͕ॻ ͚ΔΑ͏ʹͳͬͨɻ


    "844%,GPS+BWBͷ"TZODͰ͸͜Ε͕࢖ΘΕΔɻ def process(cf: CompletableFuture[Int]) = { cf.thenApply(x => x * 2) .thenAccept(x => println(x)) }
  5. 4DBMBͷ'VUVSF w 4DBMBͷ'VUVSF͸$PNQMFUBCMF'VUVSFಉ༷ʹϒϩοΫ ͞Εͳ͍ɻ def process(sf: scala.concurrent.Future[Int]) = { sf.map(x

    => x * 2) .map(x => x.toString) .foreach(str => println(str)) }
  6. $PNQMFUBCMF'VUVSF4DBMB'VUVSF w PSHTDBMBMBOHNPEVMFTTDBMBKBWBDPNQBUΛ࢖͏͜ ͱͰɺUP+BWB UP4DBMBͰ $PNQMFUBCMF'VUVSF $PNQMFUBCMF4UBHF ͱ'VUVSFΛ ૬ޓʹม׵͢Δ͜ͱ͕Ͱ͖Δ def

    convert[T](cf: CompletableFuture[T]): scala.concurrent.Future[T] = cf.toScala def convert[T](cf: scala.concurrent.Future[T]): CompletionStage[T] = cf.toJava
  7. ࢭ·Βͳ͍

  8. w εϨου͕͍͖͚ͭͮΔ object Examples extends App { val es =

    Executors.newCachedThreadPool() implicit val ec = ExecutionContext.fromExecutorService(es) val future = scala.concurrent.Future { Thread.sleep(5000) println("running") () } println("end") future.onComplete(x => x.fold(ex => ex.printStackTrace(), _ => println("success"))) }
  9. object Examples extends App { val es = Executors.newCachedThreadPool() implicit

    val ec = ExecutionContext.fromExecutorService(es) val future = scala.concurrent.Future { Thread.sleep(5000) println("running") () } println("end") future.onComplete(_ => es.shutdown()) }
  10. ϑϦʔζ

  11. w &YFDVUJPO$POUFYU*NQMJDJUTHMPCBM΍"LLBͷEFGBVMU EJTQBUDIFS౳͸ɺ'PSL+PJO1PPM͕࢖༻͞ΕΔɻ w 'PSL+PJO1PPM͸ଞͷछྨͷ&YFDVUPS4FSWJDFͱҟͳΓ XPSLTUFBMJOHΛ࢖༻͢Δɻ w ϒϩοΩϯάॲཧ౳͕͋Δͱɺ଴ػதʹଞͷλεΫͷͨΊ ʹεϨουΛ࢖༻͢Δ͜ͱ͕Ͱ͖ͳ͘ͳΔͨΊɺσου ϩοΫΛى͜͢͜ͱ͕͋Δɻ

  12. w ϒϩοΩϯά*0౳͚ͩͰͳ࣍͘ͷΑ͏ͳίʔυ΋ϒϩοΫ ͕ൃੜ͢Δ def process(jf: java.util.concurrent.Future[Int]): Int = { jf.get()

    Thread.sleep(5000)
  13. 5ISFBE 5ISFBE

  14. w 'PSL+PJO1PPMͷεϨου͕͔ͭ͠ͳ͍৔߹ɺԼͷίʔ υ͸ɺKGΛ࣮ߦ͢ΔͨΊͷεϨουΛӬԕʹ଴ͭ͜ͱʹ ͳͬͯ͠·͏ val A = scala.concurrent.Future { val

    jf: java.util.concurrent.Future[Int] = ... jf.get() } val B = scala.concurrent.Future { while (true) { Thread.sleep(500) } } " # 5ISFBE 5ISFBE
  15. r4DBMBεέʔϥϒϧϓϩάϥϛϯά lʮϑϡʔνϟʔۭؒʯʹೖͬͨΒɺͰ͖ΔݶΓϑʔ νϟʔۭؒʹ͍ଓ͚ΔΑ͏ʹ͢΂͖ͩz ·ͱΊ

  16. w "LLB΍3FBDUJWF4USFBNTΛ࢖͏৔߹ʹ͸ɺϒϩοΩϯ ά͠ͳ͍Α͏ʹ͠·͠ΐ͏ w 'VUVSFΛ࢖͏৔߹͸ɺ+BWBͷ$PNQMFUBCMF'VUVSF΍ 4DBMBͷ'VUVSFΛ࢖͍·͠ΐ͏ w "844%,GPS+BWB͸ɺ$PNQMFUBCMF'VUVSFΛฦ͢Α ͏ͳɺ4DBMBͷ'VUVSFʹม׵͢Δ͜ͱ͕Մೳͳ"1*Λ࢖͍ ·͠ΐ͏

    w ϒϩοΩϯά͕ඞཁͳ৔߹͸ɺ'PSL+PJO1PPMͰ͸ͳ͘ɺ 'JYFE5ISFBE1PPM౳ΛׂΓ౰ͯ·͠ΐ͏