In Java, we have the ThreadLocal
class:
This class provides thread-local variables. These variables differ from their normal counterparts in that each thread that accesses one (via its
get
orset
method) has its own, independently initialized copy of the variable.ThreadLocal
instances are typicallyprivate static
fields in classes that wish to associate state with a thread (e.g., a user ID or Transaction ID).
Example:
private static final ThreadLocal<StringBuilderHelper>
threadLocalStringBuilderHelper = new ThreadLocal<StringBuilderHelper>() {
@Override
protected StringBuilderHelper initialValue() {
return new StringBuilderHelper();
}
};
Is there any equivalent in Objective C or Swift to simulate this behavior? Can i just use on Swift:
static let String = someInitialValue()
and achieve the same goal?
The Java ThreadLocal class enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to the same ThreadLocal variable, the two threads cannot see each other's ThreadLocal variables.
In 2009, some JVMs implemented ThreadLocal using an unsynchronised HashMap in the Thread. currentThread() object. This made it extremely fast (though not nearly as fast as using a regular field access, of course), as well as ensuring that the ThreadLocal object got tidied up when the Thread died.
Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log.
You should always call remove because ThreadLocal class puts values from the Thread Class defined by ThreadLocal. Values localValues; This will also cause to hold reference of Thread and associated objects. the value will be set to null and the underlying entry will still be present.
Have a look at NSThread threadDictionary
. I believe this is roughly the same thing.
A typical use in Objective-C might be:
NSMutableDictionary *threadData = [[NSThread currentThread] threadDictionary];
threadData[someKey] = someObject; // write
someObject = threadData[someKey]; // read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With