From 0f8f2c2f8bc2660b0f244e086992a4b26db79724 Mon Sep 17 00:00:00 2001 From: He-Pin Date: Wed, 22 Jan 2025 03:16:02 +0800 Subject: [PATCH] chore: optimize lazy val with power of two. --- library/src/scala/runtime/LazyVals.scala | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/library/src/scala/runtime/LazyVals.scala b/library/src/scala/runtime/LazyVals.scala index 15220ea2410a..9c956f1c0b06 100644 --- a/library/src/scala/runtime/LazyVals.scala +++ b/library/src/scala/runtime/LazyVals.scala @@ -27,17 +27,18 @@ object LazyVals { private val base: Int = { val processors = java.lang.Runtime.getRuntime.nn.availableProcessors() - 8 * processors * processors + val rawSize = 8 * processors * processors + //find the next power of 2 + 1 << (32 - Integer.numberOfLeadingZeros(rawSize - 1)) } + private val mask: Int = base - 1 + private val monitors: Array[Object] = Array.tabulate(base)(_ => new Object) private def getMonitor(obj: Object, fieldId: Int = 0) = { - var id = (java.lang.System.identityHashCode(obj) + fieldId) % base - - if (id < 0) id += base - monitors(id) + monitors((java.lang.System.identityHashCode(obj) + fieldId) & mask) } private final val LAZY_VAL_MASK = 3L