100 lines
2.3 KiB
Kotlin
100 lines
2.3 KiB
Kotlin
package nl.astraeus.persistence
|
|
|
|
import nl.astraeus.nl.astraeus.persistence.OptimisticLockingException
|
|
import nl.astraeus.nl.astraeus.persistence.Persistent
|
|
import nl.astraeus.nl.astraeus.persistence.TransactionLog
|
|
import nl.astraeus.nl.astraeus.persistence.find
|
|
import nl.astraeus.nl.astraeus.persistence.findByIndex
|
|
import nl.astraeus.nl.astraeus.persistence.index
|
|
import nl.astraeus.persistence.domain.Person
|
|
import org.junit.jupiter.api.Assertions.assertNotNull
|
|
import org.junit.jupiter.api.assertThrows
|
|
import java.io.File
|
|
import kotlin.test.Test
|
|
|
|
class TestOptimisticLocking {
|
|
|
|
@Test
|
|
fun showTransactions() {
|
|
val log = TransactionLog(File("data", "test-locking"))
|
|
|
|
log.showTransactions()
|
|
}
|
|
|
|
@Test
|
|
fun testOptimisticLocking() {
|
|
println("Test locking")
|
|
|
|
val pst = Persistent(
|
|
directory = File("data", "test-locking"),
|
|
arrayOf(
|
|
index<Person>("name") { p -> (p as? Person)?.name ?: "" },
|
|
),
|
|
true
|
|
)
|
|
|
|
pst.transaction {
|
|
val person = find<Person>(1L) ?: Person(
|
|
id = 1L,
|
|
name = "John Doe",
|
|
age = 25
|
|
)
|
|
|
|
store(person)
|
|
|
|
findByIndex<Person>("name", "John Doe").forEach { p ->
|
|
println("Found person by name: ${p.name} - ${p.age}")
|
|
}
|
|
}
|
|
|
|
pst.query {
|
|
val person = find<Person>(1L)
|
|
|
|
assertNotNull(person)
|
|
}
|
|
|
|
val threads = Array(2) { index ->
|
|
Thread {
|
|
println("Start thread $index")
|
|
var person: Person? = null
|
|
|
|
pst.transaction {
|
|
Thread.sleep(10L)
|
|
person = find<Person>(1L)
|
|
println("Thread $index -> ${person?.version}")
|
|
}
|
|
|
|
if (person != null) {
|
|
Thread.sleep((index + 1) * 10L)
|
|
|
|
if (index == 1) {
|
|
assertThrows<OptimisticLockingException> {
|
|
println("Store thread $index -> ${person!!.version}")
|
|
pst.transaction {
|
|
store(person!!)
|
|
}
|
|
}
|
|
} else {
|
|
println("Store thread $index -> ${person!!.version}")
|
|
pst.transaction {
|
|
store(person!!)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
for (thread in threads) {
|
|
thread.start()
|
|
}
|
|
|
|
for (thread in threads) {
|
|
thread.join()
|
|
}
|
|
|
|
pst.datastore.printStatus()
|
|
//pst.snapshot()
|
|
pst.removeOldFiles()
|
|
}
|
|
}
|