java - Usage of ThreadLocal when no shared objects exist -



java - Usage of ThreadLocal when no shared objects exist -

i given code contains classes utilize theadlocal.

here sample implementation:

public class myclass { public myclass() { } // class methods.. private static threadlocal<myclass> factorycache = new threadlocal<myclass>() { public synchronized myclass initialvalue() { homecoming new myclass(); } public synchronized myclass get() { homecoming super.get(); } public synchronized void set(myclass value) { super.set(value); } }; public static myclass get() { homecoming factorycache.get(); } }

notice in order utilize class static getter called: myclass.get(); ensure instance corresponds current running thread.

my question - class contains no members nor static variables, meaning there no shared objects in class level. in case - i'm wondering if utilize of threadlocal here has advantage. let's assume utilize class singletone (removing threadlocal part), each thread create own stack when entering method (right?), there point of using threadlocal in such case?

additional info - web application handles many concurrent http requests , issued class used per http request.

thread safety shared state. if class doesn't have state share between threads, don't need worry thread safety.

so, if class has no fields, can safely share same instance of class between multiple threads (singleton), or create methods static (as it's done various utility classes).

it won't cause problem, because, correctly noted, each thread has own stack, hence local variables cannot shared between threads in way.

java multithreading concurrency thread-local

Comments

Popular posts from this blog

php - Android app custom user registration and login with cookie using facebook sdk -

django - Access session in user model .save() -

php - .htaccess Multiple Rewrite Rules / Prioritizing -