Warning: Use of undefined constant fixed - assumed 'fixed' (this will throw an Error in a future version of PHP) in /home/webtro13/domains/farenda.com/public_html/wp-content/themes/moments/header.php on line 65
class="header_container_flat">

One way to prevent concurrent modifications from different Threads is to given them their own local data. Java ThreadLocal allows to do thread data separation.

ThreadLocal holder

Let’s write a simple class that will hold ThreadLocal variable for each thread. We’ll use ThreadLocal.withInitial(Supplier<? extends T>) static factory method to create an instance of ThreadLocal with initialValue throwing exception, because in our case having customer is required:

Note that access to customer ThreadLocal through get() and set(String id) methods is not synchronized. ThreadLocal takes care of that.

Example Java Application

To test the above code we’ll use ExecutorService to start a few worker threads each of which will process own customer.

Worker accessing ThreadLocal

Simple Worker thread that stores current customer in ThreadLocal variable, does processing (calling a number of layers below that access the same ThreadLocal variable) and shows current customer id at the end: