Skip to content

Commit 7684d5e

Browse files
committed
refactor ReferenceCountedMutex
- 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
1 parent 322d9d4 commit 7684d5e

File tree

4 files changed

+6
-15
lines changed

4 files changed

+6
-15
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ repositories {
1313
}
1414
1515
dependencies {
16-
implementation "net.robinfriedli:exec:1.1"
16+
implementation "net.robinfriedli:exec:1.2"
1717
}
1818
```
1919

@@ -22,7 +22,7 @@ dependencies {
2222
<dependency>
2323
<groupId>net.robinfriedli</groupId>
2424
<artifactId>exec</artifactId>
25-
<version>1.1</version>
25+
<version>1.2</version>
2626
<type>pom</type>
2727
</dependency>
2828

build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ plugins {
66
}
77

88
group = "net.robinfriedli"
9-
version = "1.1"
9+
version = "1.2"
1010
sourceCompatibility = "8"
1111
targetCompatibility = "8"
1212

src/main/kotlin/net/robinfriedli/exec/MutexSync.kt

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,13 +28,11 @@ class MutexSync<K> {
2828
}
2929
}
3030

31-
// -- thread C is here
3231
synchronized(mutex) {
3332
return try {
34-
toRun.call() // - thread B is still here
33+
toRun.call()
3534
} finally {
3635
mutex.decrementRc()
37-
// -- thread A is here (without reference counting it would have removed the mutex)
3836
}
3937
}
4038
}

src/main/kotlin/net/robinfriedli/exec/ReferenceCountedMutex.kt

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,6 @@ class ReferenceCountedMutex<T>(private val key: T, private val containingMap: Mu
1010

1111
private val rc = AtomicInteger(Int.MIN_VALUE)
1212

13-
private var destroyed = false
14-
1513
fun incrementRc(): Int {
1614
return rc.updateAndGet { i ->
1715
when {
@@ -35,13 +33,8 @@ class ReferenceCountedMutex<T>(private val key: T, private val containingMap: Mu
3533
*/
3634
fun decrementRc(): Boolean {
3735
val currentRc = rc.decrementAndGet()
38-
if (currentRc <= 0) {
39-
synchronized(this) {
40-
if (!destroyed) {
41-
destroyed = containingMap.remove(key) != null
42-
return destroyed
43-
}
44-
}
36+
if (currentRc == 0) {
37+
return containingMap.remove(key) != null
4538
}
4639
return false
4740
}

0 commit comments

Comments
 (0)