Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore: optimize lazy val with power of two. #22428

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions library/src/scala/runtime/LazyVals.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Author

@He-Pin He-Pin Jan 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure why it's 8 here, Some CPU has 384 cores now, maybe 2 * 2 is better than 8.

The current implementation may use a little more memory than it was, but as many server just has 64 cores, which is the same.

//find the next power of 2
1 << (32 - Integer.numberOfLeadingZeros(rawSize - 1))
He-Pin marked this conversation as resolved.
Show resolved Hide resolved
}

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)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Use & instead of %

}

private final val LAZY_VAL_MASK = 3L
Expand Down
Loading