Created
January 25, 2024 14:03
-
-
Save ghasemdev/d0de2e85c142e816e0c48bb14f3ace62 to your computer and use it in GitHub Desktop.
thread safe
This file contains 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
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) | |
} | |
} | |
} | |
} | |
} |
This file contains 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
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