-
Notifications
You must be signed in to change notification settings - Fork 693
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #807 from rpiotrow/bugfix/806-ThreadLocalRandomGen…
…erator-not-serializable Make thread local field transient in `ThreadLocalRandomGenerator`
- Loading branch information
Showing
2 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
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
53 changes: 53 additions & 0 deletions
53
math/src/test/scala/breeze/stats/distributions/ThreadLocalRandomGeneratorTest.scala
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
package breeze.stats.distributions | ||
|
||
import org.apache.commons.math3.random.MersenneTwister | ||
import org.scalatest.{FunSuite, Matchers} | ||
|
||
import java.io._ | ||
|
||
class ThreadLocalRandomGeneratorTest extends FunSuite with Matchers { | ||
test("ThreadLocalRandomGeneratorTest should be serializable") { | ||
val generator = new ThreadLocalRandomGenerator(new MersenneTwister()) | ||
serialize(generator) | ||
} | ||
|
||
test("ThreadLocalRandomGeneratorTest should be serializable after usage") { | ||
val generator = new ThreadLocalRandomGenerator(new MersenneTwister()) | ||
generator.nextInt() | ||
serialize(generator) | ||
} | ||
|
||
test("ThreadLocalRandomGeneratorTest should be deserializable") { | ||
val generator = new ThreadLocalRandomGenerator(new MersenneTwister()) | ||
val i1 = generator.nextInt() | ||
val bytes = serialize(generator) | ||
val deserialized = deserialize(bytes) | ||
val i2 = deserialized.nextInt() | ||
|
||
i1 should not be i2 | ||
} | ||
|
||
private def serialize(generator: ThreadLocalRandomGenerator): Array[Byte] = { | ||
val outputStream = new ByteArrayOutputStream(512) | ||
val out = new ObjectOutputStream(outputStream) | ||
try { | ||
out.writeObject(generator) | ||
outputStream.toByteArray | ||
} catch { | ||
case _: IOException => fail("cannot serialize") | ||
} finally { | ||
if (out != null) out.close() | ||
} | ||
} | ||
|
||
private def deserialize(bytes: Array[Byte]): ThreadLocalRandomGenerator = { | ||
val in = new ObjectInputStream(new ByteArrayInputStream(bytes)) | ||
try { | ||
in.readObject().asInstanceOf[ThreadLocalRandomGenerator] | ||
} catch { | ||
case _: IOException => fail("cannot deserialize") | ||
} finally { | ||
if (in != null) in.close() | ||
} | ||
} | ||
} |