Skip to content

Instantly share code, notes, and snippets.

@ghasemdev
Created January 25, 2024 14:03
Show Gist options
  • Save ghasemdev/d0de2e85c142e816e0c48bb14f3ace62 to your computer and use it in GitHub Desktop.
Save ghasemdev/d0de2e85c142e816e0c48bb14f3ace62 to your computer and use it in GitHub Desktop.
thread safe
val formatter by safeThread {
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS'Z'", Locale.getDefault())
}
fun main(): Unit = runBlocking {
val time = "2024-01-24T22:58:54:322Z"
launch {
launch {
withContext(Dispatchers.Default) {
repeat(1000) {
println(formatter.parse(time)?.time)
}
}
}
launch {
withContext(Dispatchers.Default) {
repeat(1000) {
println(formatter.parse(time)?.time)
}
}
}
launch {
withContext(Dispatchers.Default) {
repeat(1000) {
println(formatter.parse(time)?.time)
}
}
}
}
}
class SafeThreadLazy<T>(val provider: () -> T) : Lazy<T> {
private val threadLocal = object : ThreadLocal<Lazy<T>>() {
override fun initialValue(): Lazy<T> = lazy(LazyThreadSafetyMode.NONE, provider)
}
override val value get() = threadLocal.get()!!.value
override fun isInitialized() = threadLocal.get()!!.isInitialized()
}
fun <T> safeThread(provider: () -> T) = SafeThreadLazy(provider)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment