If currently have a `LogFlusher` class that has a ...
# getting-started
c
If currently have a
LogFlusher
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?
r
Hi Colton, just out of curiosity, where is your log data stored when
LogFlusher
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:
Copy code
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.
w
Well, while it might not have fields, your flusher has state in the sense that
flush()
is a stateful function over some state, and I'd treat it as such.
c
stored in a database
thats an interesting point @Wout Werkman! i ended up making it a @Singletonn (im using dagger) and flush is actually a suspend method. so i used a mutex lock. I wrote a test and it seems to work as expected so i think i did it right!
👍 1
TIL that
Copy code
fun flush() {
  synchronized(LogFlusher::class){
    ...
  }
}
you can synchronize on the class level! hm... i wonder if i should have gone that route instead.
m
Synchronized and suspend functions don't play all that well together, so mutex was the right choice.
👍 1