carrier local
Alan Bateman
Alan.Bateman at oracle.com
Fri Apr 3 07:32:27 UTC 2020
On 02/04/2020 21:05, Thomas May wrote:
> LongAdder would be a good example where you'd want carrier local storage rather than thread local. Having it ThreadLocal would allocate more memory than necessary.
>
> Another example is SimpleDateFormat.
>
> In fact, I'd think whenever you are using ThreadLocals to avoid synchronization you probably would be happy using carrier local instead of ThreadLocal.
>
SimpleDateFormat is a good example to discuss as an instance is
expensive to create and it's not thread safe. It's also not too hard to
find code that caches an SimpleDateFormat instance in a TL.
The intention is that you can cache a SimpleDateFormat in a TL and
access it without synchronization as before. Yes, this would be a lot of
memory with 1M threads. If there was an unsafe like method to get a
reference to the carrier thread's TL then you would have to synchronize,
consider this:
SimpleDateFormat format = <SimpleDateFormat object cached by carrier
thread local>
format.format(...);
socket.read(...) // scheduling point, may park
format.format(...)
If several virtual threads execute this at, or around, the same time and
you'll quickly see SimpleDateFormat being accessed from different kernel
threads without synchronization, oops!
A good migration path for ThreadLocal<SimpleDateFormat>, to reduce
memory usage, is to move to java.time.format.DateTimeFormatter. It's
immutable and thread-safe, and faster to create too.
-Alan
More information about the loom-dev
mailing list