Skip to content

Commit 2c50caf

Browse files
committed
chore: optimize lazy val with power of two.
1 parent 50d245f commit 2c50caf

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

library/src/scala/runtime/LazyVals.scala

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,19 @@ object LazyVals {
2626
}
2727

2828
private val base: Int = {
29-
val processors = java.lang.Runtime.getRuntime.availableProcessors()
30-
8 * processors * processors
29+
val processors = java.lang.Runtime.getRuntime.nn.availableProcessors()
30+
val rawSize = 8 * processors * processors
31+
//find the next power of 2
32+
1 << (32 - Integer.numberOfLeadingZeros(rawSize - 1))
3133
}
3234

35+
private val mask: Int = base - 1
36+
3337
private val monitors: Array[Object] =
3438
Array.tabulate(base)(_ => new Object)
3539

3640
private def getMonitor(obj: Object, fieldId: Int = 0) = {
37-
var id = (java.lang.System.identityHashCode(obj) + fieldId) % base
38-
39-
if (id < 0) id += base
40-
monitors(id)
41+
monitors((java.lang.System.identityHashCode(obj) + fieldId) & mask)
4142
}
4243

4344
private final val LAZY_VAL_MASK = 3L

0 commit comments

Comments
 (0)