TreeMap Example in Java

TreeMap maintains ascending order and does not allows null as Key which differs in HashMap and LinkedHashMap.

About TreeMap:
  • It extends AbstractMap class and Implements NavigableMap Interface
  • It maintain ascending order
  • It does not allow null as Key

LinkedHashMap Example in Java

LinkedHashMap is used for Key-Value concepts. when we require to store values based on Key then LinkedHashMap is for You !But It maintains insertion order while HashMap does not.

About LinkedHashMap:
  • It extends HashMap class and Implements Map Interface
  • It maintain insertion order
  • Allows null as Key and Values also

HashMap Example in Java

HashMap is used for Key-Value concepts. when  we require to store values based on Key then HashMap is for You !

About HashMap :
  • HashMap is class which extends AbstractMap and Implements Map Interface
  • HashMap does not maintain insertion order

TreeSet Example in Java

About TreeSet:
  • TreeSet is class which extends AbstractSet and Implements NavigableSet Interface
  • It does maintain ascending order
  • It does not allow null
  • Contains unique elements Only, same as HashSet and LinkedHashSet

LinkedHashSet Example in Java

About LinkedHashSet :
  • LinkedHashSet is class which extends HashSet and Implements Set Interface
  • It maintain insertion order
  • Allows null
  • Contains unique elements Only

HashSet Example in Java

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

Thread Pooling using Executors and ThreadPoolExecutor in Java

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

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

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

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)

Thread Join Example in Java

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{

 @Override
 public void run() {
  for(int i=1;i<=5;i++){
   System.out.println(Thread.currentThread().getName() + " - "+i);
   
   try {
    Thread.sleep(500);
   } catch (InterruptedException e) {
    e.printStackTrace();
   }
  }
 }
 
 /**
  * @param args
  */
 public static void main(String[] args) {
  ThreadJoinExample t1 = new ThreadJoinExample();
  ThreadJoinExample t2 = new ThreadJoinExample();
  t1.setName("Thread1");
  t2.setName("Thread2");
  
  t1.start();
  System.out.println(t1.getName() + " : " + t1.isAlive());
  
  /*try{
   t1.join();
   System.out.println(t1.getName() + " : " + t1.isAlive());
  }
  catch(Exception e){
   e.printStackTrace();
  }*/
    
  System.out.println(t2.getName() + " : " + t2.isAlive());
  t2.start();
 }
}
Output :Thread1 : true
Thread1 - 1
Thread1 - 2
Thread1 - 3
Thread1 - 4
Thread1 - 5
Thread1 : false
Thread2 : false
Thread2 - 1
Thread2 - 2
Thread2 - 3
Thread2 - 4
Thread2 - 5

Pausing Execution with Sleep - Thread.sleep in Java

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.

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

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

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.

Data Encryption Decryption using DES Algorithm in Java

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