• Skip to primary navigation
  • Skip to 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 exchanger in concurrency?

June 12, 2017 By j2eereference Leave a Comment

Exchanger :

Exchanger is introduced in jdk1.5 with classes like CountDownLatch,CyclicBarrier and Semaphores.

This class is used to exchange data between two threads. An Exchanger waits until both the threads call its exchange() method and when this method is invoked, the exchanger exchanges data between two threads. It uses method exchange for exchanging data .

 It has two version of exchange method given below :

  • V exchange(V x): This method will wait until other thread calls exchange method or interrupts it. When other thread calls exchange method then waiting thread resumed and data exchanging is done between two threads.
  • V exchange(V x, long timeout, TimeUnit unit) : This method will wait until other thread calls exchange method or interrupts it or specified time elapses. . When other thread calls exchange method then waiting thread resumed and data exchanging is done between two threads.

Example to demonstrate Exchanger :

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
import java.util.concurrent.Exchanger;
class ProducerBuffer implements Runnable {
  Exchanger<String> exchanger;
  String message;
  ProducerBuffer(Exchanger<String> exchanger) {
     message = new String();
     this.exchanger = exchanger;
  }
 
@Override
public void run() {
    for (int i = 0; i < 10; i++) {
      message += i;
      System.out.println("Producer produced message: " + message);
      try {
       message = exchanger.exchange(message);
     } catch (InterruptedException e) {
       e.printStackTrace();
     }
   }
}
}
 
class ConsumerBuffer extends Thread {
  ProducerBuffer prod;
  Exchanger<String> exchanger;
  String message;
  ConsumerBuffer(Exchanger<String> exchanger) {
     this.exchanger = exchanger;
  }
 
  public void run() {
   for (int i = 0; i < 10; i++) {
     try {
       message = exchanger.exchange(new String());
       System.out.println("Consumer consumed message: " + message);
     } catch (InterruptedException e) {
       e.printStackTrace();
    }
   }
  }
}
public class ExchangerDemo {
  public static void main(String[] args) {
   Exchanger<String> exchanger = new Exchanger<String>();
   ProducerBuffer prodBuffer = new ProducerBuffer(exchanger);
   ConsumerBuffer consBuffer = new ConsumerBuffer(exchanger);
   Thread prodThread = new Thread(prodBuffer, "prodThread");
   Thread consThread = new Thread(consBuffer, "consThread");
   prodThread.start();
   consThread.start();
  }
}

OutPut:

Producer produced message: 0
Producer produced message: 1
Consumer consumed message: 0
Consumer consumed message: 1
Producer produced message: 2
Consumer consumed message: 2
Producer produced message: 3
Consumer consumed message: 3
Producer produced message: 4
Consumer consumed message: 4
Producer produced message: 5
Consumer consumed message: 5
Producer produced message: 6
Consumer consumed message: 6
Producer produced message: 7
Consumer consumed message: 7
Producer produced message: 8
Consumer consumed message: 8
Producer produced message: 9
Consumer consumed message: 9

Real Time usecase:
Exchanger is mainly used which implements Producer consumer problem as booth threads exchange data between each other

 

Related Posts

  • 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
  • Callable and Future Interface
  • Difference between Stack and Heap memory
  • What is ThreadMXBean in java?
  • What is serialVersionUID

Filed Under: concurrent package, Core Java

UncaughtExceptionHandler in java

June 6, 2017 By j2eereference Leave a Comment

UnCaughtExceptionHandler: There are two kinds of exceptions in Java one is checked exceptions and other is  Unchecked exceptions. We already know about checked and unchecked exception.

In this tutorial we will learn about UnCaughtExceptionHandler. Unchecked exceptions don’t have to be caught and when an unchecked exception is thrown inside the run() method of a Thread , the default behavior is to write the stack trace and exit the program.

For this , Java provides an elegant mechanism of handling Runtime Exceptions that is not handled by programmer to avoid the program ending abruptly using UnCaughtExceptionHandler.

When a thread terminates due to an uncaught runtime exception ,JVM will consult the thread for its UncaughtExceptionHandler using method Thread.getUncaughtExceptionHandler() which then will invoke the handler’s uncaughtException method.

If the thread doesn’t have an explicitly UncaughtExceptionHandler then its ThreadGroup will act as its UncaughtExceptionHandler and exhibit the default behavior to write the stacktrace.

Program to demonstrate:

Lets see below program , in this we throw Runtime Exception and handles it using UncaughtExceptionHandler . Inside uncaughtException method of handler we print information about thread which has failed and exception information.

 

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
package com.j2eereference;
 
 
public class UnCaughtExceptionHandlerDemo {
 
   public static void main(String[] args) {
 
      Thread t = new Thread(new MyRunnableDemo());
      t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
 
         public void uncaughtException(Thread t, Throwable e) {
         System.out.printf("An exception has been handled\n");
             System.out.printf("Thread Id: %s\n", t.getId());
             System.out.printf("Thread status: %s\n", t.getState());
             System.out.printf("Thread priority: %s\n", t.getPriority());
             System.out.printf("Exception type: %s: %s\n", e.getClass().getName(), e.getMessage());
             System.out.printf("Stack Trace description: \n");
             e.printStackTrace(System.out);
            
          
         }
      });
      
      t.start();
   }
}
 
class MyRunnableDemo implements Runnable {
 
   public void run() {
      throw new RuntimeException();
  
   }
}

OutPut :

An exception has been handledThread Id: 10

Thread status: RUNNABLE

Thread priority: 5

Exception type: java.lang.RuntimeException: null

Stack Trace description:

java.lang.RuntimeException at com.j2eereference.MyRunnableDemo.run(UnCaughtExceptionHandlerDemo.java:31)at java.lang.Thread.run(Thread.java:745)

Where to use :

  • We can use UncaughtExceptionHandler for making logging more informative as well often default logs doesn’t provide enough information about the exception when thread execution failed.
  • It can also be used In real life application where programmer would like to start a failed thread more than once to perform a critical task even if it failed couple of times by again starting thread from UnCaughtExceptionHandler.

 

 

Related Posts

  • How to avoid deadlock in java ?
  • What is deadlock in java?
  • Difference between Serializable and Externalizable
  • Binary search tree implementation in java
  • How HashSet internally works ?
  • BlockingQueue Implementation
  • Implementing PriorityQueue
  • Busy Spinning in mutithreading
  • Implementing queue in java
  • TreeSet vs ConcurrentSkipListSet

Filed Under: Core Java Tagged With: ExceptionHandling, UncaughtExceptionHandler

How to generate and resolve OutOfMemoryError?

June 2, 2017 By j2eereference Leave a Comment

OutOfMemoryError in java can occur because of many reasons like Java heap space, GC Overhead limit exceeded, requested array size exceeds VM limit and many more. It is an indication of a memory leak .

Listed below are types of java.lang.OutOfMemoryError Error messages:

  • java.lang.OutOfMemoryError:Java heap space -> This exception is thrown when JVM heap size if full and the garbage collector is unable to reclaim objects
  • java.lang.OutOfMemoryError:Metaspace ->this exception is thrown when Metaspace area is exhausted.
  • java.lang.OutOfMemoryError:Unable to create new native thread ->this exception is thrown when java process size has reached its maximum limit(too many threads are spawned in a process)
  • java.lang.OutOfMemoryError:GC overhead limit exceeded->This exception is thrown when your application spends too much time doing garbage collection.
  • java.lang.OutOfMemoryError:Permgen space -> This exception is thrown when is thrown when PermGen space memory is full.
  • java.lang.OutOfMemoryError:Out of swap space -> This exception is thrown when when the JVM memory is full when there are too many processes running on the machine.
  • java.lang.OutOfMemoryError:Requested array size exceeds VM limit -> This exception is thrown when application is trying to allocate an array whose size exceeds than the Java Virtual Machine.

In this tutorial lets understand about OutOfMemoryError which is thrown when there is limited or insufficient space to allocate an object in the Java heap i.e java.lang.OutOfMemoryError: Java heap space

 Program to generate OutOfMemoryError: Java heap space

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.j2eereference;
 
import java.util.ArrayList;
import java.util.List;
 
public class OutOfMemoryDemo
{
   private static List<String> heapList=new ArrayList<String>();
   public static void main(String[] args)
     {
     while(true)
           {
             heapList.add(new String("Shobhna"));  
           }
      }
}

OutPut:
Exception in thread “main” java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Arrays.java:3210)
at java.util.Arrays.copyOf(Arrays.java:3181)
at java.util.ArrayList.grow(ArrayList.java:261)
at java.util.ArrayList.ensureExplicitCapacity(ArrayList.java:235)
at java.util.ArrayList.ensureCapacityInternal(ArrayList.java:227)
at java.util.ArrayList.add(ArrayList.java:458)
at com.j2eereference.OutOfMemoryDemo.main(OutOfMemoryDemo.java:11)
How to solve OutOfMemoryError – Java heap space ?
To solve OutOfMemoryError we need to increase the heap size using jvm parameter –Xmx

How to use -Xmx VM option in java
1) If you want to set the maximum heap size of JVM to 1024 bytes then use below command
java -Xmx1024 OutOfMemoryDemo

2) If you want to set the maximum heap size of JVM to 1024 kilobytes then use below command
java -Xmx1024k OutOfMemoryDemo

3) ) If you want to set the maximum heap size of JVM to 1024 megabytes then use below command
java -Xmx1024m OutOfMemoryDemo

4) If you want to set the maximum heap size of JVM to 1024 gigabyte then use below command
java -Xmx1024g OutOfMemoryDemo

 

 

Related Posts

  • 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
  • Prototype design pattern
  • Interface changes in java 8
  • Generics wildcard arguments

Filed Under: Core Java Tagged With: -Xmx parameter usage, Heap space error, OutOfMemoryError, to resolve OutOfMemoryError, Types of OutOfMemoryError

Difference between Spring’s Singleton scope & Singleton Design pattern

June 1, 2017 By j2eereference Leave a Comment

Singleton pattern is scoped by per Java class.
Singleton bean scope is scoped by per spring container.

In singleton pattern, Java considers a class as singleton if it cannot create more than one instance of that class within a given class loader whereas spring considers a bean class as singleton scope if it cannot create more than one instance of bean class within a given Applicationcontext(container).

Spring container will create exactly one instance of the defined bean. This single instance will be stored in a cache of singleton bean and same instance will be returned in all subsequent requests.

Very important point to discuss here is what happens if there are multiple containers and same class loader.Lets create one example to understand this.

In below Spring example, we have created two applicationContext object( in MainApp class) which are used to load the ‘student bean'(Student class). When the same bean is again loaded with different application context object then it will return ‘null’ as bean name because scope of bean is limited within an application context.

MainApp.java

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
package com.j2eereference;
 
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
 
public class MainApp {
 
  public static void main(String[] args)
  {
ApplicationContext factory = new ClassPathXmlApplicationContext(
                                     new String[] { "Applicationcontext.xml"});
Student student1 = (Student) factory.getBean("student");
student1.setName("Shikha");
        System.out.println("Bean name 1 : " + student1.getName());
        ApplicationContext factory2 = new ClassPathXmlApplicationContext(
                                      new String[] { "Applicationcontext.xml"});
                
          Student student2= (Student) factory2.getBean("student");  
                System.out.println("Bean name in case of new applicationcontext This Time : " + student2.getName());  
 
                System.out.println("context classloader: "+factory.getClassLoader());
                System.out.println("newContext classloader: "+factory2.getClassLoader());
        }
   }

Application context : ApplicationContext provides context information and contains definition of beans.

Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>  
<beans  
xmlns="http://www.springframework.org/schema/beans"  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
   xmlns:p="http://www.springframework.org/schema/p"  
  
  
   xmlns:aop="http://www.springframework.org/schema/aop"
   xsi:schemaLocation="http://www.springframework.org/schema/beans  
              http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
              http://www.springframework.org/schema/context
             http://www.springframework.org/schema/context/spring-context-3.0.xsd
             http://www.springframework.org/schema/aop
     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
            
            
 
 
<bean id="student" class="com.j2eereference.Student" scope="singleton" >
 
</bean>
 
</beans>  

Student.java

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
package com.j2eereference;
 
import java.util.List;
 
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
 
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.beans.factory.config.BeanPostProcessor;
 
public class Student {
private String name;
 
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
 
}

OutPut:
org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Tue May 16 16:18:19 IST 2017]; root of context hierarchy
May 16, 2017 4:18:19 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Applicationcontext.xml]
Bean name 1 : Shikha
May 16, 2017 4:18:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6a400542: startup date [Tue May 16 16:18:20 IST 2017]; root of context hierarchy
May 16, 2017 4:18:20 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Applicationcontext.xml]
Bean name 2 This Time : null
context classloader: sun.misc.Launcher$AppClassLoader@73d16e93
newContext classloader: sun.misc.Launcher$AppClassLoader@73d16e93
If you want to return same instance of class in in every subsequent request then comment lines in which we created second ApplicationContext as given in below code

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
package com.j2eerefernce;
 
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
 
public class MainApp {
 
public static void main(String[] args) {
ApplicationContext factory = new ClassPathXmlApplicationContext( new String[]
                                             { "Applicationcontext.xml"});
Student student1 = (Student) factory.getBean("student");
student1.setName("Shikha");
 
System.out.println("Bean name 1 : " + student1.getName());
   <strong>          //  ApplicationContext factory2 = new ClassPathXmlApplicationContext( new String[]
             //                                  { "Applicationcontext.xml"});</strong>
                
               Student student2= (Student) factory.getBean("student");  
                System.out.println("Bean name this Time : " + student2.getName());  
 
                System.out.println("context classloader: "+factory.getClassLoader());
               // System.out.println("newContext classloader: "+factory2.getClassLoader());
        }
 
}

Now run the MainApp , you will get OutPut as
May 16, 2017 4:43:33 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@179d3b25: startup date [Tue May 16 16:43:33 IST 2017]; root of context hierarchy
May 16, 2017 4:43:33 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [Applicationcontext.xml]
Bean name 1 : Shikha
Bean name this Time : Shikha
context classloader: sun.misc.Launcher$AppClassLoader@73d16e93

 

Please refer injecting singleton class with Spring to know more about singleton bean creation.

Related Posts

  • 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
  • Selection Sort in java
  • Access Modifiers in Java
  • Difference between ArrayList and CopyOnWriteArrayList

Filed Under: Core Java Tagged With: Difference between Spring's Singleton & Singleton Design pattern, Singleton Design pattern, Spring singleton bean example, Spring's singleton

How to stop a thread?

May 31, 2017 By j2eereference Leave a Comment

How to stop a thread?

In multithreading, we start a thread using start () method and we execute thread using run() method .Similarly we also have wait(),notify and sleep() method to let thread wait or sleep for sometime. But it is difficult to stop a thread as stop() method has been deprecated. So,we need to apply some logic to stop the thread . There can be many ways to stop a thread but in this tutorial we will use Boolean flag variable to stop a thread.

Why stop() method is deprecated in java:

When we stop a thread using Thread.stop() method it causes the thread to release all the acquired monitors and throw ThreadDeath error and cauese. If any of the objects previously locked by these monitors were in an inconsistent state, then it becomes visible to other threads, which may lead the program to some unexpected  behavior.

Program to stop a thread

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
class ThreadDemo extends Thread
{
    private volatile boolean stopFlag = true;
    public void stopThread()
    {
     stopFlag = false;
    }
    
    @Override
    public void run()
    {
        while (stopFlag)
        {
            System.out.println(Thread.currentThread().getName()+" is running");
        }
        
        System.out.println(Thread.currentThread().getName()+" has stopped running");
    }
}
public class ThreadStopDemo
{  
    public static void main(String[] args)
    {
     ThreadDemo threadDemo = new ThreadDemo();
        threadDemo.start();
        
   try
        {
            Thread.sleep(1000);
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        
        threadDemo.stopThread();
    }    
}

OutPut:

In above example, we declare one boolean volatile variable stopFlag in a thread. Set this flag value as true. Inside run() method use while loop by passing stopFlag .If flag value is true then keep the task performed in while loop and thread will continue to run until flag becomes false. We have defined stopThread() method which is called from main method after thread start .This method will set the stopFlag as false and stops the thread. Also note that we have declared flag as volatile. Every Thread has its own local memory so it is good practice to make stopFlag as volatile because value of stopFlag can be alter from any thread if not declared volatile and making it volatile guarantees that thread will always read updated value of stopFlag.

Related Posts

  • 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
  • Difference between HashMap and HashTable
  • OCJP Quiz
  • JAVA QUIZ

Filed Under: Core Java Tagged With: How to stop a thread, stopping a thread using volatile boolean flag

Interrupting a thread in java

May 30, 2017 By j2eereference Leave a Comment

Thread interruption is a way in which a thread who is either in sleeping or waiting state can be made to stop sleeping or waiting by throwing InterruptedException. If thread is not in sleeping or waiting state then calling thread interruption methods will not affect the program and programs will execute normally it just sets the interrupt flag to true.

Let’s see the methods provided by thread class for interrupting a thread.

Thread interruption mechanism depends on an internal flag called interrupt status. In below method will check what will be the effect on status flag when we call these methods.

public void interrupt():  In this method Initial value of this internal flag is false. After calling interrupt() method on the thread , value of internal flag is set to true. Note that InterruptedException will be thrown only when a thread is interrupted while in sleep or wait and then set the status to false.

public boolean isInterrupted(): this method will return the value of internal flag either true or false.

public static boolean interrupted():This method will check whether the current thread has been interrupted or not.It will return true if the current thread has been interrupted; otherwise false.Also, note that  next  call of  interrupted would return false unless the current thread were interrupted again. Interrupted() is same as isInterrupted with the difference that , it clears interrupt status of a thread means  if interrupt status is true, then it will set the status to false.

Example For Interrupting a thread :

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
package com.j2eereference;
public class ThreadInterruptedDemo {
    public static void main(String args[])  {
           MyRunnable myRunnable = new MyRunnable();
           Thread t = new Thread(myRunnable, "Thread-A");
           t.start();
           System.out.println("Thread interrupt status return by isInterrupted() before interrupting is :"+t.isInterrupted());
           t.interrupt();
           System.out.println("Thread interrupt status return by isInterrupted() after interrupting is :"+t.isInterrupted());
    }
}
    
    class MyRunnable implements Runnable {
      public void run() {
           try
             {
         for(int i = 0; i <= 10; i++)
                      {
                       System.out.println(Thread.currentThread().getName()+"is running");
                       Thread.sleep(1000);
                      }
             }
           catch (InterruptedException e) {
                 System.out.println(Thread.currentThread().getName() + " has been interrupted");
                 System.out.println("After throwing interrupted exception, interrupted() method will return interrupt status as : "+Thread.currentThread().interrupted());
               }
         }
    }

OutPut :
Thread interrupt status return by isInterrupted() before interrupting is :false
Thread-Ais running
Thread interrupt status return by isInterrupted() after interrupting is :true
Thread-A has been interrupted
Second call of interrupted() method will return interrupt status as : false

Related Posts

  • 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
  • Static import
  • String constructors
  • ProcessBuilder

Filed Under: Core Java Tagged With: interrupt(), interrupted(), Interrupting a thread in java, isInterrupted(), Thread Interruption

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

  • Assert in java
  • Batch Processing in JDBC
  • Deque in Java Collection
  • Navigable Map
  • Daemon thread
  • Object Cloning in Java
  • varargs in Java
  • Transient Variable
  • Java versions
  • Dynamic Binding and Static Binding in Java

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

  • 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
  • Optimizing Loop
  • Generics
  • Autoboxing

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

  • TreeSet
  • Interaction between Threads
  • Features added in Java 1.7
  • LinkedList
  • Enums
  • Interface
  • Features added in JDBC 4.1
  • HashMap
  • Synchronization
  • Abstract class and methods

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

  • Pass by value and Pass by reference
  • Threads
  • Inner classes, Method-Local Inner classes and Anonymous Classes
  • Wrapper classes
  • Super Keyword
  • Garbage Collection in Java
  • File operations in java
  • StringTokenizer
  • Generating random numbers in java
  • Reading properties file from java

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

  • « Previous Page
  • Page 1
  • Page 2
  • Page 3
  • Page 4
  • …
  • Page 13
  • 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

  • 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
  • Iterator Design Pattern Implementation using Java
  • Strategy Design Pattern Implementation using Java
  • Decorator Design Pattern
  • Adapter Design Pattern Implementation using Java
  • JSF Composite Components
  • JSF UI Components
  • What is JavaServer Faces (JSF)?
  • GOF Design Patterns
  • History and Need for Design Patterns

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.