Skip to content

Instantly share code, notes, and snippets.

@sirolf2009
Created April 12, 2017 14:09
Show Gist options
  • Save sirolf2009/a442fc2939d8ac8e88ae8b435258f8fc to your computer and use it in GitHub Desktop.
Save sirolf2009/a442fc2939d8ac8e88ae8b435258f8fc to your computer and use it in GitHub Desktop.
operator overloading is fun (inspired by ateji px)
import java.util.concurrent.Executors
import java.util.concurrent.ExecutorService
import java.util.stream.Stream
class Parallel {
static val executor = Executors.newFixedThreadPool(100)
def static void main(String[] args) {
val now = System.currentTimeMillis()
val parallelyExecuted2 = executor || (
+ [Thread.sleep(1000) return 42]
|| [Thread.sleep(1000) return 24]
|| [Thread.sleep(2000) return 24]
|| [Thread.sleep(2000) return 22]
|| [Thread.sleep(2000) return 22]
|| [Thread.sleep(2000) return 22]
|| [Thread.sleep(1000) return 24]
|| [Thread.sleep(2000) return 24]
|| [Thread.sleep(2000) return 22]
|| [Thread.sleep(2000) return 22]
|| [Thread.sleep(2000) return 22]
)
println(parallelyExecuted2.mapToInt[it].sum())
println(System.currentTimeMillis() - now)
}
def static <T> ||(ExecutorService executor, Operation<T> he) {
he.call(executor).get()
}
def static <T> ||((Object)=>T me, (Object)=>T he) {
operator_or(me as Operation<T>, he as Operation<T>)
}
def static <T> Operation<T> +((Object)=>T me) {
return me as Operation<T>
}
def static <T> ||(Operation<T> me, Operation<T> he) {
return new Operation<T>() {
override get(ExecutorService executor) {
val meF = me.call(executor)
val heF = he.call(executor)
val meR = meF.get()
val heR = heF.get()
Stream.concat(meR, heR)
}
override compute() {
throw new UnsupportedOperationException("TODO: auto-generated method stub")
}
}
}
interface Operation<T> {
def call(ExecutorService executor) {
executor.submit[get(executor)]
}
def Stream<T> get(ExecutorService executor) {
Stream.of(compute())
}
def T compute()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment