Klitos Kyriacou
08/16/2022, 1:20 PMrateLimiter.acquire()
while (System.nanoTime() < endTime) {
foo()
bar()
baz()
if (System.nanoTime() < endTime)
rateLimiter.acquire()
}
2.
while (true) {
rateLimiter.acquire()
if (System.nanoTime() >= endTime)
break
foo()
bar()
baz()
}
3.
while (run { rateLimiter.acquire(); System.nanoTime() < endTime }) {
foo()
bar()
baz()
}
Joffrey
08/16/2022, 1:27 PMacquire()
to only be called when endTime
is not reached? In all 3 cases, the first acquire()
is done regardless of the current time. In case #1, it seems important to check if endTime
is not reached before calling acquire()
again (otherwise the if
has no reason to be there). But in case 2 and 3, acquire()
is called after foo/bar/baz
regardless of the current time.Klitos Kyriacou
08/16/2022, 1:35 PMif
guard for the rateLimiter in #1). In fact, the calls to foo(), bar() and baz() are almost instantaneous and therefore the call to rateLimiter.acquire() is guarded by the condition from the previous iteration of the loop.Joffrey
08/16/2022, 1:43 PMwhile (System.nanoTime() < endTime) {
rateLimiter.acquire()
foo()
bar()
baz()
}
acquire()
might take some time, and bring you past endTime
, but since foo/bar/baz
is almost instant, you don't lose much by executing them one extra time. Semantically, it must not be an issue to execute foo/bar/baz
after endTime
because in your current options, you could be checking the condition 1ns before the end and it would basically mean that you run foo/bar/baz
after the end too.Klitos Kyriacou
08/16/2022, 2:01 PMJoffrey
08/16/2022, 2:03 PMaquire()
suspending (if not already) and use withTimeout
to immediately cancel a pending acquire()
instead of relying on a loop condition checking the current nanoTime
against a pre-computed endTime
:
withTimeout(runDuration) {
while(true) {
rateLimiter.acquire()
foo()
bar()
baz()
}
}
This way you never wait for a long acquire()
past the expected end timeKlitos Kyriacou
08/16/2022, 2:07 PMephemient
08/16/2022, 3:51 PMKlitos Kyriacou
08/16/2022, 3:52 PMephemient
08/16/2022, 3:52 PMsleepUninterruptibly
so even wrapping it in runInterruptible
doesn't really help