Skip to content

Commit

Permalink
Optimize locking time
Browse files Browse the repository at this point in the history
  • Loading branch information
ofekby committed Nov 22, 2023
1 parent a98c1db commit 82d83a3
Showing 1 changed file with 6 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.util.messages.Topic
import java.util.Optional
import java.util.concurrent.atomic.AtomicBoolean
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReadWriteLock
import java.util.concurrent.locks.ReentrantReadWriteLock
import java.util.function.Consumer

open class TopicBasedState<T, S : Consumer<T>>(private val topic: Topic<S>, private var value: T? = null) {
private val rwLock: ReadWriteLock = ReentrantReadWriteLock()
private val hasChanged = AtomicBoolean(false)

open fun get() = rwLock.readLock().withLock {
value
Expand All @@ -20,10 +22,12 @@ open class TopicBasedState<T, S : Consumer<T>>(private val topic: Topic<S>, priv

fun set(newValue: T) {
rwLock.writeLock().withLock {
val hasChanged = value != newValue
hasChanged.set(value != newValue)
value = newValue
}

if (hasChanged && value != null) {
rwLock.readLock().withLock {
if (hasChanged.getAndSet(false) && value != null) {
ApplicationManager.getApplication().messageBus.syncPublisher(topic).accept(value!!)
}
}
Expand Down

0 comments on commit 82d83a3

Please sign in to comment.