Ali Khaleqi Yekta
10/24/2025, 9:51 PMimport kotlin.concurrent.Volatile
object RandomPool {
private val writeLock = ReentrantLock()
private val random = kotlin.random.Random.Default
@Volatile private var array = FloatArray(0)
private var _array = array
operator fun get(index: Int): Float {
// Available in the thread-local cached array
val local = _array
if (index < local.size) {
return local[index]
}
// Available in general
val latest = array
if (index < latest.size) {
_array = latest
return latest[index]
}
// Not available, need to grow
ensureCapacity(index + 1)
return array[index]
}
fun ensureCapacity(capacity: Int) =
writeLock.withLock {
// Double-Checked Locking: After acquiring the lock, check the condition again.
// Another thread might have already grown the array while this thread was waiting.
val currentArray = array
if (capacity <= currentArray.size) return@withLock
// This thread has the lock and has confirmed the array is still too small.
// Proceed with the resizing operation.
val oldSize = currentArray.size
// Grow the array with some extra capacity to reduce the frequency of re-allocations.
val newSize = maxOf(capacity, (1.5 * oldSize).toInt())
// Copy-on-Write: Create and populate the new array completely before publishing it.
val newArray = currentArray.copyOf(newSize)
for (i in oldSize until newSize) {
newArray[i] = random.nextFloat()
}
array = newArray
_array = newArray
}
}
I believe in this case, the _array should be an acceptable optimization and shouldn't cause any wrong output being returned, but asking AI, it keeps on insisting otherwise, and points out that there actually is a way that _array can return `0.0`(not randomly, but as an uninitialized value). The array is only ever set to completely filled arrays, and the _array is only updated afterwards, plus the values themselves never change. So, I don't seem to see any problem. Do you know if it's actually wrong, or the AI is hallucinating?loke
11/13/2025, 1:50 PM@Volatile , but that's a very different thing.loke
11/13/2025, 1:52 PMloke
11/13/2025, 1:53 PMnewArray, meaning that the content may not have propagated from cache by the time another thread reads the data.loke
11/13/2025, 1:53 PMloke
11/13/2025, 1:54 PMAli Khaleqi Yekta
11/13/2025, 2:53 PMloke
11/13/2025, 3:36 PMloke
11/13/2025, 3:38 PMloke
11/13/2025, 3:39 PMloke
11/13/2025, 3:40 PMAli Khaleqi Yekta
11/13/2025, 4:01 PMloke
11/16/2025, 8:19 AM