Monday, November 26, 2012

Oracle Instant Client & How to Install it ?

Install client allows you to run your application without installing oracle client or having an ORACLE_HOME.
It is easy to install client software for connecting to Oracle databases.It's available on all the platforms

Main purpose behind Oracle Instant Client : no need of oracle client installation on your machine for accessing the oracle server.It is alternative of oracle client installation with very less space .

It Consist of following packages :
  1. Basic : It provide the core functionality for all OCI,OCCI,and JDBC OCI applications.(around 97 MB)
  2. Basic Lite : Smaller version of the Basic  with only English error messages and code. Smaller size also.
  3. JDBC supplements :Additional support for XA, Internationalization, and RowSet operations under JDBC
  4. SQL*PLUS
  5. ODBC supplements
  6. SDK
By Contrast , the full oracle client installation consume about 700 MB space where as this Instant Client 97MB

Features :
    • take less space 
    • SQL*PLUS can be used with Instant Client.
    • No Reliance on typical Oracle CD installation'
    • Ease of deployment
    • same functionality as we have with Oracle client.
    • same high performance as we have with Oracle Client
    • No cost

From where we get this ?
Directly from the oracle site.
Download from the following locations as per your platform need :
http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html

How to install it ?
Here i am going to show you how to install Instant Client and SQL*PLUS on Fedora 15.

Package i have used :

Steps: 
  1. Download the required files as i have mentioned above based on your platform.
  2. Login as super user
  3. Run the rpm packages as follow 
    1. Go the directory where package was downloaded.
    2. Change the mode of the rpm file
      • chmod +x oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
    3. Execute the rpm file
      •  rpm -ivh oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm
Follow the same step for oracle-instantclient11.2-sqlplus-11.2.0.3.0-1.x86_64.rpm.
This process create a oracle folder with necessary files in /usr/lib directory i.e /usr/lib/oracle.

Next step :
How to set ORACLE_HOME & LD_LIBRARY_PATH ? see here for more details.
Set the following configuration :

  export LD_LIBRARY_PATH=/usr/lib/oracle/11.2/client64/lib
  export TNS_ADMIN=/usr/lib/oracle/11.2/client64
  export ORACLE_HOME=/usr/lib/oracle/11.2/client64
  export PATH=$PATH:/usr/lib/oracle/11.2/client64/bin

Finally your Oracle Instant Client is ready . Try sqlplus command.

How to connect to Oracle Server ?

  1. mkdir -p $ORACLE_HOME/network/admin
  2. cd [ directory containing tnsname.ora & sqlnet.ora]
  3. cp tnsname.ora sqlnet.ora $ORACLE_HOME/network/admin

For example your tnsname.ora contain :
latte=(DESCRIPTION = (ADDRESS =
                      (PROTOCOL = TCP)
                      (HOST = localhost)
                      (PORT = 1521))
                    (CONNECT_DATA =
                      (SERVICE_NAME = latte)
                      (SERVER = DEDICATED)))

Use this command for connecting to latte Oracle Server :
sqlplus username/password@latte.



Troubleshooting 
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory

if you get this error, please make sure that there should not be / as the end while declaring ORACLE_HOME.


if you find this information useful, please comment.

How to set PATH in Linux/Solaris ?

PATH can be ORACLE_HOME, JAVA_HOME, CATALINA_HOME ,etc but steps to set will be same.

There are three types file you will encounter when working on Linux,Solaris & Mac-OS.

  1. .bash_profile --linux
  2. .profile         --Solaris
  3. .bashrc
For setting the path variable in Linux/Solaris follow the steps as below
  1. Go to the home directory or go by typing cd , then press enter .
  2. Here I am using ORACLE_HOME just for the demonstration , you can set any path like this.
  3. Open the profile, for example : vi .bash_profile
  4. Write
    • ORACLE_HOME=/usr/lib/oracle/11.2/client64
    • export ORACLE_HOME
  5. Save it .
  6. Execute it
    • . ~/.bash_profile
Check the Oracle Home by echo $ORACLE_HOME

For more demonstration on how to install Java on Linux . Please see my post on how to install java on Linux.


if you find this information useful, please comment.

Sunday, November 25, 2012

Case Sensitivity while declaring a database object in Oracle

Database objects are case-sensitive & will be treated as though they are typed in upper case.
This is generally true - but there is exception and its depends on whether you use double quotes " or not.


  • If a name is not enclosed in a double quotes, then it will be treated as uppercase regardless of how is created or referenced.
  • If a name is enclosed in a double quotes, then it is case sensitive and must always will be referenced with case sensitivity and double quotes
CREATE TABLE latte(Name Varchar2(20));

The database will automatically convert latte into LATTE.So you can reference table as 

Select * from latte;
            OR
Select * from LATTE;

CREATE TABLE "latte" (Age NUMBER);
Then every future reference will require double quotes and case sensitive reference to this.

Select * from "latte"; will work.
But
Select * from LATTE; not work. 

Not either this one
Select * from latte.

There is more !!! By using double quotes, you can also include special character that are otherwise not allowed -- space.
This will work
CREATE TABLE "java latte"(name varchar2(20));


What is a Schema in Oracle ?

This is one of the basic question we mostly encounter in RDBMS questions.

What is a Schema ?
A Schema is a collection of certain database objects  such as tables, index , and views, all of which owned by a user account.

You can think of schema as being the same thing as user account, but there is a little difference b/w them.
user account houses the object own by a user and schema is a set of objects housed therein. 
Definition you will find in a oracle documentation - "logical collection of database objects".

Ideally a "schema" should not be a random collection of objects, but the fact that there is nothing built into oracle that prevents user from doing that- randomly collecting objects into a user account.
A user account should be seen and used as logical collection of database objects,driven by business rules,collected into one organized entity- the schema.

A Schema has the same name as the user account. But it entirely possible to create a schema whose owner is not a human being at all, but perhaps a background application.

Schema and Non-Schema Objects ?
All database objects fall into 2 category or types.

  • Schema
  • Non-Schema

"Schema" objects are those objects own by a user account.
"Non-schema" objects cannot owned by user account.
For example, USER is non-schema objects .Think about it, how can a user account own itself.

Schema Objects                   Non-Schema Objects
Tables                               Users
Constraints                        Roles
Indexes                             Public Synonyms 
Views
Sequence
Private Synonyms

Thursday, November 22, 2012

Why Character Array is preferred over String for Storing password in Java

In this post, we'll see few reasons why char array is always preferred over String for storing password.


As you know, both string and char array is used to store textual data but choosing one over the other is more difficult. May be you can get the idea from the immutability of String why char array is preferred over string for storing the password.

1. With plain String you have much higher chance of accidentally printing the password to logs or some other insecure places. where char[] is less vulnerable. 
For example :
Output :
String=password_of_blog
array=$%(Q($_#(QQ#

Since string is immutable i.e. there is no method defined that allow you to change or overwrite the content of string. This feature make string object unstable for storing the secure information such as user password.
You should always store or collect secure information in char [] array rather than string.

2. Since string is immutable if you store password as plain text it will be available in memory until Garbage collector clean it. Since string used string pool for re-usability of string, there will be pretty chance that it will remain in memory for long duration. 
Since any one who has access to memory dump can easily find the password in plain text that's the another reason use should use encrypt password than plain text.

3. The official document of Java Cryptography Architecture guide says about char [] vs string password

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

4. If you notice in swing application, there is method of JPasswordField i,e  getPassword() which return char[] and the deprecated method getText() which return the password in plain text. So java itself recommending to use the getPassword() method.


5. Other reason for storing passwords in character array, because char[] can be sanitized, e.g. after usage one can override clear password with junk, while string is immutable in java


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Why Java does not support Multiple Inheritance

Consider the one of the goal behind the java Language :
  • Simple,object oriented and familiar 

The reason behind omitting the Multiple inheritance from the java language is mostly from the "Simple ,objected oriented & familiar" goal.
Java people want the java language to be simple so that most of developer learn easily.They make the language similar to c++ as possible without carrying the complexity from c++ language.

Java does not support multiple inheritance

This is the main point of discussion whether java support multiple inheritance or not. There is big misconception that, java support multiple inheritance through interface. Answer is NO. Java does not support multiple inheritance at all. If you don't believe this read the first goal of java :).

Basically interface give the flexibility over concrete class and we have the option of implementing multiple interface.
Implement class is the one that is going to add properties and behavior. It is not getting the implementation from the parent class. But, in multiple inheritance we are inheriting the properties & behavior from multiple classes in a single class.

Now we are sure that there is no support for multiple inheritance in java. 
Reasons are as follow :

Simplicity 

In order to enforce simplicity is one the main reason for omitting the multiple inheritance.
We can consider the ambiguity of Diamond problem
Consider a class A with latte() method and then class B and class C derived from class A and has own latte() method implementation.
Consider class D derive from Class B & Class C using multiple inheritance.

If we refer to latte() method, compiler will not able to decide which latte() method.

This is called the Diamond problem.

                             Class A----latte()

                          /                           \
                                   /                              \
Class B -- latte()                                 Class C --latte()
                        \                             /
                         \                           /
                             Class D --latte()

In java this can never be occur because there is not multiple inheritance in java.

Here if even two interfaces going to be have the same method, the implementing class is going to have the one method and that will take care by the implementer class.

A language that allows the the Deadly diamond of Death can lead to some ugly complexities, because you have to have special rules deal with the potential ambiguities. And extra rules means extra work for you both in learning those rules and watching out for those "special rules. Java is supposed to be simple with consistent rules that don't blow up under some scenarios. So java protects you from having  to think about the Deadly Diamond of Death.


Complex design & rarely used
Multiple inheritance make the design complicate and create problem during casting & constructor chaining. 
There are not many scenario where you need multiple inheritance its wise decision to omit for the sake of simplicity.
Also java omit this ambiguity with the help of supporting single inheritance with interface. Since interface has only method declaration and does not provide any implementation there will be only one implementation of  specific method.

Now with Java 8, the interface body can contain abstract methodsdefault methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation). 

QAgain one question come to mind that if two interface are providing default method with similar signatures and class is extending both the interface, will it not be again diamond problem?
Yes, you are thinking right but Java doesn't allow you to implement interface with has same default method.


If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Sunday, November 18, 2012

Operator overloading in Java

Java doesn't allow the programmer to overload operators e.g. +,-,/,*. Java left some of the features that are supported in C++ e.g. no pointers in Java , no pass by reference in Java and no support for multiple inheritance .




Most people will think that + is overloaded in Java . For example
int a=4+3;
String blog="java"+"latte";
+is used for for addition and string concatenation.
Here is the misunderstanding what operator overloading actually means.

While technically speaking, Java does not support operator overloading at all. The behavior of the two '+' operator with respect to String and numeric type do give the appearance of single operator overload with respect to programmer aspect. 
This is fundamentally different from operator overloading defined by C++ and C# for example.

Let me give you an example

The Java language provide the special support for string concatenation operator (+). String concatenation is implemented through the StringBuffer ( or String Builder ) class and its append methods. String conversions are implemented the string method toString(), defined by Object class and inherited by the all java classes. 

Unlike c++, this is compile time operation ... not operator overloading.when you type.....


String blog="Java-"+"latte"+".blogspot."+"in"+5;


compiler change this to


String blog=new StringBuilder("Java-").append("latte").append(".blogspot.").append("in").append(new Integer(5).toString()).toString().


This is not operator overloading. It is also not a runtime expression.It is not a part of string class. 
You can think of it as macro being expanded at compile time if you compare it to something from C++ perspective.

Most basic reason behind not supporting operator overloading is 


1. Simplicity and cleanliness 

C++ has proven by example that operator overloading makes code almost impossible to maintain.Simple and clear design is goal of the Java designer,they don't want to replicate the language but want to have clear, truly OO language. Operator overloading make the design complex and also slow the JVM because it need to do extra work to identify the actual meaning of operator and reduce the opportunity to optimize language by guarantee behavior of operator in Java.

2. Avoid programming Error

If you allow programmer to do operator overloading they will come with different meaning of the same operator, it will make difficult to learn and make things more confusing and messing.

3. JVM complexity

From JVM perspective operator overloading is more difficult. If same thing can be achieved by using method overloading in more intuitive and clean way, it does not make sense to support operator overloading.

Conclusion:

Things which can be achieved through operator overloading can be achieved through method overloading using more intuitive and clean way, that might be the reason behind not supporting operator overloading.

When Java Developer explains to developer why operator overloading is useless.





Friday, November 9, 2012

Java String Interview Questions

Questions on String class is most importance topic for any core java or J2EE interviews. It doesn't matter whether application is core java desktop application,web application,mobile application and or any Enterprise application. String is one the fundamental of java programming.

I Will try add as many question that are most important respective to String class and I will also try to give you the internal picture of String Class and some performance tips.


If you know anyone who has started learning Java, why not help them out! Just share this post with them.Thanks for studying today!...

Wednesday, November 7, 2012

ThreadLocal in Java

One of the most critical aspects of a concurrent application is shared data. This has special importance in those objects that extend the Thread class or implement the Runnable interface. If you create an object of a class that implements the Runnable interface and then start various Thread objects using the same Runnable object, all the threads share the same attributes. This means that, if you change an attribute in a thread, all the threads will be affected by this change.
Sometimes, you will be interested in having an attribute that won't be shared between all the threads that run the same object. The Java Concurrency API provides a clean mechanism called thread-local variables with a very good performance.

We use ThreadLocal when you have some object that is not thread-safe, but you want to avoid synchronizing access to that object. Instead, we give each thread its own instance of the object. There are many Different ways of implementing thread safe operation like :
What is Thread Safe
Thread is a single line of process when there is multi-threading applications, we means there are multiple process that run through the same line of code. In such situation, there is a chance that one thread will modify/accessing the data of another thread. When data cannot be shared like this, then we make the operation thread safe.

Core concept of ThreadLocal is that every thread that access the ThreadLocal variable through get and set methods of ThreadLocal has own, independently initialized copy of the variable. This class provide the thread-local variables.
How does this thread-local variable differ from their counterpart normal variable is that in each thread that access thread-local variable via its methods has its own,independently initialized copy of the variable. ThreadLocal instance are privately static fields in classes that wish to associate state with a thread.It can be accessed from anywhere inside a thread.

ThreadLocal is a thread-scope like scopes in JSP(session scope).You can set any object in ThreadLocal and this object will be global and local to specific thread which is accessing the object.

  • Global means they can be accessed from anywhere inside the thread if a thread call a methods from different classes, then all the methods can see the ThreadLocal variable set by others methods because they are executing in a same thread. 
  • Local means that each thread will have its own thread local variable.One thread can not access/modify other thread local variable.

Getting ready..
In order to understand the concept, we will develop a program that has the problem exposed as discussed above and another program that solves this problem using the thread-local variables mechanism.
Output:
Starting thread 8 : Sat Aug 09 13:39:32 IST 2014
Starting thread 9 : Sat Aug 09 13:39:34 IST 2014
Starting thread 10 : Sat Aug 09 13:39:36 IST 2014
Thread finished 8 : Sat Aug 09 13:39:36 IST 2014
Starting thread 11 : Sat Aug 09 13:39:38 IST 2014
Thread finished 9 : Sat Aug 09 13:39:38 IST 2014
Starting thread 12 : Sat Aug 09 13:39:40 IST 2014
Thread finished 10 : Sat Aug 09 13:39:40 IST 2014
Thread finished 11 : Sat Aug 09 13:39:40 IST 2014
Thread finished 12 : Sat Aug 09 13:39:40 IST 2014

In the above output, you can see the results of this program's execution. Each Thread has a different start time but, when they finish, all have the same value in its startDate attribute.

Now,we are going to use the thread-local variables mechanism to solve this problem.
Output:
Starting thread 8 : Sat Aug 09 13:49:25 IST 2014
Starting thread 9 : Sat Aug 09 13:49:27 IST 2014
Starting thread 10 : Sat Aug 09 13:49:29 IST 2014
Thread finished 8 : Sat Aug 09 13:49:25 IST 2014
Starting thread 11 : Sat Aug 09 13:49:31 IST 2014
Thread finished 9 : Sat Aug 09 13:49:27 IST 2014
Starting thread 12 : Sat Aug 09 13:49:33 IST 2014
Thread finished 10 : Sat Aug 09 13:49:29 IST 2014
Thread finished 11 : Sat Aug 09 13:49:31 IST 2014
Thread finished 12 : Sat Aug 09 13:49:33 IST 2014

Now, the Thread objects have their own value of the startDate attribute.

Thread-local variables store a value of an attribute for each Thread that uses one of these variables. You can read the value using the get() method and change the value using the set() method. The first time you access the value of a thread-local variable, if it has no value for the Thread object that it is calling, the thread-local variable calls the initialValue() method to assign a value for that Thread and returns the initial value.

When to use Thread Local
Today Whatever the application be like banking, telecommunications etc we need some sort of transaction id, user id for every request. Consider an example, you have servlet that call some business methods. You have requirement to generate a unique ID for every transaction that this servlet will process and then you need to pass this transaction ID to some other business methods, for instance, logging purpose.
One solution will be passing this transaction ID in the parameters to all the business methods.  Suppose if you have more than 10+ methods ,you will pass the transaction ID in the parameters to each methods that will redundant and unnecessary

To solve this, use can use ThreadLocal. First you can generate the transaction ID may be in servlet or filter and sets in a thread local. After this whatever business method this servlet call, can access the transaction ID from ThreadLocal. Servlet can be processing more than one request. Since each request is processed in a separate thread, the transaction ID will be unique to each thread(local) and will be accessible from all over the thread execution.

Example: 
TransactionContext.java : hold the transaction ID

MyThreadLocal.java : container to hold TransactionContext  object.

BuisnessClass.java : contain the business method

BuisnessClass1.java : contain the business method

ThreadLocalExample.java : main class that first generate the ID, then set by calling the set() method.


Output
Thread-0 JavaLatte-91996810
Thread-1 JavaLatte-1049236749
Thread-0 JavaLatte-91996810
Thread-1 JavaLatte-1049236749

If you look at the output, once we set the transaction ID for one thread, then it can be accessible from any business method that it will call.

There's more...
The thread-local class also provides the remove() method that deletes the value stored in the thread-local variable for the thread that it's calling.

The Java Concurrency API includes the InheritableThreadLocal class that provides inheritance of values for threads created from a thread. If a thread A has a value in a thread-local variable and it creates another thread B, the thread B will have the same value as the thread A in the thread-local variable. You can override the childValue() method that is called to initialize the value of the child thread in the thread-local variable. It receives the value of the parent thread in the thread-local variable as a parameter.



If you know anyone who has started learning Java, why not help them out! Just share this post with them. Thanks for studying today!...

Introduction to Executor Framework

Executor Framework (java.util.concurrent.executor) is framework for standardizing invocation, scheduling, execution & control of asynchronous tasks according to a set of execution policy .

As we know, thread are light weighted than creating a new process but still creating them utilizes a lot of resources.
Creating a new thread for each task will consume more stack memory as each thread will have its own stack for storing local variable, references etc. and also CPU spend more time in context switching.
Creating a lot of threads with no bounds on the thread creation cause an application to run of heap memory.
So creating a thread pool is a better solution as finite number of thread can pooled and reused. 

Let Start with a basic interface and classes used in the java.util.concurrent packages:

Interface Executor:
This interface contain only one method
                 void execute(Runnable command)
An Object that execute submitted Runnable tasks.This interface provide a way of decoupling task submission from the mechanism of how each task will be run including details of thread use, scheduling etc.
We will see the example how it is decoupling the task.

An Executor is used instead of explicitly creating threads.
For example:
rather than invoking new Thread(new(RunnableTask())).start() for each set of tasks, you might use 
Executor e=anExecutor;
e.execute(new RunnableTask1());
e.execute(new RunnableTask2());

However, an Executor interface does not strictly require that execution be asynchronous.It might be any of the following form:

  1. an executor can run the submitted task immediately in the caller's thread.(DirectExecutor.java)
  2. task is executed in some other thread other than caller's thread.(ThreadPerTaskExecutor.java)
  3. executor can serialize the task to a second executor.(SerialExecutor.java)

Let see one by one with example:

RunnableTask.java : task to be done
In this class I am doing the sum from number 1 to 100

package javalatte;
public class RunnableTask implements Runnable {
    int sum=0;
    @Override
    public void run() {
        for(int i=0;i<100;i++){
            sum=sum+i;
        }
        System.out.println(Thread.currentThread().getName()+" sum="+sum);
    }    
}


DirectExecutor.java : this class implements the Executor interface and providing the execute method body according to point 1.
package javalatte;
import java.util.concurrent.Executor;

public class DirectExecutor implements Executor {
    @Override
    public void execute(Runnable r) {
        r.run();
    }
}


main1.java

package javalatte;
public class main1 {
    public static void main(String a[]) {
        DirectExecutor e = new DirectExecutor();
        for (int i = 0; i < 100; i++) {
            e.execute(new RunnableTask());
        }
    }
}


Output  :

main sum=4950
main sum=4950
main sum=4950
main sum=4950
main sum=4950
...
...
===============================================
ThreadPerTaskExecutor.java : this class implements the Executor interface and providing the execute method body according to point 2

package javalatte;
import java.util.concurrent.Executor;
public class ThreadPerTaskExecutor implements Executor {
    @Override
    public void execute(Runnable r) {
        new Thread(r).start();
    }
}


Main2.java 

package javalatte;
public class main2 {
    public static void main(String a[]) {
        ThreadPerTaskExecutor e = new ThreadPerTaskExecutor();
        for (int i = 0; i < 100; i++) {
            e.execute(new RunnableTask());
        }
    }
}


output : (it may vary with run)

Thread-0 sum=4950
Thread-2 sum=4950
Thread-1 sum=4950
Thread-3 sum=4950
Thread-5 sum=4950
Thread-7 sum=4950

....
...

================================
SerialExecutor.javathis class implements the Executor interface and providing the execute method body according to point 3


package javalatte;
import java.util.ArrayDeque;
import java.util.Queue;
import java.util.concurrent.Executor;
public class SerialExecutor implements Executor {
    final Queue<Runnable> task = new ArrayDeque<Runnable>();
    final Executor executor;
    Runnable active;
    public SerialExecutor(Executor executor) {
        this.executor = executor;
    }
    @Override
    public synchronized void execute(final Runnable r) {
        task.offer(
                new Runnable() {

                    @Override
                    public void run() {
                        try {
                            r.run();
                        } finally {
                            next();
                        }
                    }
                });

        if (active == null) {
            next();
        }
    }
    synchronized void next() {
        if ((active = task.poll()) != null) {
            executor.execute(active);
        }
    }
}


main3.java : in this class we are passing the task to second executor we used here ThreadPerTaskExecutor as the second executor


package javalatte;
public class main3 {
    public static void main(String a[]){
        SerialExecutor e=new SerialExecutor(new ThreadPerTaskExecutor());
        for(int i=0;i<1000;i++){
            e.execute(new RunnableTask());
        }
    }
}


output : it will always execute the sequence wise 0,1,2,3,4....

Thread-0 sum=4950
Thread-1 sum=4950
Thread-2 sum=4950
Thread-3 sum=4950
Thread-4 sum=4950
Thread-5 sum=4950
...
..

From the above 3 example, hope you guys got the idea how it decouple the task.

============================

Interface ExecutorService :
public interface ExecutorService extends Executor 

As it is extending the Executor interface , so it become an Executor that provides methods to manage termination and methods that produce a Future for tracking progress of one or more thread in asynchronous tasks.


Class Executors :
This class provide the factory methdos for Executor,ExecutorService,ScheduledExecutorService,ThreadFactory and callable classes defind in the concurrent package.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/Executors.html


Now I am sharing the example of Fixed threadpool used the above classes that i have explained :
In this example , i have used fixed number of thread i.e. 3. Only 3 thread will be created to complete the task.


package javalatte;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedThreadPoolExample {
    private static final int NO_OF_THREAD = 3;
   public static void main(String javalatte[]) {
        ExecutorService executor = Executors.newFixedThreadPool(NO_OF_THREAD);
            for(int i=0;i<1000;i++){
                Runnable worker=new RunnableTask();
                executor.execute(worker);
            }
            /**
             * Method of ExecutorService interface
             */
            executor.shutdown();
            /**
             * Waiting for thread to terminated
             */
            while(!executor.isTerminated()){
                
            }
            System.out.println("Finished");
    }
}


Output :

pool-1-thread-1 sum=4950
pool-1-thread-1 sum=4950
pool-1-thread-1 sum=4950
pool-1-thread-2 sum=4950
pool-1-thread-2 sum=4950
pool-1-thread-2 sum=4950
pool-1-thread-2 sum=4950
pool-1-thread-2 sum=4950
pool-1-thread-2 sum=4950
pool-1-thread-2 sum=4950
....
......

Note : Runnable interface void run() method has no way of returning any result back to the main method (RunnableTask.java)

Executor Interface has introduced the Callable interface that return a a value from call() method. This means asynchronous task will be able to return value once it done the processing.
Before going for the example of Callable , first we see that Future interface

Future Interface:
Future represent the result of asynchronous computation.
Methods are provides to check :

  • is computation is complete
  • wait for it completion 
  • to retrieve the result of computation 

 Result can be retrieved using get() method when computation is complete,blocking if necessary until it is ready.( we'll see in the example)

CallableTask.java

package javalatte;
import java.util.concurrent.Callable;
public class CallableTask implements Callable<String> {
    @Override
    public String call() {
        int sum = 0;
        for (int i = 0; i < 100; i++) {
            sum = sum + i;
        }
        return Thread.currentThread().getName() + " Sum=" + sum;
    }
}

FixedThreadPoolCallable.java

package javalatte;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Callable;
public class FixedThreadPoolCallable {
        private static final int NO_OF_THREAD = 3;
    public static void main(String javalatte[]){
        ExecutorService executor=Executors.newFixedThreadPool(NO_OF_THREAD);
        List<Future<String>> list=new ArrayList<Future<String>> ();
        
        for(int i=0;i<100;i++){
            Callable<String> worker=new CallableTask();
            Future<String> submit=executor.submit(worker);
            list.add(submit);            
        }
        for(Future<String> future :list){
            try{
            System.out.println("Thread:"+future.get());
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        executor.shutdown();
    }
}

output :

Thread:pool-1-thread-1 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-3 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
Thread:pool-1-thread-2 Sum=4950
...
...

The Executor implementations provides different execution policies to be set while executing the tasks ,example threadpool support the following polices:

  • newFixedThreadPool
Creates thread as task are submitted , up to maximum pool size and then attempt to keep the pool size constant.
  • newCachedThreadPool
Add threads when demand increase, no bounds on the size of the pool.
  • newSingleThreadExecutor
Single worker thread to process tasks. Guarantees order of execution based on the queue policy
  • newScheduledThreadPool
Fixed size ,support delay and periodic task

Executor framework :is based on producer consume design pattern ,where thread that submit the tasks are the producer and the thread that execute the task are consumer.

In the above example, main thread is the producer as it loops  through and submit the task to the worker thread.
RunnableRask, CallableTask is the consumer that execute the task.