ThreadLocal, what an useful class. I’ve used it several times, I know what it allows me to do, but yet I don’t know how it is, actually, implemented, so in detail, what does it offers me?
ThreadLocal is another way to achieve thread safety without immutable classes or explicitly synchronise access to memory between threads.
Looking at the implementation, essentially, it uses a map in the current Thread to hold all ThreadLocal objects. This way, we never need to worry about the values in other Threads and therefore have no concurrency issues. Furthermore, once the
Thread is done and GC runs, its map will freed from memory, also as all the local objects.
ThreadLocal has many genuine use cases, however, if you are not in concurrent programming, you will rarely use it. In general sense one could use ThreadLocal in a multithreaded application whenever we just need to use memory accessible to the current thread only (Thread confined memory). For example, per Thread singleton classes or per thread context information like transaction id.
So instead of controlling the access to different objects (different memory areas), the developer could use ThreadLocal instances as a common code still accessing to different memory areas. That allows to simplify your code and still keep it thread-safe.
© 2019 Joao Melo's Blog | Theme by Eleven Themes