Are static classes shared by threads?

7

Are static classes, methods, and properties shared across the application's threads?

That is, if I modify the static property foo in ThreadA , and then modify the same static property foo in ThreadB , what will be the value of property foo ? Will it be different for each thread or will the value set in ThreadB prevail? In the latter case, is there any configuration that can be performed to define that the static class will be thread ?

    
asked by anonymous 16.06.2016 / 15:32

2 answers

6

Yes, they are shared by every application, independent of threads . For this reason, static data is inherently not thread-safe .

One of the reasons people say to avoid using it, or when it does, is to do it safely, taking care to synchronize access.

I think it's obvious, at least for this aspect, that static objects are not problematic if you do not have more than one thread in the application.

The static property value will always be the last assigned by any of the threads . At the time of the change all the threads see the new value immediately since it is the same location.

Note that in WebAPI requests, depending on how you are configured, you may be running different instances of the application. That is, different processes, there is no communication between them.

If you want to create a static class like gambiarra to fix a current design issue, I would recommend not doing so. Static classes are great when they make sense, when they are really unique things that should be global. You need to have a semantics (there are several) to justify their use.

The concrete problem is not yet clear. So it's hard to say if this case can be solved well with the use of a static class. But it seems to me that the thread pool of the WebAPI can be a complicator and I would not use it.

    
16.06.2016 / 15:42
3

Are static classes, methods, and properties shared between application threads?

  

Yes, but not only static members, but also any member of a class, static or not, can be shared between threads.

Is there any configuration that can be performed to define one value per thread?

  

Yes. You can create a variable, static or not, that has a unique value for each thread by using the ThreadLocal .

Example:

static ThreadLocal<String> valorThreadLocal = new ThreadLocal<string>();

Now, a value set to valorThreadLocal.Value will only be retrieved when read inside the same thread as set, so each thread has its own value in valorThreadLocal .

We say in this case that the value of valorThreadLocal is local to the current thread.

    
16.06.2016 / 17:07