Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent on Objective C/Swift of Java ThreadLocal Variables

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 or set method) has its own, independently initialized copy of the variable. ThreadLocal instances are typically private 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?

like image 579
Cayoda Avatar asked Apr 05 '16 16:04

Cayoda


People also ask

What is ThreadLocal variable in Java?

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.

Is ThreadLocal slow?

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.

Does MDC use ThreadLocal?

Internally, MDC uses ThreadLocal and it has some predefined functionalities like adding a prefix to every log.

When should ThreadLocal be removed?

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.


1 Answers

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
like image 50
rmaddy Avatar answered Sep 17 '22 19:09

rmaddy