summaryrefslogtreecommitdiff
path: root/src/library/scala/concurrent/akka/Promise.scala
blob: 8ecffec2aa28deaf448cbe2ca7306cd6905a7f22 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/*                     __                                               *\
**     ________ ___   / /  ___     Scala API                            **
**    / __/ __// _ | / /  / _ |    (c) 2003-2011, LAMP/EPFL             **
**  __\ \/ /__/ __ |/ /__/ __ |    http://scala-lang.org/               **
** /____/\___/_/ |_/____/_/ | |                                         **
**                          |/                                          **
\*                                                                      */

package scala.concurrent.akka



import java.util.concurrent.TimeUnit.{ NANOSECONDS, MILLISECONDS }
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater
import scala.concurrent.{Awaitable, ExecutionContext, resolve, resolver, blocking, CanAwait, TimeoutException}
//import scala.util.continuations._
import scala.util.Duration
import scala.util.Try
import scala.util
import scala.annotation.tailrec
//import scala.concurrent.NonDeterministic


trait Promise[T] extends scala.concurrent.Promise[T] with Future[T] {
  
  def future = this
  
  def newPromise[S]: Promise[S] = executor promise
  
  // TODO refine answer and return types here from Any to type parameters
  // then move this up in the hierarchy
  /*
  final def <<(value: T): Future[T] @cps[Future[Any]] = shift {
    cont: (Future[T] => Future[Any]) =>
    cont(complete(Right(value)))
  }

  final def <<(other: Future[T]): Future[T] @cps[Future[Any]] = shift {
    cont: (Future[T] => Future[Any]) =>
    val p = executor.promise[Any]
    val thisPromise = this
    
    thisPromise completeWith other
    thisPromise onComplete { v =>
      try {
        p completeWith cont(thisPromise)
      } catch {
        case e => p complete resolver(e)
      }
    }
    
    p.future
  }
  */
  // TODO finish this once we introduce something like dataflow streams
  
  /*
  final def <<(stream: PromiseStreamOut[T]): Future[T] @cps[Future[Any]] = shift { cont: (Future[T] => Future[Any]) =>
    val fr = executor.promise[Any]
    val f = stream.dequeue(this)
    f.onComplete { _ =>
      try {
        fr completeWith cont(f)
      } catch {
        case e =>
          fr failure e
      }
    }
    fr
  }
  */
  
}


object Promise {
  
  def EmptyPending[T](): FState[T] = emptyPendingValue.asInstanceOf[FState[T]]
  
  /** Represents the internal state.
   */
  sealed trait FState[+T] { def value: Option[Try[T]] }
  
  case class Pending[T](listeners: List[Try[T] => Any] = Nil) extends FState[T] {
    def value: Option[Try[T]] = None
  }
  
  case class Success[T](value: Option[util.Success[T]] = None) extends FState[T] {
    def result: T = value.get.get
  }
  
  case class Failure[T](value: Option[util.Failure[T]] = None) extends FState[T] {
    def exception: Throwable = value.get.exception
  }
  
  private val emptyPendingValue = Pending[Nothing](Nil)
  
  /** Default promise implementation.
   */
  class DefaultPromise[T](implicit val executor: ExecutionContextImpl) extends AbstractPromise with Promise[T] {
  self =>
    
    updater.set(this, Promise.EmptyPending())
    
    protected final def tryAwait(atMost: Duration): Boolean = {
      @tailrec
      def awaitUnsafe(waitTimeNanos: Long): Boolean = {
        if (value.isEmpty && waitTimeNanos > 0) {
          val ms = NANOSECONDS.toMillis(waitTimeNanos)
          val ns = (waitTimeNanos % 1000000l).toInt // as per object.wait spec
          val start = System.nanoTime()
          try {
            synchronized {
              while (value.isEmpty) wait(ms, ns)
            }
          } catch {
            case e: InterruptedException =>
          }
          
          awaitUnsafe(waitTimeNanos - (System.nanoTime() - start))
        } else
          value.isDefined
      }
      
      executor.blocking(concurrent.body2awaitable(awaitUnsafe(dur2long(atMost))), Duration.fromNanos(0))
    }
    
    private def ready(atMost: Duration)(implicit permit: CanAwait): this.type =
      if (value.isDefined || tryAwait(atMost)) this
      else throw new TimeoutException("Futures timed out after [" + atMost.toMillis + "] milliseconds")
    
    def await(atMost: Duration)(implicit permit: CanAwait): T =
      ready(atMost).value.get match {
        case util.Failure(e)  => throw e
        case util.Success(r) => r
      }
    
    def value: Option[Try[T]] = getState.value
    
    @inline
    private[this] final def updater = AbstractPromise.updater.asInstanceOf[AtomicReferenceFieldUpdater[AbstractPromise, FState[T]]]
    
    @inline
    protected final def updateState(oldState: FState[T], newState: FState[T]): Boolean = updater.compareAndSet(this, oldState, newState)
    
    @inline
    protected final def getState: FState[T] = updater.get(this)
    
    def tryComplete(value: Try[T]): Boolean = {
      val callbacks: List[Try[T] => Any] = {
        try {
          @tailrec
          def tryComplete(v: Try[T]): List[Try[T] => Any] = {
            getState match {
              case cur @ Pending(listeners) =>
                if (updateState(cur, if (v.isFailure) Failure(Some(v.asInstanceOf[util.Failure[T]])) else Success(Some(v.asInstanceOf[util.Success[T]])))) listeners
                else tryComplete(v)
              case _ => null
            }
          }
          tryComplete(resolve(value))
        } finally {
          synchronized { notifyAll() } // notify any blockers from `tryAwait`
        }
      }
      
      callbacks match {
        case null             => false
        case cs if cs.isEmpty => true
        case cs               =>
          executor dispatchFuture {
            () => cs.foreach(f => notifyCompleted(f, value))
          }
          true
      }
    }
    
    def onComplete[U](func: Try[T] => U): this.type = {
      @tailrec // Returns whether the future has already been completed or not
      def tryAddCallback(): Boolean = {
        val cur = getState
        cur match {
          case _: Success[_] | _: Failure[_] => true
          case p: Pending[_] =>
            val pt = p.asInstanceOf[Pending[T]]
            if (updateState(pt, pt.copy(listeners = func :: pt.listeners))) false else tryAddCallback()
        }
      }
      
      if (tryAddCallback()) {
        val result = value.get
        executor dispatchFuture {
          () => notifyCompleted(func, result)
        }
      }
      
      this
    }
    
    private final def notifyCompleted(func: Try[T] => Any, result: Try[T]) {
      try {
        func(result)
      } catch {
        case e => executor.reportFailure(e)
      }
    }
  }
  
  /** An already completed Future is given its result at creation.
   *  
   *  Useful in Future-composition when a value to contribute is already available.
   */
  final class KeptPromise[T](suppliedValue: Try[T])(implicit val executor: ExecutionContextImpl) extends Promise[T] {
    val value = Some(resolve(suppliedValue))
    
    def tryComplete(value: Try[T]): Boolean = false
    
    def onComplete[U](func: Try[T] => U): this.type = {
      val completedAs = value.get
      executor dispatchFuture {
        () => func(completedAs)
      }
      this
    }
    
    private def ready(atMost: Duration)(implicit permit: CanAwait): this.type = this
    
    def await(atMost: Duration)(implicit permit: CanAwait): T = value.get match {
      case util.Failure(e)  => throw e
      case util.Success(r) => r
    }
  }
  
}