복붙노트

[SCALA] 스칼라의 미래와 약속 취소

SCALA

스칼라의 미래와 약속 취소

이 내 앞의 질문에 대한 후속이다.

내가 인터럽트 차단 호출을 실행하는 작업을, 있다고 가정합시다. 나는 미래로 실행하기 좋아하고 약속의 고장 방법을 취소합니다.

나는 다음과 같이 작업을 취소하고 싶습니다 :

그것은 의미가 있습니까? 그것은 스칼라에서 구현 할 수 있습니까? 그러한 구현의 사례가 있습니까?

해결법

  1. ==============================

    1.scala.concurrent.Future는 읽기 전용, 그래서 한 독자 수없는 다른 독자 꼬이지.

    scala.concurrent.Future는 읽기 전용, 그래서 한 독자 수없는 다른 독자 꼬이지.

    당신이 다음과 같이 당신이 원하는 것을 구현할 수있을 것 같아 :

    def cancellableFuture[T](fun: Future[T] => T)(implicit ex: ExecutionContext): (Future[T], () => Boolean) = {
      val p = Promise[T]()
      val f = p.future
      p tryCompleteWith Future(fun(f))
      (f, () => p.tryFailure(new CancellationException))
    }
    
    val (f, cancel) = cancellableFuture( future => {
      while(!future.isCompleted) continueCalculation // isCompleted acts as our interrupted-flag
    
      result  // when we're done, return some result
    })
    
    val wasCancelled = cancel() // cancels the Future (sets its result to be a CancellationException conditionally)
    
  2. ==============================

    2.여기에 자신의 코멘트를 빅터의 코드의 interruptable 버전 (내가 잘못 해석하면 빅터가, 저를 수정하시기 바랍니다).

    여기에 자신의 코멘트를 빅터의 코드의 interruptable 버전 (내가 잘못 해석하면 빅터가, 저를 수정하시기 바랍니다).

    object CancellableFuture extends App {
    
      def interruptableFuture[T](fun: () => T)(implicit ex: ExecutionContext): (Future[T], () => Boolean) = {
        val p = Promise[T]()
        val f = p.future
        val aref = new AtomicReference[Thread](null)
        p tryCompleteWith Future {
          val thread = Thread.currentThread
          aref.synchronized { aref.set(thread) }
          try fun() finally {
            val wasInterrupted = (aref.synchronized { aref getAndSet null }) ne thread
            //Deal with interrupted flag of this thread in desired
          }
        }
    
        (f, () => {
          aref.synchronized { Option(aref getAndSet null) foreach { _.interrupt() } }
          p.tryFailure(new CancellationException)
        })
      }
    
      val (f, cancel) = interruptableFuture[Int] { () =>
        val latch = new CountDownLatch(1)
    
        latch.await(5, TimeUnit.SECONDS)    // Blocks for 5 sec, is interruptable
        println("latch timed out")
    
        42  // Completed
      }
    
      f.onFailure { case ex => println(ex.getClass) }
      f.onSuccess { case i => println(i) }
    
      Thread.sleep(6000)   // Set to less than 5000 to cancel
    
      val wasCancelled = cancel()
    
      println("wasCancelled: " + wasCancelled)
    }
    

    Thread.sleep를 (6000)와 함께 출력된다 :

    latch timed out
    42
    wasCancelled: false
    

    Thread.sleep를 (1000)와 함께 출력된다 :

    wasCancelled: true
    class java.util.concurrent.CancellationException
    
  3. ==============================

    3.트위터의 선물은 취소를 구현합니다. 여기 보라 :

    트위터의 선물은 취소를 구현합니다. 여기 보라 :

    https://github.com/twitter/util/blob/master/util-core/src/main/scala/com/twitter/util/Future.scala

    563 개 프로그램이 책임이있는 추상 메소드 라인. 스칼라의 미래는 현재 취소를 지원하지 않습니다.

  4. ==============================

    4.당신은 Monix 라이브러리 대신 미래를 사용할 수 있습니다

    당신은 Monix 라이브러리 대신 미래를 사용할 수 있습니다

    https://monix.io

  5. from https://stackoverflow.com/questions/16020964/cancellation-with-future-and-promise-in-scala by cc-by-sa and MIT license