Skip to content

Instantly share code, notes, and snippets.

@vagran
Created January 8, 2020 21:16
Show Gist options
  • Save vagran/64617e2a2784ad38c86612130cb3fd89 to your computer and use it in GitHub Desktop.
Save vagran/64617e2a2784ad38c86612130cb3fd89 to your computer and use it in GitHub Desktop.
@Volatile var i = 0
val lock = AtomicInteger(0)
fun LockSynchronized()
{
synchronized(this) {
i++
}
}
fun LockAtomic()
{
while (true) {
if (lock.compareAndExchange(0, 1) != 0) {
continue
}
i++
lock.set(0)
break
}
}
fun LockTest1()
{
for (i in 0..5000000) {
LockSynchronized()
}
for (j in 0..10) {
val start = System.nanoTime()
for (i in 0..1000000) {
LockSynchronized()
}
val end = System.nanoTime()
println(end - start)
}
}
fun LockTest2()
{
for (i in 0..5000000) {
LockAtomic()
}
for (j in 0..10) {
val start = System.nanoTime()
for (i in 0..1000000) {
LockAtomic()
}
val end = System.nanoTime()
println(end - start)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment