Monthly Archives: October 2014

Setting up a JDBC connection to Oracle 11g from java class

For setting up a JDBC connection , we need to have the following data primarily:

DB_URL = “jdbc:oracle:thin:@localhost:1521:xe”;

This is for setting up connection to oracle 11g. For any other databases the DB_URL and the DRIVER may vary. Also  the URL pattern depends on the port and the database that we are trying to connect to and the details may be obtained in tnsnames.ora file in  <drive:\>oracleexe\app\oracle\product\11.2.0\server\network\ADMIN path

XE =
(ADDRESS = (PROTOCOL = TCP)(HOST = Devashish-PC)(PORT = 1521))

Now comes the database username and password. If you already have a user created then you can skip this step else do the following:

1. In start menu in the oracle11g folder click on get started.
2. When prompted to enter the username type ‘system’ and password type ‘tiger’.
3. Localhost appears.
4. Click on application express.
5. Create the database user.

Suppose my user is created with credentials :

USER = “dev”;
PASS = “june”;

Now when the following steps has been performed. Go to eclipse and create a new project. Download ojdbc14 , configure buildpath and add as external jar.

Then the the code for connecting is :

final String JDBC_DRIVER="oracle.jdbc.driver.OracleDriver";
final String DB_URL = "jdbc:oracle:thin:@localhost:1521:xe";
// Database credentials
final String USER = "dev";
final String PASS = "june";
Connection con=null;
Statement stmt=null;
try {
ResultSet rs=stmt.executeQuery("select * from tab");
} catch (Exception e) {

It should return the no of tables fetched e.g. in my case it showed 10.

Happy coding  🙂

Threads Pools and Executor Service

In order to maintain the performance in a distributed system, we might require to limit the number of threads in a thread pool. We have two approaches:

Executor Service & Thread Pools .

I feel executor service is the easier approach whereas Thread Pools is required when we need customization.

Executor Service:

Executor Service is the child interface of Executor. Basically, we can create the following types if executor service as:

FixedThreadPool  :  To create a fixed number of threads, if more tasks are submitted then the idle threads in the thread pools the tasks will wait.


CachedThreadPool : Threads will execute the task and are killed.

SingleThreadPool : Only one thread in the entire thread pool.

We just require to create an object of the Runnable/Thread type and submit it in the threadpool.

A sample code snippet is as follows:

ExecutorService executor= Executors.newScheduledThreadPool(5);

for(int i=0;i<10;i++)


Runnable worker=new WorkerThread(i);




if (executor.isTerminated()) {




class WorkerThread implements Runnable


private int i;

public WorkerThread(int i) {




public void run() {

System.out.println(Thread.currentThread().getName()+” Start= “+i);

System.out.println(Thread.currentThread().getName()+” End.”);




Thread Pool Executor is perhaps a better approach where we have a lot of options.

ExecutorService threadPoolExecutor =        new ThreadPoolExecutor(corePoolSize,            maxPoolSize,keepAliveTime,TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(),                   threadFactory,rejectionHandler);

Let us see what the above parameters mean:

Core and maximum pool sizes :

When a new task is submitted in method , and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle.

If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.

Keep-alive times :

If the pool currently has more than corePbeoolSize threads, excess threads will be terminated if they have been idle for more than the keepAliveTime.


Any blocking queue can be used to transfer and hold the submitted task such as a Synchronous Queue, a LinkedBlockingQueue or an ArrayBlockingQueue.

Thread Factory: A default thread factory can be used as

ThreadFactory threadFactory = Executors.defaultThreadFactory();

RejectedExecutionHandler : Implementation to handle the jobs that can’t fit in the worker queue.

For that we need to create a class which implements the RejectedExecutionHandler.

class RejectedExecutionHandlerImpl implements RejectedExecutionHandler



public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {

System.out.println(r.toString()+” is rejected”);



So we create the executor pool as:

ThreadPoolExecutor executorPool=new ThreadPoolExecutor(2, 4, 10,TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(2),threadFactory,rejectionHandler);

And then we add a new task in the thread pool as

executorPool.execute(new WorkerThread(3));

After all the tasks has been executed by the thread pool we should terminate the thread pool as executorPool.shutdown();