Thread Safety

Is a static method thread safe? Is a static method a bottleneck?

First, let’s go shopping.

Let’s say I take a grocery cart of 10 items into a checkout lane at my local grocery store. The clerk takes each item from my cart and computes a total cost for all the items. Unless there was a human error (or an item was priced incorrectly), we would expect the clerk’s cash register to compute the correct total.

The clerk is like a thread. Like a thread in an application, the clerk executes a set of instructions to compute the total cost of my grocery items. The clerk will process one cart of items at a time, and each will make use of a cash register to tally the items.

Now picture a different scenario. Picture 5 checkout lanes, each lane with one clerk, but only one shared cash register for the entire store. If multiple clerks are ringing up items on the shared cash register for different shoppers at the same time, nobody will receive the correct total. My clerk might ring up two items and then pause for a second, which allows a second clerk to come in and add another shopper’s item to the current list in the cash register. The total cost for items in my cart would be incorrect. This is an analogy of what can happen if a method is not thread safe – corrupted data.

The solution to the shared cash register problem is to ensure a clerk will have exclusive possession of the single cash register while totaling my order. No other clerks are allowed to use the register until my 10 items are finished. These steps will produce the correct results, but as you might imagine, it can make for long lines at the checkout. Everyone is waiting on this one cash register to come free. This is an analogy of what can happen to the scalability of an application when threads are locked while waiting for a shared resource.

There is a delicate balance to strike when writing code that is both high performance and thread safe with shared resources.

Comments

Popular posts from this blog

മലയാളത്തില്‍ മൊത്തം എത്ര അക്ഷരങ്ങള്‍ ഉണ്ട്?

Convert Number To Words in SQL Sever

Crystal reports load report failed: Could not load file or assembly CrystalDecisions.Web, Version=10.2.3600.0