Showing posts with label Core Java. Show all posts
Showing posts with label Core Java. Show all posts

Tuesday, September 24, 2013

HashSet Example in Java

Links to this post
About HashSet:
  • HashSet is class which extends AbstractSet and Implements Set Interface
  • It does not maintain insertion order
  • It allow null
  • Contains unique elements Only, same as LinkedHashSet

Wednesday, September 18, 2013

Thread Pooling using Executors and ThreadPoolExecutor in Java

Links to this post
Thread Pool manages pool of threads waiting for job. They are called worker Threads.Initially threads are waiting in pool for job and once they will get job to process, it will be process that job and move back to thread pool and wait for another job.

As mentioned in below example, I have create fixed size of Thread Pool with 5 worker threads. Now I will submit 10 jobs which should be processed by worker threads in Thread Pool. But Since I have only 5 Threads available in Thread pool, how it will work?

Thread Interrupt Example in Java

Links to this post
Thread class provides method interrupt() using which one can Interrupt thread.

Before moving ahead, It's important to understand following scenarios :
  • If Thread is blocked in invocation of method like sleep(),join() or Object.wait then It's interrupted status will be cleared and InterruptedException will be thrown.
  • If Thread is blocked in IO Operation upon java.nio.channels.InterruptibleChannel then channel will be closed and interrupted status will be set. Here, Thread will receive ClosedByInterruptException

Thread Naming in Java

Links to this post
Thread class provides following methods using which You can set name to Thread and retrieve thread name.
  • public final void setName(String name) - Changes name of Thread equals to argument
  • public final String getName() - Return Thread name

JVM Shutdown Hook - addShutdownHook in Java

Links to this post
JVM Provides hook to register thread with shutdown init sequence. Meaning whenever shutdown will happen, this thread will run.You may require this to cleanup resources in case of unexpected JVM Shutdown.

Runtime.class provides method addShutdownHook whereYou can provide Thread instance.
public void addShutdownHook(Thread hook)

Tuesday, September 17, 2013

Thread Join Example in Java

Links to this post
Thread Class provides join() method Basically It will wait for Thread to die.Consider following scenario where we haven't used join and observe the output.

In Scenarion1, Output is not sequential and one Thread goes to sleep and Thread scheduler picks up another thread and start executing.

Scenario1 : Situation where there is no Join :
package com.anuj.threading;

 * Thread Join Example
 * @author Anuj
class ThreadJoinExample extends Thread{

 public void run() {
  for(int i=1;i<=5;i++){
   System.out.println(Thread.currentThread().getName() + " - "+i);
   try {
   } catch (InterruptedException e) {
  * @param args
 public static void main(String[] args) {
  ThreadJoinExample t1 = new ThreadJoinExample();
  ThreadJoinExample t2 = new ThreadJoinExample();
  System.out.println(t1.getName() + " : " + t1.isAlive());
   System.out.println(t1.getName() + " : " + t1.isAlive());
  catch(Exception e){
  System.out.println(t2.getName() + " : " + t2.isAlive());

Pausing Execution with Sleep - Thread.sleep in Java

Links to this post
If You want to suspend executing of Thread for particular period of time then Thread.sleep is for You.Once You suspend particular thread, Thread scheduler pickups other threads which are waiting for execution.

Monday, September 16, 2013

How to Set Priority of Thread - Thread Priority Example in Java

Links to this post
Each Thread has priority. Thread Scheduler schedules thread based on thread priority. You can set priority of thread. It's important to understand Preemptive Scheduling and Time Slicing before moving ahead.

Priorities are integer values from 1 (Thread.MIN_PRIORITY) to 10 (Thread.MAX_PRIORITY).
Default Priority is Thread.NORM_PRIORITY (Value 5)

What is Difference between Preemptive Scheduling and Time Slicing in Java

Links to this post
Preemptive Scheduling :
In Preemptive Scheduling , Highest Priority thread runs first until it enters into waiting states or dead states or higher priority tasks comes into picture.

Time Slicing:
In Time Slicing, Task executes for specific predefined slice of time and then enters into pool of read tasks. Then Scheduler decides which tasks should be executed next.

Tuesday, September 03, 2013

Data Encryption Decryption using DES Algorithm in Java

Links to this post
Encryption is process of converting plan text to cypher text using encryption algorithm and encryption Key.
Decryption is reverse process of encryption which recover original data from encrypted data using decryption key.

Here, One should understood Cryptography concept before moving into encryption and description world. It's basically making communication private - Protect Sensitive Information. Refer to wiki for more details.

Types of Cryptography :
  1. Symmetric
  2. ASymmetric

Wednesday, August 14, 2013

Apache Tika - Extract MetaData and Stractured Text Content Extraction

Links to this post
Apache Tika is used for detecting and extracting metadata and structured text content from different documents using existing parser libraries.

Apache Tika provides interface called Parser (org.apache.tika.parser) which provides api called parse whose job is to parses a document stream into a sequence of xhtml sax events.

Tika supports different formats like text,audio,image,video,word document,open document,pdf,xml,html etc. Please refer to Apache Tika Supported Documents Format for more details. You may want have a look at Apache Tika 1.4 API documentation

    Saturday, August 10, 2013

    Java Program to Find Fibonacci Series of Given Number

    Links to this post
    Fibonacci? Consider requirement that I want to display Fibonacci series of number 10.If You remember maths in school, we used to find Fibonacci number using below :

    Fibonacci is sum of previous two Fibonacci numbers fn= fn-1+ fn-2

    Fibonacci of 10 will be 0 1 1 2 3 5 8 13 21 34  ex. 0 1 (0+1) (1st+2nd)...

    How to Calculate Factorial of Number using Java with Recursion

    Links to this post
    Factorial? let me show you how we calculate factorial of given number. Consider requirement that I want to find factorial of number 5.

    If you remembered Maths, in School we used to find factorial using below match function !
    n! = n * (n-1)!

    Ex. 5! = 5*(5-1)! = 5*4!
          4! = 4 *(4-1)! = 4*3!
          3! = 3*(3-1)! = 3*2!
          2!= 2*(2-1)! = 2*1!
          1! = 1*(1-0)! =  1

    Saturday, May 25, 2013

    Retrieve Key-Value Pairs of the Properties files in Java

    Links to this post
    Java  Properties class represents a persistent set of properties.

    Properties class extends HashTable meaning Properties inherits from Hashtable, So put and putAll methods can be applied to a Properties object.

    Some of useful methods are metioned below which object of Properties class can call.

    Properties pro = new Properties();

    1. keySet() - Retrieve Set of Keys 
    2. keys() - Retrieves all keys of the properties files. Which stored in the Enumeration objects.

    Monday, February 18, 2013

    Apache Solr and SolrJ Maven Dependancies

    Links to this post
    While I was developing Solr application using Solrj, there was confusion (which is always :) ) of which maven dependencies to be included in Pom.xml. Hence thought to share here.
    Please don't miss to add M2_REPO classpath variable pointing to repository directory so you can easily import required library into your Java Project.

    Maven Dependencies for Developing application with Solr (version 4.1) are followed as :

    1. Solrj Dependencies

    2. Solr-core Dependencies

    Sunday, November 25, 2012

    Java i18n Internationalization Example

    Links to this post
    Internationalization is the process of designing an application so that it can be adapted to various languages and regions without engineering changes.

    Sometimes I was wondering term internationalization is abbreviated as i18n, Why? and Found reason is   there are 18 letters between the first "i" and the last "n." :)

    Why to use i18n and Benifits of i18n :
    1. Support for new languages does not require recompilation as stored in Properties Files.
    2. Can be localized quicklyby setting Local as per Language and country
    3. Instead of hard coding Textual elemtns(GUI labels,status message,Error message. they are stored outside and retrieved dynamically.
    4. By small additional of data(properties file of different landuage) , same code can be run WorldWide.
    5. Culturally dependent data, like dates and currencies, appear in formats that line up with user's region and language

    Sunday, November 04, 2012

    Viewing Content of Jar in Java

    Links to this post
    jar tvf <myjarfile>.jar - Display Verbose output

    0 Mon Mar 28 01:49:30 IST 2011 META-INF/
     217 Mon Mar 28 01:49:28 IST 2011 META-INF/MANIFEST.MF
       0 Mon Mar 28 01:49:30 IST 2011 datamapping/
       0 Mon Mar 28 01:49:30 IST 2011 datamapping/Properties/
      777 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping$1.class
      770 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping$2.class
      553 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping$3.class
    16453 Mon Mar 28 01:49:28 IST 2011 datamapping/DataMapping.class
      553 Mon Mar 28 01:49:30 IST 2011 datamapping/DisplayData$1.class
     2331 Mon Mar 28 01:49:30 IST 2011 datamapping/DisplayData.class
     4938 Mon Mar 28 01:49:30 IST 2011 datamapping/Properties/

    jar tf <myjarfile>.jar - This command displays the contents of the JAR file to stdout:

    How to Create Jar in Java

    Links to this post
    jar cf  <jar-file>  <input-files>

    Options :
    c  - option indicates that you want to create a JAR file.

    - option indicates that you want the output to go to a file rather than to stdout.

    jar-file  - is the name that you want the resulting JAR file to have. You can use any filename for a JAR file. By convention, JAR filenames are given a .jar extension, though this is not required.

    input-file(s) - is a space-separated list of one or more files that you want to be placed in your JAR file.
    If any of the "input-files" are directories, the contents of those directories are added to the JAR archive recursively.

    How to List Entries in Jar Files using Java Program

    Links to this post
    The JarFile class is used to read the contents of a JAR file.

    Class JarFiles extends the class with support for reading an optional Manifest entry. The Manifest can be used to specify meta-information about the JAR file and its entries.

    JarFiles has method called entries() which is used to returns an enumeration of the ZIP file entries. Using Enumeration, You can iterate over entries to list enteries in JarFiles

    Saturday, October 27, 2012

    Retrieve Modifier Information using Java Reflection APIs

    Links to this post
    Java Reflection has API called getModifiers() which is used to get Modifier information of class. just create object of class and call getModifiers() method. Play with Modifier and it's methods.

    Java Program to get Modifier Information using Java Reflection API:

    System.out.println("Modifier Information - ");
    List list = new ArrayList();
    Class originalClassObj = list.getClass();
    int modifier = originalClassObj.getModifiers();
    if (Modifier.isPublic(modifier)) {
    if (Modifier.isAbstract(modifier)) {
    if (Modifier.isFinal(modifier)) {
    Output :

    Modifier Information - 

    Author : Anuj Patel
    Blog :