When multiple threads execute a single instance of a program and therefore share memory, multiple threads could possibly be attempting to read and write to the same place in memory.If we have a multithreaded program, we will have multiple threads processing the same instance.What happens when Thread-A examines instance variable x? Notice how Thread-B has just incremented instance variable x. The problem here is Thread-A has written to the instance variable x and is not expecting that value to change unless Thread-A explicitly does so. Unfortunately Thread-B is thinking the same thing regarding itself; the only problem is they share the same variable.
First method to make a program threadsafe: Avoidance
To ensure we have our own unique variable instance for each thread, we simply move the declaration of the variable from within the class to within the method using it. We have now changed our variable from an instance variable to a local variable. The difference is that, for each call to the method, a new variable is created; therefore, each thread has its own variable. Before, when the variable was an instance variable, the variable was shared for all threads processing that class instance. The following thread-safe code has a subtle, yet important, difference. This only applies to primitives. When it comes to actual Objects, the local variable does not make the program thread-safe since the variable just holding the reference to the unique object.
Second defense:Partial synchronization
Thread synchronization is an important technique to know, but not one you want to throw at a solution unless required. Anytime you synchronize blocks of code, you introduce bottlenecks into your system. When you synchronize a code block, you tell the JVM that only one thread may be within this synchronized block of code at a given moment. If we run a multithreaded application and a thread runs into a synchronized code block being executed by another thread, the second thread must wait until the first thread exits that block.
It is important to accurately identify which code block truly needs to be synchronized and to synchronize as little as possible. In our example, we assume that making our instance variable a local variable is not an option.
Third Defence: Whole synchronization
Here u should implement an interface which make the whole class a thread safe on or synchronized
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment