Wednesday, 22 March 2017

What is Thread Pool in Java and why we need it?


Java Thread pool represents a group of worker threads that are waiting for the job and reuse many times. Thread pool creates Thread and manages them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threadsin form of worker thread.

In case of thread pool, a group of fixed size threads are created i.e. it also limits number of clients based upon how many thread per JVM is allowed, which is obviously a limited number. A thread from the thread pool is pulled out and assigned a job by the service provider. After completion of the job, thread is contained in the thread pool again.

Advantage of Java Thread Pool
Better performance, it saves time because there is no need to create new thread. The thread pool is one of essential facility any multi-threaded server side Java application requires. One example of using thread pool is creating a web server, which processes client request.

If only one thread is used to process client request, than it subsequently limit how many client can access server concurrently. In order to support large number of clients, you may decide to use one thread per request paradigm, in which each request is processed by separate Thread, but this require Thread to be created, when request arrived.  Since creation of Thread is time consuming process, it delays request processing.

Since Thread are usually created and pooled when application starts, your server can immediately start request processing, which can further improve server’s response time.

Real time usage
It is used in Servlet and JSP where container creates a thread pool to process the request.

Thread pools help us to better manage threads and decoupling task submission from execution. Thread pool and Executor framework introduced in Java 5 is an excellent thread pool provided by library.


Friday, 3 March 2017

Oracle queries for the rownum, rank to find the nth highest salary

Find the 2nd highest data in SQL:
SELECT MAX(balance) FROM mtx_wallet_balances WHERE balance NOT IN (SELECT MAX(balance) FROM mtx_wallet_balances )

SELECT MAX(balance) FROM mtx_wallet_balances WHERE balance <> (SELECT MAX(balance) FROM mtx_wallet_balances)


Find the nth highest data in Oracle using rownum:
select * from ( select mwb.*, row_number() over (order by balance DESC) rownumb from mtx_wallet_balances mwb ) where rownumb = 105;

Find the nth highest data in Oracle using RANK:
SELECT * FROM (SELECT balance, RANK () OVER (ORDER BY balance DESC) ranking FROM mtx_wallet_balances) WHERE ranking = 105;



Wednesday, 1 March 2017

Singleton using enum : Enforce the singleton property with a private constructor or an enum type


A singleton is simply a classthat is instantiated exactly once.

Before release 1.5, there were two ways to implement singletons. Both are based on keeping the constructor private and exporting a public static member to provide access to the sole instance.

In one approach, the member is a final field:

//   Singleton with public final field
public classSingleton {
     public static finalSingleton INSTANCE = new Singleton();
     private Singleton() { ... }
}

The private constructor is called only once, to initialize the public static final field Singleton.INSTANCE. Singleton instance will exist once the Singleton class is initialized—no more, no less. However a privileged client can invoke the private constructor using Reflection by AccessibleObject.setAccessiblemethod.

//Singleton with static factory
public classSingleton {
     private static finalSingleton INSTANCE = new Singleton();
     privateSingleton() { ... }
     public static Singleton getInstance() { return INSTANCE; }
}

To make a singleton class that is implemented using either of the previous approaches serializable, it is not sufficient merely to add implements Serializable to its declaration.
Each time a serialized instance is deserialized, a new instance will be created. To maintain the singleton guarantee, you have to declare all instance fields transient and provide a readResolve method.

//readResolve method to preserve singleton property
privateObject readResolve() {
     // Return the one true Singleton and let the garbage collector
     // take care of the Singleton impersonator.
     returnINSTANCE;
}

Singleton using enum:
As of release 1.5, there is a third approach to implementing singletons. This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks.

Enum is thread-safe which helps us to avoid double checking(=less code for better results).

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.

public enumSingleton {
     INSTANCE;
     public voiddoStuff(){
           System.out.println("Singleton using Enum");
     }
}

And this can be called from clients:
public static voidmain(String[] args) {
     Singleton.INSTANCE.doStuff();
}

Related Posts Plugin for WordPress, Blogger...