add drill03 exercise 1

This commit is contained in:
Raffaele Mignone 2020-03-24 21:43:20 +01:00
parent 91dac8aacc
commit a1bc8b5fde
Signed by: norangebit
GPG Key ID: F5255658CB220573
4 changed files with 69 additions and 3 deletions

View File

@ -239,7 +239,7 @@ formatting:
active: true active: true
autoCorrect: true autoCorrect: true
MultiLineIfElse: MultiLineIfElse:
active: true active: false
autoCorrect: true autoCorrect: true
NoBlankLineBeforeRbrace: NoBlankLineBeforeRbrace:
active: true active: true
@ -401,7 +401,7 @@ performance:
active: true active: true
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
SpreadOperator: SpreadOperator:
active: true active: false
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
UnnecessaryTemporaryInstantiation: UnnecessaryTemporaryInstantiation:
active: true active: true
@ -503,7 +503,7 @@ style:
MagicNumber: MagicNumber:
active: true active: true
excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt" excludes: "**/test/**,**/androidTest/**,**/*.Test.kt,**/*.Spec.kt,**/*.Spek.kt"
ignoreNumbers: '-1,0,1,2' ignoreNumbers: '-1,0,1,2,100,500,1000'
ignoreHashCodeFunction: true ignoreHashCodeFunction: true
ignorePropertyDeclaration: false ignorePropertyDeclaration: false
ignoreLocalVariableDeclaration: false ignoreLocalVariableDeclaration: false

View File

@ -0,0 +1,17 @@
package drills.drill03.exercise1
import util.active.toActive
import kotlin.time.ExperimentalTime
import kotlin.time.measureTime
@ExperimentalTime
fun main() {
val math = MathImpl().toActive(Math::class.java)
val elapsed = measureTime {
for (i in 0 until 1000)
math.add(i, 0)
}
println("Elapsed time: $elapsed")
}

View File

@ -0,0 +1,11 @@
package drills.drill03.exercise1
interface Math {
fun add(a: Int, b: Int)
}
class MathImpl : Math {
override fun add(a: Int, b: Int) {
println("The sum is ${a + b}")
}
}

View File

@ -0,0 +1,38 @@
package util.active
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
import java.util.concurrent.LinkedBlockingQueue
class ActiveObjectHandler(private val target: Any) : InvocationHandler {
private val queue = LinkedBlockingQueue<Call>()
init {
Thread {
while (true)
queue.take().executeOn(target)
}.start()
}
override fun invoke(proxy: Any?, method: Method?, args: Array<out Any>?): Any {
if (method != null && args != null)
queue.add(Call(method, args))
return Unit
}
data class Call(val method: Method, val args: Array<out Any>) {
fun executeOn(target: Any) {
method.invoke(target, *args)
}
}
}
fun <T> Any.toActive(inter: Class<T>): T {
return Proxy.newProxyInstance(
this::class.java.classLoader,
arrayOf(inter),
ActiveObjectHandler(this)
) as T
}