Skip to content

Commit 2cdc2c3

Browse files
committed
chore: optimize lazy val with power of two.
1 parent fb6cc9b commit 2cdc2c3

File tree

1 file changed

+6
-5
lines changed

1 file changed

+6
-5
lines changed

library/src/scala/runtime/LazyVals.scala

+6-5
Original file line numberDiff line numberDiff line change
@@ -27,17 +27,18 @@ object LazyVals {
2727

2828
private val base: Int = {
2929
val processors = java.lang.Runtime.getRuntime.nn.availableProcessors()
30-
8 * processors * processors
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)