Skip to content

Commit

Permalink
Simplify socket pool index calculation.
Browse files Browse the repository at this point in the history
  • Loading branch information
JonathanLennox committed Oct 15, 2024
1 parent 5470f0a commit af1c1e6
Showing 1 changed file with 4 additions and 19 deletions.
23 changes: 4 additions & 19 deletions src/main/kotlin/org/ice4j/socket/SocketPool.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import java.net.DatagramSocket
import java.net.DatagramSocketImpl
import java.net.SocketAddress
import java.nio.channels.DatagramChannel
import java.util.concurrent.atomic.AtomicInteger
import java.util.concurrent.atomic.AtomicLong

/** A pool of datagram sockets all bound on the same port.
*
Expand Down Expand Up @@ -71,7 +71,7 @@ class SocketPool(
}
}

private val sockIndex = AtomicInteger(0)
private val sockIndex = AtomicLong(0)

/** The socket on which packets will be received. */
val receiveSocket: DatagramSocket
Expand All @@ -90,23 +90,8 @@ class SocketPool(
}

private fun nextIndex(): Int {
val nextIdx = sockIndex.incrementAndGet()
if (nextIdx < numSockets) {
return nextIdx
}
/* Try to modulo the counter, but be prepared to lose. */
val mod = nextIdx.rem(numSockets)
if (sockIndex.compareAndSet(nextIdx, mod)) {
return mod
}
do {
val cur = sockIndex.get()
if (cur < numSockets) {
break
}
val curMod = cur.rem(numSockets)
} while (!sockIndex.compareAndSet(cur, curMod))
return mod
val nextIdx = sockIndex.getAndIncrement()
return nextIdx.rem(numSockets).toInt()
}

fun close() {
Expand Down

0 comments on commit af1c1e6

Please sign in to comment.