Skip to content

Instantly share code, notes, and snippets.

@k33g
Last active August 29, 2015 13:56
Show Gist options
  • Select an option

  • Save k33g/9327906 to your computer and use it in GitHub Desktop.

Select an option

Save k33g/9327906 to your computer and use it in GitHub Desktop.
futures.right.way.i.hope
module m33ki.hopes
import gololang.Async
import java.util.concurrent.TimeUnit
import java.util.concurrent.Executors
import java.util.concurrent.Semaphore
# Properties
struct hopeStructure = {
promise
, task
, executor
}
# Methods
augment m33ki.hopes.types.hopeStructure {
function todo = |this, task2run| { # this is a setter
this: task(task2run)
return this
}
function done = |this, callbackWhenDone| { # this is a setter
this: promise(): future(): onSet(callbackWhenDone)
return this
}
function go = |this, value| {
this: executor(): submit({
this: promise(): set(this: task()(value))
})
return this
}
}
# Constructor
function Hope = |executor| {
return hopeStructure(promise(), null, executor)
}
# utility
struct vo = { value }
augment m33ki.hopes.types.vo {
function multiply = |this, n| -> this: value(this: value()*n)
}
function main = |args| {
let executor = Executors.newCachedThreadPool()
let hope1 = Hope(executor)
: todo(|x| {
let v = vo(1)
x: times(|index|{
println("from hope1 : " + index)
v: multiply(index+1)
java.lang.Thread.sleep(500_L)
})
return v: value()
})
: done(|x|->println("result of hope1 : " + x))
: go(5)
let hope2 = Hope(executor)
: todo(|x| {
let v = vo(1)
x: times(|index|{
println("from hope2 : " + index)
v: multiply(index+1)
java.lang.Thread.sleep(500_L)
})
println(v: value())
return v: value()
})
: done(|x|->println("result of hope2 : " + x))
: go(6)
executor: shutdown()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment