Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,23 @@

package co.touchlab.stately.concurrency

actual open class Synchronizable(private val _lock: Lock) {
actual constructor() : this(Lock())
import kotlin.experimental.ExperimentalNativeApi
import kotlin.native.ref.createCleaner

fun <R> runSynchronized(block: () -> R): R = _lock.withLock(block)
actual open class Synchronizable internal constructor(private val resource: SynchronizationResource) {
actual constructor() : this(SynchronizationResource())

@Suppress("unused")
@OptIn(ExperimentalNativeApi::class)
private val cleaner = createCleaner(resource, SynchronizationResource::close)

fun <R> runSynchronized(block: () -> R): R = resource.lock.withLock(block)
}

internal open class SynchronizationResource(internal val lock: Lock = Lock()) {
internal open fun close() {
lock.close()
}
}

actual inline fun <R> Synchronizable.synchronize(noinline block: () -> R): R = runSynchronized(block)
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package co.touchlab.stately.concurrency

import kotlin.native.runtime.GC
import kotlin.native.runtime.NativeRuntimeApi
import kotlin.test.Test
import kotlin.test.assertEquals

@OptIn(NativeRuntimeApi::class)
class SynchronizableTest {
@Test
fun closesLockWhenCollected() {
val closeCount = AtomicInt(0)
val resource = object : SynchronizationResource() {
override fun close() {
super.close()
closeCount.incrementAndGet()
}
}

useResource(resource)

repeat(100) {
GC.collect()
if (closeCount.get() == 1) {
GC.collect()
assertEquals(1, closeCount.get())
return
}
}

assertEquals(1, closeCount.get())
}

private fun useResource(resource: SynchronizationResource) {
Synchronizable(resource).synchronize {}
}
}
Loading