mdedetrich commented on code in PR #371: URL: https://github.com/apache/incubator-pekko/pull/371#discussion_r1231912176
########## actor/src/main/scala/org/apache/pekko/util/RandomShortProvider.scala: ########## @@ -0,0 +1,43 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * license agreements; and to You under the Apache License, version 2.0: + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * This file is part of the Apache Pekko project, derived from Akka. + */ + +package org.apache.pekko.util + +import org.apache.pekko.annotation.InternalApi + +import java.util.Random + +/** + * An efficient thread safe generator of pseudo random shorts based on + * https://en.wikipedia.org/wiki/Double_hashing#Enhanced_double_hashing. + * + * Note that due to the usage of synchronized this method is optimized + * for the happy case (i.e. least contention) on multiple threads. + */ + +@InternalApi +private[pekko] class RandomShortProvider(seed: Random) { + // These methods are volatile so that they stay within cache + private var index = seed.nextLong + private var increment = seed.nextLong + private var count = 1L + + def nextId(): Short = synchronized { + val result = (0xFFFFFFFF & index).asInstanceOf[Short] Review Comment: So using a much shorter timeout the improvements are better (i.e. this is the results with 10 nanos) ``` [info] IdGeneratorBanchmark.measureEnhancedDoubleHash thrpt 3 0,001 ± 0,001 ops/ns [info] IdGeneratorBanchmark.measureSecureRandom thrpt 3 0,001 ± 0,001 ops/ns [info] IdGeneratorBanchmark.measureThreadLocalRandom thrpt 3 0,312 ± 0,074 ops/ns [info] IdGeneratorBanchmark.multipleThreadsMeasureEnhancedDoubleHash thrpt 3 0,001 ± 0,001 ops/ns [info] IdGeneratorBanchmark.multipleThreadsMeasureSecureRandom thrpt 3 0,001 ± 0,001 ops/ns [info] IdGeneratorBanchmark.multipleThreadsMeasureThreadLocalRandom thrpt 3 0,622 ± 0,018 ops/ns ``` I am not sure what problem we are trying to achieve with a semaphore though, in such a hot loop with only a single permit its actually slower than `synchronized` which because the JVM know its only single threaded (i.e. permit of 1) is hyper optimized for this case. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
