Colton Idle
06/13/2024, 1:01 AMLogFlusher
class that has a flush()
method. Sometimes due to different threads calling LogFlusher.flush()
I'll have two flushes going on at the same time, which leads to two network calls with the same data. Although the POST request is idempotent... I'd like to prevent this in kotlin.
I'm assuming I can just add @Synchronized
as an annotation to the flush method and I'll be good to go? A small caveat is that my LogFlusher
is not a singleton so the two different places that call flush have there own instance of LogFlusher
created. I recall that you should only make something a singleton if it actually has state. In this case, my LogFlusher
doesn't have state. Should I make it a singleton too?Ronny Bräunlich
06/13/2024, 4:51 AMLogFlusher
doesn't have state?
Now to your question: as always with concurrency, there are a lot of options 😅 Since your LogFlusher
isn't a singleton I would refrain from using the @Synchronized
annotation but rather the function with the class itself as a lock:
fun flush() {
synchronized(LogFlusher::class){
...
}
}
That ways you should be safe on a class level. Alternatively, you could also use a static Semaphore
or Mutex
and block access inside the method to a single thread.Wout Werkman
06/13/2024, 2:01 PMflush()
is a stateful function over some state, and I'd treat it as such.Colton Idle
06/13/2024, 2:53 PMColton Idle
06/13/2024, 2:55 PMColton Idle
06/13/2024, 2:58 PMfun flush() {
synchronized(LogFlusher::class){
...
}
}
you can synchronize on the class level! hm... i wonder if i should have gone that route instead.Michael Krussel
06/13/2024, 8:09 PM