Skip to content

Add answer to exercise 8 chapter 3 #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Dec 14, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions src/main/scala/org/learningconcurrency/exercises/ch3/ex8.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
package org.learningconcurrency
package exercises
package ch3

import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.util.regex.Pattern

import scala.sys.process._

/**
* Implement a method spawn that, given a block of Scala code, starts a new JVM process and runs the specified block in the new process:
* def spawn[T](block: =>T): T = ???
* Once the block returns a value, the spawn method should return the value from the child process.
* If the block throws an exception, the spawn method should throw the same exception.
*/
object Ex8 extends App {

// This method's preconditions are the following:
// - In case of executing in sbt, set `fork` setting to `true` (set fork := true ).
//
// If passed block which contains `System.exit`, this method throws `SecurityException`.
def spawn[T](block: => T): T = {
val className = Ex8_EvaluationApp.getClass().getName().split((Pattern.quote("$")))(0)
val tmp = File.createTempFile("concurrent-programming-in-scala", null)
tmp.deleteOnExit()

val out = new ObjectOutputStream(new FileOutputStream(tmp))
try {
out.writeObject(() => block)
} finally {
out.close()
}

val ret = Process(s"java -cp ${System.getProperty("java.class.path")} $className ${tmp.getCanonicalPath}").!
if (ret != 0)
throw new RuntimeException("fails to evaluate block in a new JVM process")

val in = new ObjectInputStream(new FileInputStream(tmp))
try {
in.readObject() match {
case e: Throwable => throw e
case x => x.asInstanceOf[T]
}
} finally {
in.close()
tmp.delete()
}
}

val s1 = spawn({
1 + 1
})
assert(s1 == 2)

try {
spawn({
"test".toInt
})
} catch {
case e: NumberFormatException =>
case _: Throwable => assert(false)
}

try {
spawn({
System.exit(0)
})
} catch {
case e: SecurityException =>
case _: Throwable => assert(false)
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package org.learningconcurrency
package exercises
package ch3

import java.io.FileInputStream
import java.io.FileOutputStream
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.security.Permission

// This application receives the file path in which the serialized `Function0` object has been written.
// Then, it reads and evaluates serialized `Function0` object, finally overwrites its result to the same file.
object Ex8_EvaluationApp extends App {
System.setSecurityManager(new SecurityManager() {
// allows access to file.
override def checkPermission(perm: Permission): Unit = {}
// detects `System.exit` in order not to be halted by the caller.
override def checkExit(status: Int): Unit = {
throw new SecurityException("not allowed to pass a block which contains System.exit(int) !")
}
});

val path = args(0)

val in = new ObjectInputStream(new FileInputStream(path))
try {
val f0 = in.readObject().asInstanceOf[Function0[Any]]
in.close()

val out = new ObjectOutputStream(new FileOutputStream(path))
try {
out.writeObject(f0())
} catch {
case e: Throwable => out.writeObject(e)
} finally {
out.close()
}
} finally {
in.close()
}
}