jay's old blog

this blog will be deleted soon - please visit my new blog - https://thesanguinetechtrainer.com

Threads – Static Variables and Information and Pool

Earlier we told about shared variables. That is good when you don’t mind a the variable being shared. However, there will be times when you want each thread to have its own variable. This is useful when you are using many threads but want to ensure that each of them get their own copy. That is when you use static variables.  

It is kind of ironic that this is called static variables because static methods end up becoming unique.  

Of course, you must remember that this is an attribute rather than a keyword like private, public or even static.  

        public static int static_count = 0; 

Also, if you want to collect information about the current, you can use the CurrentThread option. Here you go. 


This is useful when you want to get more information about your thread itself. For debugging and reporting purposes.  

Then there is this thread pool thing  


In this case, thread pool is like a collection of threads that you can use, from a pool. Now, the question is, why a pool? When you think about it, the whole memory itself is like a pool. When you create a new thread, you ask the memory to create a thread for you. The thing with the thread pool is, it allows an overload of threads. 

To understand that, lets think of this. Suppose, your computer has a capacity of only a 100 threads. Then, you request threads and you request some more. Eventually, you hit the 100th thread. The program is still working just fine. However, when you request for the 101st thread, things could go wrong. It could get very wrong. That's because the program has made a request and the memory component will try its darn best, even if it means killing the program.  

That is where the thread pool comes into the picture. When you use a thread pool, an attempt to assign a thread is assign only if it's available. If the thread pool has threads to give out, it will do so. Otherwise the request will be put on wait. This way, the program won't crash.  

As always, find the code at our repo. 

Comments are closed