Created
August 27, 2020 18:32
-
-
Save peheje/d673a4897d2954f3e9d2c35a2909b5dd to your computer and use it in GitHub Desktop.
Wrap job multiple times
This file contains hidden or 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
import kotlin.random.Random | |
import kotlin.system.measureTimeMillis | |
fun main() { | |
val basicJob = BasicJob() | |
val delayedJob = DelayedJob(basicJob, 1000) | |
val measuredAndDelayedJob = MeasuredJob(delayedJob) | |
val measuredDelayedAndSynchronizedJob = SynchronizedJob(measuredAndDelayedJob, "lock") | |
measuredDelayedAndSynchronizedJob.run() | |
} | |
abstract class Job { | |
abstract fun run() | |
} | |
class BasicJob : Job() { | |
override fun run() { | |
println("Basic job") | |
Thread.sleep(Random.nextInt(500).toLong()) | |
} | |
} | |
class DelayedJob(private val job: Job, private val delay: Long) : Job() { | |
override fun run() { | |
println("Delayed job") | |
Thread.sleep(delay) | |
job.run() | |
} | |
} | |
class MeasuredJob(private val job: Job) : Job() { | |
override fun run() { | |
println("Measured job") | |
val time = measureTimeMillis { | |
job.run() | |
} | |
println("-> Job ran in $time ms") | |
} | |
} | |
class SynchronizedJob(private val job: Job, private val key: String) : Job() { | |
override fun run() { | |
println("Synchronized job") | |
synchronized(key.intern()) { | |
job.run() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment