https://kotlinlang.org logo
#coroutines
Title
# coroutines
c

Conor Fennell

04/26/2021, 9:36 PM
Howdy, Have a beginner question around coroutines. I am using coroutines in a ktor project. And multiple coroutines can increment the same prometheus counter at the same time
io.prometheus.client.Counter
The prometheus Counter is a Java library. Is there any concurrency issues people would foresee? The prometheus implementation uses Compare and Swap operations so should be coroutine safe. But saying that, there is a thread hash code used for some accounting
ThreadLocal()
.
Copy code
static final ThreadLocal<int[]> threadHashCode = new ThreadLocal();
    static final Random rng = new Random();
    static final int NCPU = Runtime.getRuntime().availableProcessors();
    transient volatile Striped64.Cell[] cells;
    transient volatile long base;
    transient volatile int busy;
    private static final AtomicLongFieldUpdater<Striped64> CAS_BASE = AtomicLongFieldUpdater.newUpdater(Striped64.class, "base");
    private static final AtomicIntegerFieldUpdater<Striped64> CAS_BUSY = AtomicIntegerFieldUpdater.newUpdater(Striped64.class, "busy");
t

TwoClocks

04/27/2021, 3:55 AM
If promrtheus is thread safe, then it's coroutine safe. If prometheus is not thread safe then it's might not be coroutine safe depending on which dispatcher/coroutineScope you are using.
🙇 1
u

uli

04/27/2021, 11:53 AM
@TwoClocks not true 🙂 I have not looked at the code. But if the code relies on ThreadLocal there is a chance of this ThreadLocal to change because the dispatcher thread of the coroutine might change.
t

TwoClocks

04/27/2021, 3:04 PM
ahhh. I see. Yeah, that could be a problem, again depending on which dispatcher you used.
4 Views