• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Core Java
  • Design Patterns
  • JSP
  • Servlets
  • Building Tools
  • jQuery
  • Spring
  • Hibernate
  • Mongo DB
  • More
    • HTML
    • SCJP
    • AJAX
    • UML
    • Struts
    • J2EE
    • Testing
    • Angular JS

J2EE Reference

  • Home
  • About Us
    • Java Learning Centers
  • Contact Us

Core Java

What is ThreadLocal in Java ?

May 29, 2017 By j2eereference Leave a Comment

What is ThreadLocal in java : ThreadLocal in java is a class which enables you to create thread-safe local variables. ThreadLocal is another way to achieve thread-safety .

Why ThreadLocal variables are thread safe?

ThreadLocal variables are thread-safe as every thread has its own set of ThreadLocal variables which can only be read and write by the same thread and other threads cannot see these ThreadLocal variables.Thread can holds ThreadLocal variables till it is not in dead state.

When ThreadLocalVariable is eligible to garbage collection?

ThreadLocal variable becomes eligible to Garbage collection after thread died or due to any Exception with the condition that ThreadLocal variable doesn’t have any other live references.

Program for using ThreadLocal :

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import java.util.Date;
class ThreadLocalRunnable implements Runnable
{
  private ThreadLocal threadLocal = new ThreadLocal();
  @Override
  public void run()
  {
    threadLocal.set(new Date().toString());
    try {
          Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
          e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+" processing time is : "+threadLocal.get());
  }
}
 
public class ThreadLocalDemo
{
  public static void main(String[] args) throws InterruptedException
  {
    ThreadLocalRunnable threadLocal = new ThreadLocalRunnable();
    Thread threadA = new Thread(threadLocal,"Thread-A");
    Thread threadB = new Thread(threadLocal,"Thread-B");
    Thread threadC = new Thread(threadLocal,"Thread-C");
    threadA.start();
    threadA.join();
    threadB.start();
    threadB.join();
    threadC.start();
}
}

OutPut:
Thread-A processing time is : Thu May 04 17:36:36 IST 2017
Thread-B processing time is : Thu May 04 17:36:37 IST 2017
Thread-C processing time is : Thu May 04 17:36:38 IST 2017

Where to use ThreadLocal:
1)In multithreaded environment, each thread will start at different time and we might need to store time at which they have started. So, we can store thread’s start time in ThreadLocal.

2)Many web frameworks use ThreadLocal for maintaining context may be session or request related value.For example : In a multithreaded web application we have a requirement to generate a unique transaction id for each and every user request .We need to pass this transaction id to all the business methods. One way is to provide transaction id as a parameter to all the business methods. But this is not a good solution as the code is redundant and unnecessary.So, can use ThreadLocal variable here by setting this transaction id in the ThreadLocal. Now, all the business methods in this controller can access this transaction id from the ThreadLocal . Also,multiple user requests are coming and each request is processed y separate thread, so transaction id will be unique to each thread .

3)You can make any non Thread Safe object as thread- safe by wrapping in ThreadLocal

4)J2EE application servers like Weblogic,Websphere uses java ThreadLocal to keep track of transaction and security Context.

Related Posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof

Filed Under: Core Java Tagged With: multithreading, Thread-safe, ThreadLocal, ThreadLocal variables usecases

ArrayList custom Implementation

May 26, 2017 By j2eereference Leave a Comment

Here we are going to create custom ArrayList ,our own ArrayList Class . Let’s first check out basic methods of ArrayList class ,so that we can provide same functionality in our custom ArrayList class.

Basic methods required to create custom ArrayList are :

1) public void add(E element): This method will add objects (element) in ArrayList.
2) public E get(int index) : This method will return element at specific index
3) public Object remove(int index) : This method will remove element at specified index private 4)
4) public void ensureCapacity(): this method will increase capacity of ArrayList by increases its size to double
Program to create custom ArrayList class.

Program to create custom ArrayList class

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package com.j2eereference;
 
import java.util.Arrays;
 
class Student {
    private String stuId;
    private String name;
    
    public Student(String id, String name) { // constructor
           this.stuId = id;
           this.name = name;
    }
    @Override
    public String toString() {
           return "Student[student id is : "+ stuId + " and name is " + name + "] ";
    }
}
class ArrayListCustom<E> {
    
  private static final int INITIAL_CAPACITY = 15;
  private Object elementArray[]={};
  private int size = 0;
  public ArrayListCustom() {
  elementArray = new Object[INITIAL_CAPACITY];
  }
  public E get(int index) {
    if ( index <0 || index>= size) {  
     throw new IndexOutOfBoundsException("Index out of bound exception. Please provide valid index");
    }
    return (E) elementArray[index];
  }
  
  public void add(E e) {
    if (size == elementArray.length) {
      ensureCapacity();
    }
    elementArray[size++] = e;
  }
public Object remove(int index) {
    if ( index <0 || index>= size) {  
      throw new IndexOutOfBoundsException("Index out of bound exception. Please provide valid index");
    }
  
    Object removedElement=elementArray[index];
    for(int i=index;i<size - 1;i++){
     elementArray[i]=elementArray[i+1];
    }
    size--;  
    return removedElement;
  }
  private void ensureCapacity() {
    int newIncreasedCapacity = elementArray.length * 2;
    elementArray = Arrays.copyOf(elementArray, newIncreasedCapacity);
  }
  public void display() {
      System.out.print("Students present in the ArrayList : ");
      for(int i=0;i<size;i++){
             System.out.print(elementArray[i]+" ");
      }
  }
}
public class CustomArrayList {
    
     public static void main(String...a) {
     ArrayListCustom<Student> customList = new ArrayListCustom<Student>();
     System.out.println("Adding student in custom ArrayList");
     customList.add(new Student("101", "Shobhna"));
     customList.add(new Student("102", "Shilpi"));
     customList.add(new Student("105", "Upasana"));
     customList.add(new Student("108", "Gurpal"));
     customList.add(new Student("110", "Mohit"));
     customList.add(new Student("112", "Harpreet"));
     customList.add(new Student("111", "Raghu"));
     customList.add(new Student("115", "Krishna"));
    
    
     customList.display();
     System.out.println("\n Student  at index "+6+" = "+customList.get(6));
     System.out.println("Student removed from index "+4+" = "+customList.remove(4));
    
     customList.display();
     customList.remove(10);
    
   }
    
}

OutPut:
Adding student in custom ArrayList
Students present in the ArrayList : Student[student id is : 101 and name is Shobhna] Student[student id is : 102 and name is Shilpi] Student[student id is : 105 and name is Upasana] Student[student id is : 108 and name is Gurpal] Student[student id is : 110 and name is Mohit] Student[student id is : 112 and name is Harpreet] Student[student id is : 111 and name is Raghu] Student[student id is : 115 and name is Krishna]
Student at index 6 = Student[student id is : 111 and name is Raghu]
Student removed from index 4 = Student[student id is : 110 and name is Mohit]
Students present in the ArrayList : Student[student id is : 101 and name is Shobhna] Student[student id is : 102 and name is Shilpi] Student[student id is : 105 and name is Upasana] Student[student id is : 108 and name is Gurpal] Student[student id is : 112 and name is Harpreet] Student[student id is : 111 and name is Raghu] Student[student id is : 115 and name is Krishna] Exception in thread “main” java.lang.IndexOutOfBoundsException: Index out of bound exception. Please provide valid index
at com.j2eereference.ArrayListCustom.remove(CustomArrayList.java:48)
at com.j2eereference.CustomArrayList.main(CustomArrayList.java:96)

We are getting IndexOutOfBoundException at the end of the output as we are removing element at index 10 but our custom ArrayList contains only 8 elements.

Related Posts

  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords
  • Anonymous Inner Class in Java
  • Network Programming – java.net Package
  • Java Regular Expressions
  • Method Local Inner Class in Java
  • URL Processing in Java

Filed Under: Core Java Tagged With: ArrayList custom Implementation

Difference between volatile and synchronized keyword?

May 25, 2017 By j2eereference Leave a Comment

Difference between Volatile and synchronized Keyword is very popular java question asked in Multithreading and concurrency interviews. Here are few differences listed down :

1) Volatile in java is a keyword which is used in variable declaration only and cannot be used with method. We will get compilation error if using volatile with method.

Syntax to use volatile with variable:

volatile Boolean flag ;

While synchronization keyword is used in method declaration or can be used to create synchronization blocks. We will get compilation error if we define variables as synchronized

How to use Synchronized method and Synchronized block

Synchronized method:
synchronized void executeMethod(){
//write code inside synchronized method
}

Synchronized block:
void executeMethod(){
synchronized (this)
{
//write code inside synchronized block
}
}

2) Volatile variables read values from main memory and not from cached data so volatile variables are not cached whereas variables defined inside synchronized block are cached.

3) Volatile variables are lock free which means that it does require any lock on variable or object whereas synchronized requires lock on method or block .

4) Volatile variable can be null whereas we will get NullPointerException in case we use null object.

5) As volatile never acquires any kind of lock ,so it will never create deadlock in program. But in case of synchronized we might end up creating deadlock if synchronization is not done properly.

6) Synchronized keyword may cause performance issue as one thread wait for another thread to release lock on shared object whereas volatile variable is lock free and hence is not much expensive in terms of performance.

7) Using synchronization thread can be blocked when waiting for other thread to release lock but not in the case of volatile keyword.

8) Volatile keyword is suitable When there is an independent value to be share among multiple threads like counter and flag.
Whereas synchronization is used in the scenario where we are using multiple variables very frequently and these variables are performing some calculation.

Related Posts

  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID
  • What is exchanger in concurrency?
  • UncaughtExceptionHandler in java
  • How to generate and resolve OutOfMemoryError?
  • Difference between Spring’s Singleton scope & Singleton Design pattern
  • How to stop a thread?
  • Interrupting a thread in java
  • Implementing PriorityQueue

Filed Under: Core Java Tagged With: Difference between volatile and synchronized keyword, Synchronized keyword, Volatile Keyword, when to use volatile

How to write thread safe code?

May 24, 2017 By j2eereference Leave a Comment

It is very important to write thread safe code if application is multithreaded to avoid deadlock and race conditions. Below listed points should be followed in multithreading environment.

1. Use synchronized block or synchronized methods if code is accessed by multiple threads to avoid race conditions. Only one thread can enter synchronized method or block by acquiring lock on the object at a time and hence avoid race condition.

2. Use volatile variables When there is an independent value to be shared among mutiple threads like counter and flag. Volatile variables read values from main memory and not from cache and in this way get updated value of variables.This also avoid race condition.

3. As we know, every thread has its own stack which contains local variables and value of local variables are confined to that thread stack and not be shared with other threads running in the same process. So, local variables are thread safe and if possible try to use local variables.

4. Use Atomic Classes like AtomicInteger as atomic operations are thread safe.

5. Final variables are also thread safe as once we assign any value or reference of an object then it cannot change value of variable or point to other object reference later in the code.

We declare and assign final variable of integer type with value 10 before calling executeMethod. Inside executeMethod we are trying to change the value of i to 0 then it will give compilation error.

public class FinalDemo {
final int i=10;
void executeMethod(){
i=0; //compilation error
}
}

6. If you are building multithreading application then use thread-safe collection classes for code safety like use ConcurrentHashMap in place of HashMap.

7. Use ThreadLocal Class as this class provides thread-safe local variables.

8. Use Immutable Objects like String rather than StringBuffer which is mutable . Immutable Objects are thread safe as their state cannot be changed once created and any state change will produce new object.

9. Use VisualVM or jstack to detect deadlock problems and time taken by threads for completing its task.

Related Posts

  • Busy Spinning in mutithreading
  • Implementing queue in java
  • TreeSet vs ConcurrentSkipListSet
  • How to create immutable class?
  • Implementing Stack in java
  • What is ReentrantLock?
  • What is Semaphore in java
  • Why AtomicInteger class
  • What is CyclicBarrier?
  • CountDownLatch in java

Filed Under: Core Java Tagged With: guidelines to thread-safe code, How to write thread safe code

How to avoid deadlock in java ?

May 23, 2017 By j2eereference 1 Comment

Conditions to avoid deadlock :
1)Lock Ordering : Deadlock occurs when multiple threads need same locks but acquired in different order and hence get blocked. In order to avoid this ,make sure that threads acquire the needed locks in same order so that one thread is able to complete its task and releases the locks and after that other thread can resume its processing.
Below program doesnot follow lock ordering and results in deadlock condition .In program output you can check that neither Thread-A not thread-B complete their processing as statement is never printed

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
public class DeadLockDemo
{
  public static void main(String[] args)
  {
    Thread threadA = new Thread("Thread-A")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
        {
          try {
                Thread.sleep(100);
              } catch (InterruptedException e)
              {
                e.printStackTrace();
              }
         System.out.println(Thread.currentThread().getName()
         + " has acquired lock on Integer class and waiting to acquire lock
         on Float class to complete its processing");
        synchronized (Float.class)
        {
           System.out.println(Thread.currentThread().getName()
           + " has acquired lock on Float class");
        }
       }
       System.out.println(Thread.currentThread().getName()+ " has completed its processing");
      }
    };
  Thread threadB = new Thread("Thread-B")
  {
    public void run()
    {
      System.out.println(Thread.currentThread().getName()+ " has started its processing");
      synchronized (Float.class)
      {
        System.out.println(Thread.currentThread().getName()
        + " has acquired lock on Float class and waiting to acquire lock on Integer class");
        try {
              Thread.sleep(100);
            } catch (InterruptedException e)
            {
              e.printStackTrace();
            }
      synchronized (Integer.class)
      {
        System.out.println(Thread.currentThread().getName()
        + " has acquired lock on Integer class");
      }
     }
   System.out.println(Thread.currentThread().getName()+ " has completed its processing");
  }
};
   threadA.start();
   threadB.start();
}
}

OutPut:
Thread-B has started its processing
Thread-A has started its processing
Thread-B has acquired lock on Float class and waiting to acquire lock on Integer class
Thread-A has acquired lock on Integer class and waiting to acquire lock on Float class to complete its processing

Now, change the order of locks in the above program by taking lock on Integer class first and then Float class. In Program Output , you can check that now both Thread-a and Thread-B are able to complete their task.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
public class DeadLockDemo
{
  public static void main(String[] args)
  {
    Thread threadA = new Thread("Thread-A")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
        {
          try {
                Thread.sleep(100);
              } catch (InterruptedException e)
              {
                e.printStackTrace();
              }
              System.out.println(Thread.currentThread().getName()
              + " has acquired lock on Integer class and waiting to acquire lock on
              Float class to complete its processing");
 
       synchronized (Float.class)
       {
         System.out.println(Thread.currentThread().getName()
         + " has acquired lock on Float class");
       }
      }
        System.out.println(Thread.currentThread().getName()+ " has completed its processing");
     }
    };
 
    Thread threadB = new Thread("Thread-B")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
        {
          System.out.println(Thread.currentThread().getName()+ " has acquired lock on Float class and waiting to acquire lock on Integer class...");
          try
          {
            Thread.sleep(100);
          } catch (InterruptedException e)
          {
            e.printStackTrace();
           }
 
         synchronized (Float.class)
         {
           System.out.println(Thread.currentThread().getName()
           + " has acquired lock on Integer class");
          }
         }
           System.out.println(Thread.currentThread().getName()+ " has completed its processing");
        }
       };
 
       threadA.start();
       threadB.start();
  }
}

OutPut :
Thread-A has started its processing
Thread-B has started its processing
Thread-B has acquired lock on Float class and waiting to acquire lock on Integer class…
Thread-B has acquired lock on Integer class
Thread-B has completed its processing
Thread-A has acquired lock on Integer class and waiting to acquire lock on Float class to complete its processing
Thread-A has acquired lock on Float class
Thread-A has completed its processing

2)Avoid nested synchronization blocks as it makes a thread to acquire another lock while it already holds one lock.This can result in deadlock in case if other thread wants to use the same lock which is held by this thread.

3)Lock the code where it is actually required and not the whole method ,so use synchronized blocks around the specific lines of code that you want to make thread safe in place of synchronized method.

4)Lock Timeout: another way to prevent deadlock is to specify time for a thread to acquire lock and If thread fails to acquire the lock in the specified time then it should give up trying for that lock and retry after some time.

5)Use Join() Method : Using join method threads can start and end sequentially as join method waits for a thread to complete its task on which it is called and then start the next thread processing.

 

Related Posts

  • Prototype design pattern
  • Interface changes in java 8
  • Generics wildcard arguments
  • Hashing techniques in java
  • Difference between comparator and comparable
  • Externalization in Java
  • insertion sort algorithm in java
  • Merge sort algorithm in java
  • Quicksort algorithm in java
  • bubble sort algorithm in java

Filed Under: Core Java Tagged With: Conditions to avoid deadlock, Deadlock, Lock ordering to prevent deadlock, lock timeout

What is deadlock in java?

May 22, 2017 By j2eereference 1 Comment

What is Deadlock : A deadlock  is the situation where two or more threads are holding lock on resources and  waiting for each other to release the lock  from the resources in order to complete their task.

Let’s assume, Thread 1 has acquired lock on Resource 1 and requesting for Resources 2 and Thread 2 has acquired lock on Resource2 and requesting for Resource1. So, Thread1 needs Resource 2 which is held by Thread2 to complete its task whereas Thread2 needs Resource1 which is held by thread1 to complete its task.

DeadLock Example :

In below Program, Thread-A is waiting for Thread-B to release lock on Float.class and Thread-B is waiting for Thread-A to release lock on Integer.class .Deadlock is formed here as both threads are blocked and waiting for each other to release the lock. Please note down one thing that in the output statement  ” has completed its processing ” is  never printed in and this is because of deadlock between Thread-A & Thread-B is never ended.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
public class DeadLockDemo {
  public static void main(String[] args)
  {
    Thread threadA = new Thread("Thread-A")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Integer.class)
       {
        try {
              Thread.sleep(100);
            } catch (InterruptedException e)
            {
              e.printStackTrace();
            }
             System.out.println(Thread.currentThread().getName()
             + " has acquired lock on Integer class and waiting to acquire lock on Float
              class to complete its processing");
            synchronized (Float.class)
            {
              System.out.println(Thread.currentThread().getName()+ " has acquired lock on Float class");
            }
       }
             System.out.println(Thread.currentThread().getName()+ " has completed its processing");
      }
    };
 
    Thread threadB = new Thread("Thread-B")
    {
      public void run()
      {
        System.out.println(Thread.currentThread().getName()+ " has started its processing");
        synchronized (Float.class)
        {
           System.out.println(Thread.currentThread().getName()+ " has acquired lock on Float class and waiting to acquire lock on Integer class");
           try {
                 Thread.sleep(100);
               } catch (InterruptedException e)
               {
                  e.printStackTrace();
                }
            synchronized (Integer.class)
            {
               System.out.println(Thread.currentThread().getName()+ " has acquired lock on Integer class");
             }
          }
               System.out.println(Thread.currentThread().getName()+ " has completed its processing");
        }
     };
 
      threadA.start();
      threadB.start();
   }
}

OutPut:

Thread-B has started its processing
Thread-A has started its processing
Thread-B has acquired lock on Float class and waiting to acquire lock on Integer class
Thread-A has acquired lock on Integer class and waiting to acquire lock on Float class to complete its processing

Conditions for deadlock to occur:

1)Mutual Exclusion: In this condition, only one thread at a time can hold the shared resource exclusively and use it other requesting threads must wait for this thread to release the shared resource.

2)Hold and wait: In this condition, thread must hold the allocated resource while waiting for other resource which is currently being held by other thread.

3)Circular wait: In this, a circular waiting chain is formed where each thread in the list is waiting for the resource being held by next thread in the list.

4)No Preemption: Operating system must not remove the resource allocated to a thread until thread execution completed or released voluntarily by the thread holding it.

Related Posts

  • Selection Sort in java
  • Access Modifiers in Java
  • Difference between ArrayList and CopyOnWriteArrayList
  • Synchronized Map and ConcurrentHashMap
  • Reading file using Java 7 and Java 8
  • Temporal Adjusters in Java 8
  • Period class in Java 8
  • Date in Java 8
  • Singleton in Clustered Environment
  • Enumeration and Iterator

Filed Under: Core Java Tagged With: Deadlock, Deadlock condition, Deadlock creation program, what is deadlock

Difference between Serializable and Externalizable

May 19, 2017 By j2eereference Leave a Comment

1)Serializable is a marker interface which doesn’t have any method where as Externalizable extends Serializable interface and it provides method : writeExternal() and readExternal()

2)In Serializable , we only need to implement serializable interface which in turn provides its own default serialization process.
In Externalizable,we require to override writeExternal() and readExternal() methods to start serialization process.

3)In Serializable interface constructor is not called during deserialization process where as constructor is called during deserialization process in externalizable interface.

4)We can customize default serialization process of Serializable interface by defining methods readObject() and writeObject() of ObjectInputStream Class whereas in Externalizable interface ,serialization process is completely customized as we require to override method writeExternal() and readExternal().

5)Serializable interface provides less control over serialization because it is not mandate to use readObject() and writeObject() method as Serializable is a marker interface which provides default serialization process .On other hand Externalizable provides full control on serialization process as it is mandatory to override writeExternal() and readExternal() methods.

6)Externalizable interface gives better performance as using default serialization process of serializable interface we cant do much except making some non-required fields as transient and static but with Externalizable interface we can have full control over Serialization process.

7)In Serializable interface , it is very tough to modify class structure as any modification may break the serialization where as in Externalizable it is easy to modify class structure as developer has complete control over serialization logic.

Default Constructor is not getting called during Deserialization process if we implement Serializable Interface:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
 
class StudentInformation implements  Serializable
{
  private static final long serialVersionUID = 1L;
  private Integer rollNo;
  private String name;
  public StudentInformation()
  {
    System.out.println("No argument constructor is called");
  }
  public StudentInformation(Integer rollNo,String name)
  {
    System.out.println("Parameterised constructor is called");
    this.rollNo = rollNo;
    this.name = name;
  }
  @Override
  public String toString()
  {
    return "Student Information is rollNo : " + rollNo + "and Student name is : "+name ;
  }
}
 
public class SerializableDemo
{
   public static void main(String[] args) {
   StudentInformation object1 = new StudentInformation(21,"Shobhna");
   try {
         OutputStream fout = new FileOutputStream("ser.txt");
         ObjectOutput oout = new ObjectOutputStream(fout);
         System.out.println("Serializing StudentInformation object");
         oout.writeObject(object1);
         fout.close();
         oout.close();
         System.out.println("Serialization process completed.");
 
         InputStream inputStream=new FileInputStream("ser.txt");
         ObjectInput outInput=new ObjectInputStream(inputStream);
         System.out.println("");
         System.out.println("DeSerializing StudentInformation objects");
         StudentInformation std=(StudentInformation)outInput.readObject();
         System.out.println(std);
         inputStream.close();
         outInput.close();
         System.out.println("Object DeSerialization completed.");
      } catch (IOException | ClassNotFoundException  e) {
        e.printStackTrace();
      }
   }
}

OutPut :
Parameterised constructor is called
Serializing StudentInformation object
Serialization process completed.

Deserializing StudentInformation objects
Student Information is rollNo : 21and Student name is : Shobhna
Object Deserialization completed.

Default Constructor is getting called during Deserialization process if we implement Externalizable Interface:

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
 
class StudentDetail implements Externalizable 
{
   private static final long serialVersionUID = 1L;
   private Integer rollNo;
   private String name;
   public StudentDetail()
   {
     System.out.println("No argument constructor is called");
   }
   public StudentDetail(Integer rollNo,String name)
   {
     System.out.println("Parameterised constructor is called");
     this.rollNo = rollNo;
     this.name = name;
   }
  @Override
  public String toString()
  {
    return "Student Information is rollNo : " + rollNo + "and Student name is : "+name ;
  }
 
 @Override
public void writeExternal(ObjectOutput oo) throws IOException
{
   oo.writeInt(rollNo);
   oo.writeObject(name);
}
 
public void readExternal(ObjectInput in) throws IOException,  ClassNotFoundException
{
   this.rollNo=in.readInt();
   this.name=(String) in.readObject();
}
 
}
public class ExternalizableDemo
{
  public static void main(String[] args) {
  StudentDetail studentDetail = new StudentDetail(21,"Shobhna");
  try {
        OutputStream fout = new FileOutputStream("ser.txt");
        ObjectOutput oout = new ObjectOutputStream(fout);
        System.out.println("Deserializating StudentDetail object");
        oout.writeObject(studentDetail);
        fout.close();
        oout.close();
        System.out.println("Serialization completed.");
       //DeSerialization process >
 
       InputStream fin=new FileInputStream("ser.txt");
       ObjectInput oin=new ObjectInputStream(fin);
       System.out.println("\nDeSerializating StudentDetail object");
       StudentDetail stDetail=(StudentDetail)oin.readObject();
       System.out.println(stDetail);
       fin.close();
       oin.close();
       System.out.println("DeSerialization completed.");
     } catch (IOException | ClassNotFoundException  e)
     {
       e.printStackTrace();
     }
  }
}

OutPut:

Parameterised constructor is called
Deserializating StudentDetail object
Serialization completed.

DeSerializating StudentDetail object
No argument constructor is called
Student Information is rollNo : 21and Student name is : Shobhna
DeSerialization completed.

Please have a look at the posts on Serializable and Externalizable.

 

 

Related Posts

  • Difference between HashMap and HashTable
  • OCJP Quiz
  • JAVA QUIZ
  • Volatile Keyword in JAVA
  • Setting PDF content properties using iText
  • Using Regular Expression in Java
  • Creating PDF file using itext
  • Accessing Private method outside the class
  • Starting tomcat in Debug mode
  • Scanner

Filed Under: Core Java Tagged With: Difference between Serializable and Externalizable, Externalizable, Externalizable program, Serializale

Binary search tree implementation in java

May 18, 2017 By j2eereference Leave a Comment

Binary Search Tree: Binary search tree is a hierarchical data structure which is used to store data.In a binary tree each node has maximum of two children.Binary Search tree shows a special feature given below:

  •  Value of Left child node should be less than its parent’s node value
  • Value of right child node should be greater than its parent’s node value.

Important terms used in Binary tree:

  • Root :Topmost node of the tree is called root node.
  • Child Node: Child node is a node which is below a given node and connected through an edge in downward direction.
  • Parent Node : Any node except root node which is above a given node and connected through an edge in upward direction.
  • Leaf : Leaf node is the node which does not have any children
  • Keys : Key represents value of a node.
  • Path : Path represents sequence of nodes along the edges.
  • Levels : Root node is at level 0 and next child node is at Level 1 ,so Level represents height of tree from the root node.
  • Visiting : checking the value of node during traversal.

Binary search Tree implementation in Java

In the below program , we will implement Binary search tree using Java.

newNode() method will insert node in the binary tree, first inserted node is root node which is 6 in our example. Inside newNode() method we are checking whether new node value is less than or greater than root node value 6. If it is greater than 6 then keep this node at the left side of root node 6 otherwise keep the given node at the right side. In this way we are calling newNode method recursively to check and insert the given node at the correct place.
printTree() method will first print left nodes then root node and then right node using recursion.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Node
{
   public int data;
   public Node left;
   public Node right;
}
 
public class BinaryTree
{
   static Node newNode(int data, Node node)
   {
      if(node==null)
      {
          node = new Node();
          node.data = data;
          node.left = null;
          node.right=null;
          return node;
       }
       else
       {
          Node current=node;
          if(data >=current.data)
          {
             current.right= newNode(data,current.right);
          }
          else if(data < current.data)
          {
             current.left=newNode(data,current.left);
          }
       }
       return node;
   }
 
   static void printTree(Node root)
   {
       if(root!=null)
       {
          printTree(root.left);
          System.out.print(root.data +"  ");
          printTree(root.right);
        }
    }
 
    public static void main(String[] args)
    {
       Node rootNode = null;
       rootNode=newNode(6, rootNode);
       rootNode=newNode(2, rootNode);
       rootNode=newNode(3, rootNode);
       rootNode=newNode(8, rootNode);
       rootNode=newNode(7, rootNode);
       rootNode=newNode(1, rootNode);
       rootNode=newNode(5, rootNode);
       rootNode=newNode(10, rootNode);
       printTree(rootNode);
    }
}

Output:

1  2  3  5  6  7  8  10

6 is root node

Type of Traversals in binary Tree:

  • Preorder Traversal– In Preorder traversal, first of all root node is visited then traverse the left subtree and at last traverse the right subtree

          Visit Root–>Left Subtree traversal –> Right Tree Traversal

For binary tree given in above example,Preorder would be 6,1,2,3,5,7,8,10

  • Inorder Traversal− In Inorder traversal, traverse the left subtree then visit the root node and at last traverse the right subtree

Left Subtree traversal –>Visit Root–>Right Tree Traversal

          For binary tree given in above example,Preorder would be 1,2,3,5,6,7,8,10

  • Postorder Traversal− − In Postorder traversal, traverse the right then visit the traverse the left subtree and at last visit the root node.

Right Tree Traversal->Left Subtree traversal –>Visit Root

           For binary tree given in above example,Preorder would be 7,8,10,1,2,3,5,6

 Use cases of Binary Search Tree:

1)Binary Search Tree is used in Search applications like dictionary

2) It is used in multilevel indexing in database

Related Posts

  • Static import
  • String constructors
  • ProcessBuilder
  • Assert in java
  • Batch Processing in JDBC
  • Deque in Java Collection
  • Navigable Map
  • Daemon thread
  • Object Cloning in Java
  • varargs in Java

Filed Under: Core Java Tagged With: Binary search Tree, Binary search tree creation, binary search tree property, Binary Tree

How HashSet internally works ?

May 17, 2017 By j2eereference Leave a Comment

What is HashSet: HashSet is a class that extends AbstractSet and implements set interface which stores unique elements only.

Internal Implementation of HashSet Class: If you check internal implementation of  HashSet  class it internally uses HashMap to store elements.   Below code gives you good understanding of how HashSet internally works.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public class HashSet<E> extends AbstractSet<E>implements Set<E>, Cloneable, java.io.Serializable
{
  static final long serialVersionUID = -5024744406713321676L;
  private transient HashMap<E,Object> map;
 
  // Dummy value to associate with an Object in the backing Map
  private static final Object PRESENT = new Object();
  /**
  * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
  * default initial capacity (16) and load factor (0.75).
  */
  public HashSet() {
    map = new HashMap<>();
  }
  public boolean add(E e) {
   return map.put(e, PRESENT)==null;
  }
}

As you can see above whenever you create HashSet Object , HashSet constructor also creates a HashMap object. This HashMap Object will store the elements which you have entered in the HashSet. If you check add method of HashSet in the above code  you can see that inside add method put method of HashMap is used to store elements where key is the element you want to store and value is the constant named as PRESENT.

Some important points to be remember:

  • HashSet stores unique elements only.
  • It gives constant time performance for insertion,retrieval and removal operations.
  • It allows only one null element.
  • HashSet class is not synchronized ,so can not be accessed by multiple threads .If you want to use HashSet in multi-threaded environment , use Collections.SynchronizedSet() method.

Example o f HashSet :

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import java.util.HashSet;
import java.util.Iterator;
 
class Employee
{
  String empName;
  int empID;
  String department;
  public Employee(String empName , int empID, String department)
  {
    this.empName = empName;
    this.empID = empID;
    this.department = department;
  }
  @Override
  public int hashCode()
  {
    return empID;
  }
  @Override
  
  public boolean equals(Object obj)
  {
    Employee emp = (Employee) obj;
    return (empID == emp.empID);
  }
 
  @Override
  public String toString()
  {
    return "Employee Id is :"+empID+" & employee name is : "+empName+" & department is : "+department;
  }
}
 
public class HashSetDemo
{
   public static void main(String[] args)
   {
     HashSet< Employee > set = new HashSet< Employee >();
     //Adding elements to HashSet
     set.add(new Employee("Shobhna", 125128, "Senior Associate"));
     set.add(new Employee("Gurpal", 74077, "Project Manager"));
     set.add(new Employee("Shilpi", 15061, "QA"));
     set.add(new Employee("Nishant", 7974758, "BA"));
     set.add(new Employee("Anil", 125128, "Software Engineer"));//duplicate element
     iterator< Employee> it = set.iterator();
     while (it.hasNext())
     {
       Employee emp = (Employee) it.next();
       System.out.println(emp);
     }
   }
  }

OutPut:
Employee Id is :15061 & employee name is : Shilpi & department is : QA
Employee Id is :125128 & employee name is : Shobhna & department is : Senior Associate
Employee Id is :74077 & employee name is : Gurpal & department is : Project Manager
Employee Id is :7974758 & employee name is : Nishant & department is : BA

In above example ,  hashCode() and equals() methods are overridden in Employee class so that Employees will be compared based on empId. Two Employee objects having same empId will be considered as duplicates irrespective of other fields. In given example,duplicate entry for employee Anil will not be stored in the HashSet as empId of Anil is same as of Shobhna.

Related Posts

  • Transient Variable
  • Java versions
  • Dynamic Binding and Static Binding in Java
  • Creating log in XML format
  • Shutdown Hooks API
  • User defined exception in java
  • Different ways of creating object in java
  • Immutable Object
  • Comparable Interface
  • Optimize j2ee Application

Filed Under: Core Java Tagged With: Colllection framework, HashSet, HashSet internal working, Set Interface

BlockingQueue Implementation

May 16, 2017 By j2eereference Leave a Comment

BlockingQueue :

java.util.concurrent.BlockingQueue is an interface that extends the java.util.Queue that add special support for blocking that it will wait for space to become available in the queue while storing and will wait for the queue to become non empty while retrieving elements.

Implementation of BlockingQueue :

  • util.concurrent.ArrayBlockingQueue : ArrayBlockingQueue is a fixed size bounded queue
  • util.concurrent.DelayQueue : The queue is unbounded and Elements added to the queue must implement thejava.util.concurrent.Delayed interface. Elements can be retrieved from the queue when the delay time has expired.
  • util.concurrent.LinkedBlockingQueue : LinkedBlockingQueue is an optionally-bounded blocking queue. This queue orders elements FIFO (first-in-first-out). The LinkedBlockingQueue keeps the elements internally in a linked structure
  • util.concurrent.PriorityBlockingQueue : A priority queue is unbounded queue where elements are ordered by natural order or by a Comparator provided at queue construction time .It does not permit null elements.
  • util.concurrent.SynchronousQueue : SynchronousQueue is a queue that can only contain a single element .In a SynchronousQueue an insert will wait for a remove operation by another thread and vice versa.

ArrayBlockingQueue implementation of BlockingQueue.

As already mentioned above, an ArrayBlockingQueue is a fixed size bounded queue. It is backed by array. As it is a BlockingQueue , its put(e) method will block a thread and waits for space to become available in the queue, and its take() method will block other thread and wait for an element become available in the queue. It is declared as given below

private static BlockingQueue<String> bq = new ArrayBlockingQueue<String>(no_of_element);

 Methods of ArrayBlockingQueue :

 put(E item) method in java –This method checks whether space is available or not.If space is not available it will wait else it will insert element and notify all waiting threads in java.

E take() method in java -This method Checks whether element is available or not.If element is not available it will wait else it will remove element and notify all waiting threads in java.

 Peek(): This method gets the element from head but not removed and returns null if not available

element(): This method gets the element from head but not removed and throw exception if not available

Example of ArrayBlockingQueue:

Java
1
2
3
4
5
6
7
8
9
10
11
12
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
 
public class BlockingQueueDemo {
   public static void main(String args[]){
      BlockingQueue<Integer> sharedQueue = new ArrayBlockingQueue<Integer>(5);
      Thread producerThread = new Thread(new ProducerThread(sharedQueue), "ProducerThread");
      Thread consumerThread = new Thread(new ConsumerThread(sharedQueue), "ConsumerThread");
      producerThread.start();
      consumerThread.start();
  }
}

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import java.util.concurrent.BlockingQueue;
 
class ConsumerThread implements Runnable{
      private BlockingQueue<Integer> sQueue;
      public ConsumerThread (BlockingQueue<Integer> sQueue) {
         this.sQueue = sQueue;
      }
 
      @Override
      public void run() {
       while(true){
         try {
              System.out.println("Consumer retrieved item : "+ sQueue.take());
             } catch (InterruptedException ex) {
            }
       }
      }
    }

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.concurrent.BlockingQueue;
 
class ProducerThread implements Runnable {
 
      private final BlockingQueue<Integer> sQueue;
      public ProducerThread(BlockingQueue<Integer> sQueue) {
         this.sQueue = sQueue;
      }
 
      @Override
      public void run() {
       for(int i=1; i<=5; i++){
        try {
              System.out.println("Producer produced item: " + i);
              sQueue.put(i);
            } catch (InterruptedException ex) {
            }
       }
     }
   }

Output:
Producer produced item: 1
Producer produced item: 2
Producer produced item: 3
Producer produced item: 4
Producer produced item: 5
Consumer retrieved item : 1
Consumer retrieved item : 2
Consumer retrieved item : 3
Consumer retrieved item : 4
Consumer retrieved item : 5

Realtime Use cases:
1) Realtime use case for BlockingQueue is Chat application in which messages are put into a queue. Produces will produce the messages from one end and consumer will consume messages.

2) ThreadPoolExecutor uses BlockingQueue to put executable task which get executed by worker threads.

3) A real world example could be an application-wide notification framework, which sends mails to the stakeholders at various points during the course of application usage.

Related Posts

  • Optimizing Loop
  • Generics
  • Autoboxing
  • TreeSet
  • Interaction between Threads
  • Features added in Java 1.7
  • LinkedList
  • Enums
  • Interface
  • Features added in JDBC 4.1

Filed Under: Core Java

  • « Go to Previous Page
  • Go to page 1
  • Go to page 2
  • Go to page 3
  • Go to page 4
  • Go to page 5
  • Go to page 6
  • Interim pages omitted …
  • Go to page 14
  • Go to Next Page »

Primary Sidebar

FOLLOW US ONLINE

  • View J2eereference-166104970118637’s profile on Facebook
  • View j2eereference’s profile on Twitter
  • View j2eereference’s profile on LinkedIn

Subscribe by email

Recent posts

  • What is parallel Stream
  • reduce method of the Stream class
  • Difference between the findFirst() and findAny() method
  • intern() method of String class
  • SOLID – Five principles of object-oriented software design
  • Java Coding Best Practices
  • How to use lambda expression effectively
  • Enhanced pseudo-Random Number Generators in java17
  • How to use Foreign-Memory Access API
  • Pattern Matching for instanceof
  • Text Blocks – Feature added in Java17
  • Record – The new feature added in java 17
  • What is Sealed Class
  • Features added in Java 17
  • Java Buzzwords

Footer

Core Java
Design Patterns
JSP
Servlets
HTML
Building Tools
AJAX
SCJP
jQuery
Testing
Spring
UML
Struts
Java Centers
Java Training
Home
About Us
Contact Us
Copyright © j2eereference.com. All right reserved.