Skip to content

Commit

Permalink
refactor ReferenceCountedMutex
Browse files Browse the repository at this point in the history
 - remove synchronisation when removing mutex from map since the mutex
   is only removed once when decrementing the rc to 0
   - this is now guaranteed since the rc cannot increment once reaching
     0 anymore
  • Loading branch information
robinfriedli committed Oct 20, 2020
1 parent 322d9d4 commit 7684d5e
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 15 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ repositories {
}
dependencies {
implementation "net.robinfriedli:exec:1.1"
implementation "net.robinfriedli:exec:1.2"
}
```

Expand All @@ -22,7 +22,7 @@ dependencies {
<dependency>
<groupId>net.robinfriedli</groupId>
<artifactId>exec</artifactId>
<version>1.1</version>
<version>1.2</version>
<type>pom</type>
</dependency>
Expand Down
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ plugins {
}

group = "net.robinfriedli"
version = "1.1"
version = "1.2"
sourceCompatibility = "8"
targetCompatibility = "8"

Expand Down
4 changes: 1 addition & 3 deletions src/main/kotlin/net/robinfriedli/exec/MutexSync.kt
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,11 @@ class MutexSync<K> {
}
}

// -- thread C is here
synchronized(mutex) {
return try {
toRun.call() // - thread B is still here
toRun.call()
} finally {
mutex.decrementRc()
// -- thread A is here (without reference counting it would have removed the mutex)
}
}
}
Expand Down
11 changes: 2 additions & 9 deletions src/main/kotlin/net/robinfriedli/exec/ReferenceCountedMutex.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,6 @@ class ReferenceCountedMutex<T>(private val key: T, private val containingMap: Mu

private val rc = AtomicInteger(Int.MIN_VALUE)

private var destroyed = false

fun incrementRc(): Int {
return rc.updateAndGet { i ->
when {
Expand All @@ -35,13 +33,8 @@ class ReferenceCountedMutex<T>(private val key: T, private val containingMap: Mu
*/
fun decrementRc(): Boolean {
val currentRc = rc.decrementAndGet()
if (currentRc <= 0) {
synchronized(this) {
if (!destroyed) {
destroyed = containingMap.remove(key) != null
return destroyed
}
}
if (currentRc == 0) {
return containingMap.remove(key) != null
}
return false
}
Expand Down

0 comments on commit 7684d5e

Please sign in to comment.