TtlWrapperDemo.kt 1.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
package com.alibaba.demo.ttl

import com.alibaba.ttl.TransmittableThreadLocal
import com.alibaba.ttl.TtlCallable
import com.alibaba.ttl.TtlRunnable
import java.util.concurrent.Callable
import java.util.concurrent.Executors

/**
 * @author Jerry Lee (oldratlee at gmail dot com)
 */
fun main() {
    val executorService = Executors.newCachedThreadPool()
oldratlee's avatar
oldratlee 已提交
14
    val context = TransmittableThreadLocal<String>()
15

oldratlee's avatar
oldratlee 已提交
16 17
    context.set("value-set-in-parent")
    println("[parent thread] set ${context.get()}")
18 19 20 21

    /////////////////////////////////////
    // Runnable / TtlRunnable
    /////////////////////////////////////
oldratlee's avatar
oldratlee 已提交
22
    val task = Runnable { println("[child thread] get ${context.get()} in Runnable") }
23 24 25 26 27 28 29 30
    val ttlRunnable = TtlRunnable.get(task)!!

    executorService.submit(ttlRunnable).get()

    /////////////////////////////////////
    // Callable / TtlCallable
    /////////////////////////////////////
    val call = Callable {
oldratlee's avatar
oldratlee 已提交
31
        println("[child thread] get ${context.get()} in Callable")
32 33 34 35 36 37 38 39 40 41 42
        42
    }
    val ttlCallable = TtlCallable.get(call)!!

    executorService.submit(ttlCallable).get()

    /////////////////////////////////////
    // cleanup
    /////////////////////////////////////
    executorService.shutdown()
}