SORU
14 Kasım 2012, ÇARŞAMBA


Scala durumlarda kullanın.eşzamanlı.Söz mü?

SIP-14 okuyorum ve Future kavramı çok mantıklı ve anlaşılması kolay hale getirir. Ama Promise hakkında iki soru var:

  1. SIP Depending on the implementation, it may be the case that p.future == p diyor. Bu nasıl olabilir? Future Promise iki farklı tür değil mi?

  2. Promise kullanmalıyız? Örnek producer and consumer kod :

    import scala.concurrent.{ future, promise }
    val p = promise[T]
    val f = p.future
    
    val producer = future {
        val r = produceSomething()
        p success r
        continueDoingSomethingUnrelated()
    }
    val consumer = future {
        startDoingSomething()
        f onSuccess {
            case r => doSomethingWithResult()
        }
    }
    

okumak kolaydır ama gerçekten böyle yazmaya gerek var mı? Sadece Gelecek ve bu gibi Söz olmadan bunu uygulamaya çalıştım:

val f = future {
   produceSomething()
}

val producer = future {
   continueDoingSomethingUnrelated()
}

startDoingSomething()

val consumer = future {
  f onSuccess {
    case r => doSomethingWithResult()
  }
}

Bu verilen örnek arasındaki fark nedir ve bir Sözü gerekli kılan nedir?

CEVAP
14 Kasım 2012, ÇARŞAMBA


Söz ve Geleceği tamamlayıcı kavramlardır. Gelecek, iyi, ileride alınacağını olan bir değerdir ve bu olay gerçekleştiğinde ile bir şeyler yapabilirsin. Bu nedenle, bir hesaplama okumak veya bitiş noktası - arasında bir değer almak bir şeydir.

Bir Söz, benzetme, hesaplama yazılı tarafı. Hesaplama sonucu koyacağım nerede yeri olan ve bu sözü girmiştir sonucu okumak için kullanılacak bir geleceği olsun söz bir söz oluşturun. Bir Söz, ya da başarısızlık ya da başarı ile tamamlamak, ilgili Geleceğe bağlı olan tüm davranışları tetikleyebilir.

İlk sorunuza gelince, nasıl söz bir p p.future == p var olabilir. Tek maddelik bir tampon gibi bu-başlangıçta boş olan bir kap düşünün ve bunun üzerine içeriği olacak olan bir değeri sonsuza dek saklayabilirsiniz. Şimdi, sizin bakış açınızdan bağlı olarak, bir Söz ve bir Gelecek de bu. Tampon değeri yazma niyetinde olan biri için söz veriyorum. Bu değer tampon koymak için bekleyen birisi için bir gelecek olduğunu.

Eğer Söz here sürekli bir göz atacak olursak özellikle, Scala eşzamanlı API için, Söz arkadaşı nesneden yöntemlerinin nasıl uygulandığını görebilirsiniz :

object Promise {

  /** Creates a promise object which can be completed with a value.
   *  
   *  @tparam T       the type of the value in the promise
   *  @return         the newly created `Promise` object
   */
  def apply[T](): Promise[T] = new impl.Promise.DefaultPromise[T]()

  /** Creates an already completed Promise with the specified exception.
   *  
   *  @tparam T       the type of the value in the promise
   *  @return         the newly created `Promise` object
   */
  def failed[T](exception: Throwable): Promise[T] = new impl.Promise.KeptPromise[T](Failure(exception))

  /** Creates an already completed Promise with the specified result.
   *  
   *  @tparam T       the type of the value in the promise
   *  @return         the newly created `Promise` object
   */
  def successful[T](result: T): Promise[T] = new impl.Promise.KeptPromise[T](Success(result))

}

Şimdi, sözler, DefaultPromise ve KeptPromise bu uygulama here bulunabilir. İkisinin de tabanı, aynı ada sahip olan küçük özelliği genişletmek, ama farklı bir paket içinde yer almaktadır:

private[concurrent] trait Promise[T] extends scala.concurrent.Promise[T] with scala.concurrent.Future[T] {
  def future: this.type = this
}

p.future == p ile ne demek istediklerini görebilirsiniz.

DefaultPromise KeptPromise değeri çok yaratılmasından koymak ile bir tampon ise yukarıda bahsettiğim tampon.

Sizin örnek ile ilgili olarak, orada kullandığınız gelecekteki engellemek aslında perde arkasında bir söz oluşturur. here 22*: tanımına bakalım

def future[T](body: =>T)(implicit execctx: ExecutionContext): Future[T] = Future[T](body)

Yöntemleri zincirini izleyerek impl.Future bitiş:

private[concurrent] object Future {
  class PromiseCompletingRunnable[T](body: => T) extends Runnable {
    val promise = new Promise.DefaultPromise[T]()

    override def run() = {
      promise complete {
        try Success(body) catch { case NonFatal(e) => Failure(e) }
      }
    }
  }

  def apply[T](body: =>T)(implicit executor: ExecutionContext): scala.concurrent.Future[T] = {
    val runnable = new PromiseCompletingRunnable(body)
    executor.execute(runnable)
    runnable.promise.future
  }
}

Gördüğünüz gibi, yapımcı taşınız olsun sonuç bir söz dökülür alır.

DAHA SONRA DÜZENLEYİN:

Gerçek dünya ile ilgili: vaatler ile anlaşma olmaz Çoğu zaman doğrudan. Eğer zaman uyumsuz hesaplamaları gerçekleştiren bir kütüphane kullanacağız eğer sadece vadeli kütüphane yöntemleri tarafından döndürülen ile çalışacaksınız. Söz, bu durumda, kütüphane tarafından oluşturulur - bu yöntemlerden ne okuma sonu ile çalışıyoruz.

Ama eğer kendi zaman uyumsuz API uygulamak için ihtiyacınız varsa onlarla çalışmaya başlamanız gerekecek. Üstüne uyumsuz bir HTTP istemci uygulamak gerekir, sağlar, Netty farz et. Sonra kodunuzu bu gibi biraz görünüyor

    def makeHTTPCall(request: Request): Future[Response] = {
        val p = Promise[Response]
        registerOnCompleteCallback(buffer => {
            val response = makeResponse(buffer)
            p success response
        })
        p.future
    }

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • ☆ SUB4SUB CENTER! ☆ spam here

    ☆ SUB4SUB

    22 ŞUBAT 2010
  • michal lelkowski

    michal lelko

    9 Temmuz 2006
  • Phymec

    Phymec

    18 Temmuz 2009