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 threads in 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.


Synchronized vs Concurrent Collections

Synchronize means: the resource (which is synchronized) can't be modified by multiple threads simultaneously.

Synchronized and Concurrent Collections can be used to provide thread-safety; however differences between them come in performance, scalability and the way to achieve thread-safety. Synchronized collections (=synchronized HashMap, Hashtable, HashSet, Vector and synchronized ArrayList) are much slower than their concurrent counterparts (=ConcurrentHashMap, CopyOnWriteArrayList, and CopyOnWriteHashSet). Because synchronized collections locks the whole collection e.g. whole Map or List while concurrent collection never locks the whole Map or List. They achieve thread safety by using advanced and sophisticated techniques like lock stripping.

Hashtable vs. ConcurrentHashMap
So what is the difference between Hashtable and ConcurrentHashMap, both can be used in multi-threaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration. Since ConcurrentHashMap introduced concept of segmentation, It doesn't matter whether how large it becomes because only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

In Summary ConcurrentHashMap only locks certain portion of Map while Hashtable lock full map while doing iteration or performing any write operation.

ArrayList vs. CopyOnWriteArrayList

CopyOnWriteArrayList allows multiple reader threads to read without synchronization and when a write happens it copies the whole ArrayList and swap with a newer one.

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;



Nth maximum salary in MySQL using LIMIT clause

MySQL supports a LIMIT keyword, which provides pagination capability. We can find the nth highest salary in MySQL without using sub query.


SELECT salary FROM Employee ORDER BY salary DESC LIMIT N-1, 1;


4rth highest salary in MySQL with LIMIT clause: 
-- use database
use abusecore;

-- creating Employee table in mysql
CREATE TABLE Employee (name varchar(10), salary int);

-- inserting sample data into Employee table
INSERT INTO Employee VALUES ('Mill', 3000);
INSERT INTO Employee VALUES ('Sham', 4000);
INSERT INTO Employee VALUES ('Jack', 3000);
INSERT INTO Employee VALUES ('Pats', 5000);
INSERT INTO Employee VALUES ('Rock', 7000);

-- 4rth highest salary in MySQL
SELECT salary FROM Employee ORDER BY Salary DESC LIMIT 3,1

-- Output:
3000

Nth highest salary in MySQL with LIMIT clause:

SELECT salary FROM Employee ORDER BY Salary DESC LIMIT n-1,1;



This approach is faster than correlated query approach but its vendor dependent.

Composition (HAS-A) Relationship



Composition in java can be achieved by using instance variables that refers to other objects.

Example: Car has Engine, or House has Bathroom, a Person has a Job.

class Engine {
     private String model;
     private long power;

     public long getPower() {
           return power;
     }

     public void setPower(long power) {
           this.power = power;
     }

     public String getModel() {
           return model;
     }

     public void setModel(String model) {
           this.model = model;
     }  
}

class Car {
     //composition has-a relationship
     private Engine engine;

     public Car() {

           this.engine = new Engine();
           engine.setPower(1000L);
     }

     public long getPower() {
           return engine.getPower();
     }
}

public class CompositionTest {
     public static void main(String[] args) {
           Car car = new Car();
           System.out.println("Engine Power in cc #"+car.getPower());
     }
}


Notice that above test program is not affected by any change in the Engine object. If you are looking for code reuse and the relationship between two classes is has-a then you should use composition rather than inheritance.

Biggest benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.

Wednesday, 1 March 2017

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


A singleton is simply a class that 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 class Singleton {
     public static final Singleton 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.setAccessible method.

//Singleton with static factory
public class Singleton {
     private static final Singleton INSTANCE = new Singleton();
     private Singleton() { ... }
     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
private Object readResolve() {
     // Return the one true Singleton and let the garbage collector
     // take care of the Singleton impersonator.
     return INSTANCE;
}

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 enum Singleton {
     INSTANCE;
     public void doStuff(){
           System.out.println("Singleton using Enum");
     }
}

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

Tuesday, 28 February 2017

What is initial capacity and load factor?


Initial capacity is nothing but the number of buckets when the hash table is created, capacity is automatically increased when hash table get full of element.

Load factor is a measurement of how full collection (hash table) is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

How it affects performance?
As a general rule, the default load factor (.75) offers a good trade-off between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

Conclusion:
So finally we can conclude default load capacity (.75) used by Hash Map is a good value in most situations. We can set the initial capacity of Hash Map based on own knowledge of how many items it will hold.

Set it like, initial-capacity = number of items/.75 (round up).


Generate the next prime of a number in Java

Java java.math.BigInteger class contains a method nextProbablePrime () to check the primality of a number.

import java.math.BigInteger;

public class NextPrime {

            public static void main(String[] args) {
                        int number = 83;
                        Long nextPrime = nextPrime(number);
                        System.out.println(nextPrime + " next prime to " + number);

            }

            /**
             * method to find next prime
             * @param number
             * @return boolean
             */
            private static Long nextPrime(int number) {
                        BigInteger bValue = BigInteger.valueOf(number);
                       
                        /**
                         * nextProbablePrime method used to generate next prime.
                         * */
                        bValue = bValue.nextProbablePrime();
                       
                        return Long.parseLong(bValue.toString());
            }
}

Output:
            89 next prime to 83

Related Posts Plugin for WordPress, Blogger...