Created
January 8, 2020 21:16
-
-
Save vagran/64617e2a2784ad38c86612130cb3fd89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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