Skip to content

Instantly share code, notes, and snippets.

@peheje
Created August 27, 2020 18:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save peheje/d673a4897d2954f3e9d2c35a2909b5dd to your computer and use it in GitHub Desktop.
Save peheje/d673a4897d2954f3e9d2c35a2909b5dd to your computer and use it in GitHub Desktop.
Wrap job multiple times
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