Created
January 11, 2018 23:25
-
-
Save alexandru/f30b0c8b3920e7d8a8a6ecf018c0aaec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io._ | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.util.control.NonFatal | |
import scala.concurrent.duration._ | |
import scalaz._ | |
import scalaz.effect._ | |
object Sample extends SafeApp { | |
def run(args: List[String]): IO[Unit] = | |
for { | |
_ <- generate | |
f <- acquire.bracket(release)(readFile).fork | |
_ <- IO.unit.delay(500.millis) | |
_ <- f.interrupt(new RuntimeException("Boo")) | |
_ <- IO.unit.delay(1000.millis) | |
_ <- f.join | |
} yield () | |
def readFile(in: BufferedReader): IO[String] = | |
IO.async { cb => | |
global.execute(new Runnable { | |
def run() = { | |
try { | |
System.out.println("Started!") | |
Thread.sleep(1000) | |
val buffer = new StringBuffer() | |
var continue = true | |
while (continue) { | |
val line = in.readLine() | |
continue = line != null | |
if (continue) buffer.append(line) | |
} | |
cb(\/-(buffer.toString)) | |
} catch { | |
case NonFatal(ex) => | |
System.err.println(s"Thrown! ${ex}") | |
cb(-\/(ex)) | |
} | |
} | |
}) | |
} | |
def release(in: BufferedReader): IO[Unit] = | |
IO.sync(in.close()) | |
val acquire: IO[BufferedReader] = | |
IO.sync(new BufferedReader(new InputStreamReader(new FileInputStream("/tmp/test"), "utf-8"))) | |
val generate: IO[Unit] = | |
IO.sync { | |
val out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("/tmp/test"), "utf-8")) | |
for (_ <- 0 until 100) out.write("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n") | |
out.close() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment