PrioritySemaphore

class PrioritySemaphore(maxPermits: Int)

Priority-ordered permit pool. acquire suspends until a permit is free; when multiple acquirers are waiting, release wakes the one with the highest priority (= largest Double). Replaces kotlinx.coroutines.sync.Semaphore, which is FIFO — under a fast pan with hundreds of queued tile-fetch requests, FIFO leaves the camera-relevant (or coarse-fallback) tile buried behind seconds of stale prior-frame requests. There is no in-flight cancellation: this reorders only the WAIT line, not the running set. Cesium 3D Tiles uses the same pattern in RequestScheduler.update().

Shared by earth.worldwind.layer.ogc3d.stream.TileFetchQueue (closer + coarser wins) and the vector-tile fetch path (coarse-first, so the fallback always paints before refinement).

Implementation: linear-insert + head-pop sorted list of waiters; O(N) per acquire, O(1) per release. For N up to ~1000 (observed at globe scale) the linear insert is microseconds — far cheaper than the multi-second queue stall it eliminates.

Constructors

Link copied to clipboard
constructor(maxPermits: Int)

Functions

Link copied to clipboard
suspend fun acquire(priority: Double)
Link copied to clipboard
Link copied to clipboard
suspend fun release()

Must be cancellation-safe — callers invoke from finally blocks of fetches that may already be cancelled. A bare mutex.withLock would throw immediately under the cancelled context, leaking the permit; running under NonCancellable lets the brief atomic update always finish.

Link copied to clipboard
inline suspend fun <T> PrioritySemaphore.withPermit(priority: Double, block: () -> T): T

Acquire a permit at priority, run block, then release — the priority analogue of kotlinx.coroutines.sync.withPermit. Higher priority is served first when the pool is contended; equal priorities keep FIFO order.