Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Wednesday, February 22, 2017

How to create thread safe classes in Java


Thread safety in java is the process to make our program safe to use in multi threaded environment, there are different ways through which we can make our program thread safe.

1) Synchronization is the easiest and most widely used tool for thread safety in java.

2) Immutable objects are by default thread safe because there state can not be modified once created. For example, String class is immutable in java which inherently thread-safe.

3) Use of Atomic Wrapper classes from java.util.concurrent.atomic package. Atomic operations in Java are thread-safe. For example AtomicInteger.

4) Use of locks from java.util.concurrent.locks package.

5) Using volatile keyword with variables to make every thread read the data from memory, not read from thread cache. 

6) Using thread safe classes for thread safety. Example of thread-safe class in Java: Vector, Hashtable, ConcurrentHashMap, String etc.


7)  Locking is one way of achieving thread-safety in Java.

Friday, January 29, 2016

Volatile and Synchronized in Java

Volatile and Synchronized in Java


This can be best understood by looking at the effects that volatile & synchronized on a method. volatile is a field modifier, while synchronized modifies code blocks and methods. So we can specify three variations of a simple accessor using those two keywords:
int i1; int geti1() {return i1;}
volatile int i2; int geti2() {return i2;}
int i3; synchronized int geti3() {return i3;}
geti1() accesses the value currently stored in i1 in the current thread. Threads can have local copies of variables, and the data does not have to be the same as the data held in other threads. In particular, another thread may have updated i1 in it’s thread, but the value in the current thread could be different from that updated value. In fact Java has the idea of a “main” memory, and this is the memory that holds the current “correct” value for variables. Threads can have their own copy of data for variables, and the thread copy can be different from the “main” memory. So in fact, it is possible for the “main” memory to have a value of 1 for i1, for thread1 to have a value of 2 for i1 and for thread2 to have a value of 3 for i1 if thread1 and thread2 have both updated i1 but those updated value has not yet been propagated to “main” memory or other threads.
On the other hand, geti2() effectively accesses the value of i2 from “main” memory. A volatile variable is not allowed to have a local copy of a variable that is different from the value currently held in “main” memory. Effectively, a variable declared volatile must have it’s data synchronized across all threads, so that whenever you access or update the variable in any thread, all other threads immediately see the same value. Of course, it is likely that volatile variables have a higher access and update overhead than “plain” variables, since the reason threads can have their own copy of data is for better efficiency.
Well if volatile already synchronizes data across threads, what is synchronized for? Well there are two differences. Firstly synchronized obtains and releases locks on monitors which can force only one thread at a time to execute a code block, if both threads use the same monitor (effectively the same object lock). That’s the fairly well known aspect to synchronized. But synchronized also synchronizes memory. In fact synchronized synchronizes the whole of thread memory with “main” memory. So executing geti3() does the following:
The thread acquires the lock on the monitor for object this (assuming the monitor is unlocked, otherwise the thread waits until the monitor is unlocked).
The thread memory flushes all its variables, i.e. it has all of its variables effectively read from “main” memory (JVMs can use dirty sets to optimize this so that only “dirty” variables are flushed, but conceptually this is the same. See section 17.9 of the Java language specification).
The code block is executed (in this case setting the return value to the current value of i3, which may have just been reset from “main” memory).
(Any changes to variables would normally now be written out to “main” memory, but for geti3() we have no changes.)
The thread releases the lock on the monitor for object this.
So where volatile only synchronizes the value of one variable between thread memory and “main” memory, synchronized synchronizes the value of all variables between thread memory and “main” memory, and locks and releases a monitor to boot. Clearly synchronized is likely to have more overhead than volatile.
Using the volatile keyword ensures that the variable is never kept in a register. This guarantees that the variable is truly shared between threads.
Synchronization boundaries signal to the virtual machine that it must invalidate its registers.
When the virtual machine enters a synchronized method or block, it must reload data it has cached in its local registers. Before the virtual machine exits a synchronization method or block, it must store its local registers to main memory.

Difference between “implements Runnable” and “extends Thread” in Java

Difference between “implements Runnable” and “extends Thread” in Java


1. Inheritance Option:   The limitation with “extends Thread” approach is that if you extend Thread,  you can not extend anything else . Java does not support multiple inheritance.  In reality , you do not need Thread class behavior , because in order to use a thread you need to instantiate one anyway.
On the other hand,
Implementing the Runnable interface gives you the choice to extend any class you like , but still define behavior that will be run by separate thread.
2. Reusability :  In “implements Runnable” , we are creating a different Runnable class for a specific behavior  job (if the work you want to be done is job). It gives us the freedom to reuse the specific
behavior job whenever required.
“extends Thread”  contains both thread and job specific behavior code. Hence once thread completes execution , it can not be restart again.
3. Object Oriented Design:  Implementing Runnable should be preferred . It does not specializing or modifying the thread behavior . You are giving thread something to run. We conclude that Composition is the better way. Composition means two objects A and B satisfies has-a  relationship.
“extends Thread”  is not a good Object Oriented practice.
4. Loosely-coupled : “implements Runnable” makes the code loosely-coupled and easier to read .
Because the code is split into two classes . Thread class for the thread specific code and your Runnable implementation class for your job that should be run by a thread code.
“extends Thread”  makes the code tightly coupled . Single class contains the thread code as well as the job that needs to be done by the thread.
5. Functions overhead :  “extends Thread”  means inheriting all the functions of the Thread class which we may do not need .  job can be done easily by Runnable without the Thread class functions overhead.
Example of  “implements Runnable” and “extends Thread” 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<div>
<pre>public class RunnableExample implements Runnable {
     
    public void run() {</pre>
<pre>        System.out.println("Alive is awesome");</pre>
<pre>    }</pre>
<pre>}
 
</pre>
</div>
<div>
<pre>public class ThreadExample extends Thread {
     
    public void run() {</pre>
<pre>        System.out.println(" Love Yourself ");</pre>
<pre>   }</pre>
<pre>}
Recap : Difference between “implements Runnable”  and “extends Thread”
 implements Runnable extends Thread
Inheritance optionextends any java classNo
ReusabilityYesNo
Object Oriented DesignGood,allows compositionBad
Loosely CoupledYesNo
Function OverheadNoYes

Difference between Sleep and Wait method in Java

Difference between Sleep and Wait method in Java

1.  Class  belongs :  The wait() method belongs to java.lang.Object class, thus can be called on any Object. The sleep() method belongs to java.lang.Thread class, thus can be called on Threads.
2. Context :  The wait() method can only be called from Synchronized context i.e. using synchronized block or synchronized method. The sleep() method can be called from any context.
3. Locking :  The wait() method releases the lock on an object and gives others chance to execute. The sleep() method does not releases the lock of an object for specified time or until interrupt.
4. Wake up condition :  A waiting thread can be awake by notify() or notifyAll() method. A sleeping can be awaked by interrupt or time expires.
5. Execution :  Each object has each wait() method for inter-communication between threads. The sleep() method is static method belonging to Thread class. There is a common mistake to write t.sleep(1000) because sleep() is a class method and will pause the current running thread not t.

Recap  : Difference between Sleep and Wait in Java 
SleepWait
Class  belongsjava.lang.Threadjava.lang.Object
ContextCalled from any contextOnly synchronized context
LockingDoes not release the lock
for specified time  or until
interrupt.
Releases the lock
Wake up ConditionWhen time expires or
due to interruption
Awake by call to notify()
or notifyAll() method
ExecutionExecution of sleep will
pause the current running
thread not the object on which
it is called.
Thread wait()
continues till a specific condition
holds true