Thursday, August 24, 2017

Difference between Executor and Thread class in Java

Both Thread and Executor is  used to run your code in parallel and you can create and start your own thread either by extending java.lang.Thread class or implementing java.lang.Runnable interface. Though both approaches work well in small application, On the other hand, Executor is an interface which also provides parallel execution, but via a thread pool, which is more suitable for large Java application.

Thread vs Executor in Java


The other major differences could be:

1) First and foremost difference between Thread and Executor is that java.lang.Thread is a class in Java while java.util.concurrent.Executor is an interface.


2) The Executor concept is actually an abstraction over parallel computation. It allows concurrent code to be run in managed way. On the other hand, Thread is a concrete way to run the code in parallel.

3) The third difference between an Executor and a Thread class is that former decouples a task (the code which needs to be executed in parallel) from execution, while in the case of a Thread, both task and execution are tightly coupled.

4) The Executor concept allows your task is to be executed by a worker thread from the thread pool, while Thread itself execute your task.

Difference between a Thread and an Executor in Java

5) Executor provides a execute() method which accepts a Runnable task, while Thread accepts the Runnable task on its constructor.

6) One more key difference between a Thread and an Executor is that a Thread can only execute one Runnable task but an Executor can execute any number of Runnable task.

7) In the case of Thread, the task is executed by the Thread which accepts Runnable instance, but in the case of Execution the command (a Runnable implementation) may be executed in a new thread, a pooled thread or in the calling thread itself, depending upon the implementation of Executor interface.

8) In the case of a thread, it's developer's responsibility to create and start the thread, but in the case of Executor, the framework will create and start threads for you. Though you can control the whole process by giving your implementation of Executor interface. Though, with the improvements in ForkJoinPool in Java 7 and 8, you might want to use that instead of Executor. If ForkJoinPool is a new concept to you, I suggest reading Java 8 in Action to learn more about it.

Thread vs Executor in Java


7) Now, let's see an example of execution a Runnable task via Executor and via Thread in Java:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Main {

  public static void main(String args[]) {

    Runnable task = new Runnable() {
      @Override
      public void run() {
        System.out.println("Task is executed by : "
            + Thread.currentThread().getName());
      }
    };

    Thread t = new Thread(task, "Executer Thread");
    t.start();

    Executor e = Executors.newSingleThreadExecutor();
    e.execute(task);

  }
}

Output
Task is executed by Executer Thread
Task is executed by pool-1-thread-1

The difference is quite clear that first is just a thread while later is a pool of threads.

It's worth noting that factory methods of Executors class e.g. newSingleThreadExecutor() return an ExecutorService, which is sub-interface of Executor and also provides methods to accepts a Callable, terminate or shut down the thread pool.

That's it from my side. If you have some more points add it into the comments, I will add those in the post.

Happy reading and keep commenting :)
click to install Flipkart app

Friday, August 4, 2017

static vs volatile in java

 A very common interview question asked from mid level experience java developer and the question is: What is the difference between static and volatile variable in java?

So lets try to divide it in two parts:

 What is a Static variable in java:

Declaring a static variable in Java, means that there will be only one copy, no matter how many objects of the class are created. The variable will be accessible even with no Objects created at all. However, threads may have locally cached values of it.


What is volatile in java:

When a variable is volatile and not static, there will be one variable for each Object. So, on the surface it seems there is no difference from a normal variable but totally different from static. However, even with Object fields, a thread may cache a variable value locally.


Static and volatile are introduced for special purposes in java. Volatile keyword mainly used in multi threading environment. How?

Declaring a variable as volatile (be it static or not) states that the variable will be accessed frequently by multiple threads. In Java, this boils down to instructing threads that they can not cache the variable's value, but will have to write back immediately after mutating so that other threads see the change. (Threads in Java are free to cache variables by default). 

 help my cause here 

An additional interesting question would be: Is there a difference between a static and a static volatile variable?

static variable is stored once per class. A static volatile variable is stored once per class and will be accessed frequently by multiple threads, i.e. reads cannot be cached.


Even if you access a static value through multiple threads, each thread can have its local cached copy! To avoid this you can declare the variable as static volatile and this will force the thread to read each time the global value.
However, volatile is not a substitute for proper synchronization!


These are the basic differences between static and volatile as I can think off.

Please do add a comment if you found some other difference, I will add them in this post.

Thanks for reading.

We have another website: HowToSaveMoney and OnePaisa.in

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...