つまらないシステム(1) Scala の Future と ExecutionContext

D5c7b3659d50696454ca0e6dceaf1f53?s=47 mashijp
November 13, 2015

つまらないシステム(1) Scala の Future と ExecutionContext

Scalaで詰まらないシステムを作るために覚えていてほしいこと。

D5c7b3659d50696454ca0e6dceaf1f53?s=128

mashijp

November 13, 2015
Tweet

Transcript

  1. ͭ·Βͳ͍γεςϜ(1) - FutureͱExecutionContext - mashi

  2. ૝ఆͯ͠Δಡऀ •  ৽ଔͷΈͳ͞Μ •  Scalaॻ͘ͷָ͕͘͠ͳ͖ͬͯͨ •  Future͍͢͝ʂָ͍͠ʂ

  3. Future[T] ͱ͸ •  ͍͔ͭT͕ฦͬͯ͘Δ •  ͍ͭʁ – Θ͔Μͳ͍

  4. Future ͷ࡞Γํ •  Future.apply Λ࢖͏ def apply(f: => T)(implicit ec:

    ExecutionContext): T •  f Ͱ౉ͨؔ͠਺͸ec: ExecutionContext ʹ Α࣮ͬͯߦ͞ΕΔ – ͜ͷ f Λࠓ͔Β Runnable ͱݺͼ·͢ •  ͍࣮ͭߦ͞ΕΔͷ͔ – Θ͔Μͳ͍ (ExecutionContext ͕ܾΊΔ) ৄ͘͠͸http://mashi.hatenablog.com/entry/2014/11/24/010417 Scala ExecutionContextͬͯԿ/ Future͸εϨου্ཱͪ͛͡Όͳ͍Α
  5. ExecutionContext ͷҰൠతͳ࣮૷ Thread 1 Thread 2 Thread 3 Thread 4

    •  ༩͑ͨ Runnable Λۭ͍ͯΔεϨουͰ͍ ͍ײ͡ʹ࣮ߦ͢Δ Runnable 1 Runnable 2 Runnable 3 Runnable n ۭ͖࣍ୈ࣮ߦ͢Δ
  6. ৗʹొ৔͢ΔExecutionContext •  Future Λ͍͘͡Δʹ͸ৗʹ ExecutionContext ΛٻΊΒΕΔ •  ීஈॻ͍͍ͯΔίʔυ val dbData:

    Future[A] = getFromDB() val result: Future[B] = dbData.map({ e => convertToB(e) })
  7. ৗʹొ৔͢ΔExecutionContext •  ීஈԿؾͳ͘ॻ͍͍ͯΔίʔυ΋࣮͸ implicit ͰExecutionContextΛ౉͍ͯ͠Δ •  mapʹ౉ͨؔ͠਺Λ࣮ߦ͢Δ ExecutionContext Λ҉໧తʹࢦఆ͍ͯ͠Δ val

    dbData: Future[A] = getFromDB() val result: Future[B] = dbData.map({ e => convertToB(e) })(ec: ExecutionContext)
  8. ExecutionContext ͸༻్ผʹఆٛ͢΂͠ •  ྫ) memcached ͱ MySQL Ͱ෼͚Δ •  ྫ)

    MySQL ͷσʔλϕʔε1 ͱ 2 Ͱ෼͚Δ •  ྫ) MySQL ͷ master ͱ slaveͰ෼͚Δ •  ͳ͔ͥʁ
  9. ExecutionContext ͸٧·Δ •  ϒϩοΩϯά͢Δ΋ͷΛ࢖͏ͱ٧·Δ – ྫ͑͹ MySQL ͷૢ࡞͸٧·Δ ˞͜͜Ͱ͸লུ͢Δ͕ɺscala-redis-nb ͷΑ͏ͳϊϯϒϩοΩϯάͳ࣮૷ Λ࢖͏ͱجຊతʹ٧·Βͳ͍

  10. 1つのExecutionContextΛ࢖͍·Θͨ͠৔߹ •  ྫ͑͹MySQL ͱmemcached͕৐͍ͬͯΔγεςϜ •  MySQLͷԠ౴͕஗͘ͳΔͱશ෦ॏ͘ͳΔ Thread 1 Thread 2

    Thread 3 Thread 4 MySQLૢ࡞ MySQLૢ࡞ MySQLૢ࡞ 1ͭͷExecutionContext Λྲྀ༻ memcached ૢ࡞ MySQL ૢ࡞ MySQL ૢ࡞ MySQL ૢ࡞ MySQL ૢ࡞ ͦͷଞͷ ૢ࡞ ؔ܎ͳ͍ૢ࡞·Ͱಉ͡Ωϡʔʹ٧·ΕΔͷͰ memcached ͷૢ࡞΋ॏ͘ͳΔ MySQL͔Β ͷԠ౴଴ͪ…
  11. ExecutionContextΛ༻్ผʹ෼͚ͨ৔߹ •  ͋ΔՕॴ͕٧·ͬͯ΋ଞʹӨڹ͠ͳ͘ͳΔ Thread 1 Thread 2 MySQLૢ࡞ MySQLૢ࡞ MySQLૢ࡞

    memcached ૢ࡞ MySQL ૢ࡞ MySQL ૢ࡞ ͦͷଞͷ ૢ࡞ Thread 1 Thread 2 Thread 1 Thread 2 ͬͪ͜ʹ͸Өڹ͠ͳ͍ MySQL͚͕ͩ٧·Δ
  12. ·ͱΊ •  ීஈؾʹ͍ͯ͠ͳͯ͘΋implicitͰ҉໧తʹ ExecutionContextΛ౉͍ͯ͠Δ͜ͱ͕͋Δ –  'VUVSFͷNBQ΍qBU.BQΛ͢Δͱඞͣ౉ͯ͠ ͍Δ •  map ΍flatMap

    Λ͢Δͱ͖ʹࠓ͜͜Ͱ౉͍ͯ͠ ΔExecutionContextΛ٧·ΒͤΔڪΕ͕ͳ͍͔Λ ৗʹҙࣝ͢΂͠ –  ࣮૷ɾϨϏϡʔ࣌ʹΑ͘ݟ·͠ΐ͏ •  ͪΌΜͱ࣮૷͢Ε͹ྫ͑͹ʮmemcached ͕յ Εͯ΋memcached ʹ͸ؔ܎ͳ͍ͱ͜Ζʹ͸Ұ ੾Өڹ͕Ͱͳ͍ʯΑ͏ͳϑΣʔϧιϑτͳγε ςϜΛ࡞Γ্͛ΒΕΔ