Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Merge pull request #1332 from lift/asc_issue_1332

Use ThreadLocalRandom when available for StringHelpers
  • Loading branch information...
commit 823c96ba647d8b46c02a1160b03847e033690a18 2 parents cbf51d4 + f2de993
@dpp dpp authored
Showing with 19 additions and 2 deletions.
  1. +19 −2 core/util/src/main/scala/net/liftweb/util/StringHelpers.scala
View
21 core/util/src/main/scala/net/liftweb/util/StringHelpers.scala
@@ -19,6 +19,7 @@ package util
import java.security.SecureRandom
import java.util.regex._
+import java.util.Random
import java.lang.Character._
import java.lang.{StringBuilder => GoodSB}
import scala.xml.NodeSeq
@@ -32,7 +33,23 @@ object StringHelpers extends StringHelpers
trait StringHelpers {
/** random numbers generator */
- private val _random = new SecureRandom
+ private lazy val _slowRandom = new SecureRandom
+ private lazy val _currentTlrMethod = {
+ try {
+ val tlr = Class.forName("java.util.concurrent.ThreadLocalRandom")
+ Full(tlr.getMethod("current"))
+ } catch {
+ case e =>
+ Failure("ThreadLocalRandom is not available.", Full(e), Empty)
+ }
+ }
+ private def withRng[T](block: (Random)=>T) = {
+ _currentTlrMethod.map { meth =>
+ block(meth.invoke(null).asInstanceOf[Random])
+ } openOr {
+ _slowRandom.synchronized(block(_slowRandom))
+ }
+ }
/**
* If str is surrounded by quotes it return the content between the quotes
@@ -176,7 +193,7 @@ trait StringHelpers {
if (pos >= size) sb
else {
val randNum = if ((pos % 6) == 0) {
- _random.synchronized(_random.nextInt)
+ withRng(_.nextInt)
} else {
lastRand
}
Please sign in to comment.
Something went wrong with that request. Please try again.