Wednesday, 27 April 2016

Callable and Future in Java concurrency

Callable, an interface, was added in Java 5. It allows you to define a task to be completed by a thread asynchronously.

You must be wondering, there is already a Runnable interface, with its run() method to do the same thing then why Callable? Problem with Runnable is it can't return a value. It offers a single method run() that accepts no arguments and returns no values, nor can it throw any checked exceptions.

So if you have to use Runnable in scenario where you want to return some value, you'll have to write a method outside the interface to get a value back from the completed task, Also you need some kind of notification to know that the task is completed and now value can be retrieved.

Callable provides the functionality out of the box to implement the scenario as stated above.

Callable interface

The Callable interface has a call() method, since it is a generic interface so it can return any value (Object, String, Integer etc.) based on how it is initialized.

Note that Callable is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.

General form of Callable interface

public interface Callable<V> {
    V call() throws Exception;
}

Runnning a task using Callable

Like Runnable you cannot pass a Callable into a thread to execute, you use the ExecutorService, which has a submit() method which takes Callable as parameter to execute the Callable task.

<T> Future<T> submit(Callable<T> task)

Here task is the Callable task to submit and it returns a Future representing pending completion of the task.

Future interface

A Future represents the result of an asynchronous computation. When you submit a callable task using the submit() method of the ExecutorService, Future object is returned.

Future provides methods to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

get() - get() method retrieves the result of the computation, blocking if necessary for the computation to complete.

If you don't want to get blocked indefinitely, you can use the version of the get() method with the timeout parameter, then it will wait only for the given time.
get(long timeout, TimeUnit unit) - Waits if necessary for at most the given time for the computation to complete, and then retrieves its result, if available.

You can also cancel the submitted task using cancel() method.

cancel(boolean mayInterruptIfRunning) - Attempts to cancel execution of this task.

This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. Returns false if the task could not be cancelled, typically because it has already completed normally; true otherwise.

There is also isDone() method to check if task is completed and isCancelled() to check whether the task was cancelled before it was completed normally.

Example code using Callable and Future

In this example code there is a MyCallable class that implements the Callable interface and the return value of the call() method is String and its length.

A thread pool of four threads is created and submit() method of ExecutorService is used to submit callable tasks. Total submitted tasks are 6.
Also one tempMethod() is called just to show the asynchronous nature of the callable. While getting the future values isDone() method is used for the fourth get() to check whether that particular task is completed or not.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableDemo {
    public static void main(String args[]){
        // ExecutorService with pool of 4 threads
        ExecutorService es = Executors.newFixedThreadPool(4);
        // Submitting 6 tasks
        Future<String> f1 = es.submit(new MyCallable("callable"));
        Future<String> f2 = es.submit(new MyCallable("future"));
        Future<String> f3 = es.submit(new MyCallable("executor"));
        Future<String> f4 = es.submit(new MyCallable("executor service"));
        Future<String> f5 = es.submit(new MyCallable("executors"));
        Future<String> f6 = es.submit(new MyCallable("scheduled executor"));
        // calling some other methods
        tempMethod();
        
        try {
            // Calling get() method to get the future value
            System.out.println("1. " + f1.get());
            System.out.println("2. " + f2.get());
            System.out.println("3. " + f3.get());
            if(f4.isDone()){
                System.out.println("4. " + f4.get());
            }else{
                System.out.println("waiting");
            }
            System.out.println("5. " + f5.get());
            System.out.println("6. " + f6.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //shutting down the executor service
        es.shutdown();
    }
    
    //
    public static void tempMethod(){
        System.out.println("I am in temp method");
    }
}

/**
 *
 * Callable
 *
 */
class MyCallable implements Callable<String> {
    String str;
    MyCallable(String str){
        this.str = str;
    }
    @Override
    public String call() throws Exception {
        System.out.println("In call method of Callable " + str);
        StringBuffer sb = new StringBuffer();
        return (sb.append("Length of string ").append(str).append(" is ").
                append(str.length())).toString();
    
    }
    
}

Output

In call method of Callable callable
In call method of Callable future
In call method of Callable executor
I am in temp method
1. Length of string callable is 8
2. Length of string future is 6
3. Length of string executor is 8
waiting
In call method of Callable executors
In call method of Callable scheduled executor
5. Length of string executors is 9
6. Length of string scheduled executor is 18
In call method of Callable executor service

It can be seen here that after 3 calls to callable tempMethod() is called in between while the Callable tasks are executed asynchronously. Also notice that fourth value is not there as a check for completion of task is there with isDone(), since the task is not completed and we are not blocking by calling the get() method so that particular value is skipped.
The output may differ when you execute the code.

Callable as lambda expression

As already stated above that Callable is a functional interface so it can be implemented as a lambda expression too. If we have to write the code as above using the lambda expression then it can be done this way -

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class CallableLambda {
    public static void main(String args[]){
        ExecutorService es = Executors.newFixedThreadPool(4);
        getLength(es, "executor");
        getLength(es, "executor service");
        getLength(es, "Scheduled executor service");
        getLength(es, "executors");
        getLength(es, "fork join");
        getLength(es, "callable");
        
        
    }
    
    public static void getLength(ExecutorService es, String str){
        Future<String> f = es.submit(() -> { return str + str.length();});
        try {
            System.out.println("" + f.get());
        } catch (InterruptedException | ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output

executor8
executor service16
Scheduled executor service26
executors9
fork join9
callable8

In the code Callable is implemented as a lambda expression with in the sumbit() method of the ExecutorService. Also, if you noticed the try-catch block in the code, multi catch statement from Java 7 is used here.

That's all for this topic Callable and Future in Java concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Executor and ExecutorService in Java concurrency
  2. LinkedBlockingDeque in Java
  3. Difference between Runnable and Callable in Java
  4. CopyOnWriteArrayList in Java
  5. ReentrantReadWriteLock in Java
  6. Java Concurrency interview questions

You may also like -

Tuesday, 26 April 2016

Executor and ExecutorService in Java concurrency

In large-scale applications, its good to separate thread management and creation from the rest of the application. The concurrent API has a feature called executors that provides an alternative to managing threads through the Thread class.

Executors frameworks comprises of -

  1. Executor interfaces - which define the three executor object types.
  2. Thread pools - These are the most common kind of executor implementation.
  3. Fork/Join - A framework (from JDK 7) for taking advantage of multiple processors.

In this post we'll see the executor interfaces in detail.

At the core of the executors is the Executor interface, which also has two sub interfaces ExecutorService and ScheduledExecutorService.

Executor interface

An object of type Executor can execute runnable tasks. An Executor is normally used instead of explicitly creating threads. For example If r is a Runnable object, and e is an Executor object you can replace

(new Thread(r)).start();

with

e.execute(r);

Methods provided by Executor interface

The Executor interface provides a single method, execute -

void execute(Runnable command)

Executes the given command at some time in the future. The command may execute in a new thread, in a pooled thread, or in the calling thread, at the discretion of the Executor implementation.

ExecutorService interface

ExecutorService interface extends Executor interface and provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks.

ExecutorService has more versatile submit method. Like execute, submit accepts Runnable objects, but also accepts Callable objects, which allow the task to return a value. The submit method returns a Future object, which is used to retrieve the Callable return value and to manage the status of both Callable and Runnable tasks.

Executor Service Implementing classes

In the Java concurrency there are three pre defined executor classes that implement the Executor and ExecutorService interface.

  1. ThreadPoolExecutor - Implements the Executor and ExecutorService interfaces and executes the submitted task using one of the pooled thread.
  2. ScheduledThreadPoolExecutor - It extends ThreadPoolExecutor and also implements the ScheduledExecutorService. This class schedule commands to run after a given delay, or to execute periodically.
  3. ForkJoinPool implements the Executor and ExecutorService interfaces and is used by the Fork/Join Framework.

Before writing any examples for Exector or ExecutorService, two things are worth knowing Executors class and ThreadPools.

ThreadPools

In a large scale application if each task uses its own thread then allocating and deallocating many thread objects creates a significant memory management overhead.

Thread pool as the name suggests provides a set of threads, any task which has to be executed get a thread from this pool.

Executors class

Executors class provide factory and utility methods for Executors framework classes like Executor, ExecutorService, ScheduledExecutorService, ThreadFactory, and Callable.

Though you can use ThreadPoolExecutor and ScheduledThreadPoolExecutor directly, but the best way to get an executor is to use one of the static factory methods provided by the Executors utility class.

Some of the factory methods -

  1. static ExecutorService newCachedThreadPool() - Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available.
  2. static ExecutorService newFixedThreadPool(int numThreads) - Creates a thread pool that reuses a fixed number of threads.
  3. static ScheduledExecutorService newScheduledThreadPool(int numThreads) - Creates a thread pool that can schedule commands to run after a given delay, or to execute periodically.
  4. newSingleThreadExecutor() - Creates an Executor that uses a single worker thread operating off an unbounded queue.

Example code

As already mentioned apart from execute() method, ExecutorService also has submit() method which takes both Runnable and Callable as parameter. So let's see examples for these methods.

execute method

In this example a thread pool of two threads are created, and 6 runnable tasks are executed. These 6 tasks will be executed using only these 2 threads from the thread pool, new thread won't be created for each of the 6 tasks. It can be verified from the thread name in the output.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExecutorDemo {
 public static void main(String args[]) {
  // creating executor with pool of 2 threads
  ExecutorService ex = Executors.newFixedThreadPool(2);
  // running 6 tasks
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  ex.execute(new Task());
  //shutting down the executor service
  ex.shutdown();
 }
}

 
/**
 *
 *
 *
 */
class Task implements Runnable{

 @Override
 public void run() {
  System.out.println("in run task for thread - " + Thread.currentThread().getName());
  // Introducing some delay for switching
  try {
   Thread.sleep(500);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
}

Output

in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-1
in run task for thread - pool-1-thread-1
in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-1

Submit with Runnable parameter example

submit method submits a runnable task for execution and returns a Future representing that task. The Future's get() method will return null upon successful completion.

In the example 2 runnable tasks are submitted which return future objects, in case of Runnable, Future's get method will return null.

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceDemo {
 public static void main(String args[]) {
  // creating executor with pool of 2 threads
  ExecutorService ex = Executors.newFixedThreadPool(2);
  // running tasks
  Future f1 = ex.submit(new Task());
  Future f2 = ex.submit(new Task());
  try {
   // getting the future value
   System.out.println("Future f1 " + f1.get());
   System.out.println("Future f1 " + f1.get());
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (ExecutionException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  ex.shutdown();
  
 }
}

/**
 * 
 * Runnable 
 *
 */
class Task implements Runnable{

 @Override
 public void run(){
  System.out.println("in run task for thread - " + Thread.currentThread().getName());
  // Introducing some delay for switching
  try {
   Thread.sleep(500);
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   
   e.printStackTrace();
   
   
  }
 }
 
}

Output

in run task for thread - pool-1-thread-2
in run task for thread - pool-1-thread-1
Future f1 null
Future f1 null

Submit with Callable as parameter example

Callable interface has call method which can return value too, so in this case when Future's get method is called it'll return a value. Note that here callable is implemented as a lambda expression.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ExecutorServiceDemo {
    public static void main(String args[]) {
        // creating executor with pool of 2 threads
        ExecutorService ex = Executors.newFixedThreadPool(2);
        // Callable implemented as lambda
        Callable<String> c = ()->"Callable lambda is called";
        // running tasks with callable as param
        Future f1 = ex.submit(c);
        try {
            // getting the future value
            System.out.println("Future f1 " + f1.get());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ex.shutdown();
        
    }
}

Output

Future f1 Callable lambda is called

ExecutorService shutdown

An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources.

ScheduledExecutorService

ScheduledExecutorService extends ExecutorService and provides methods that can schedule commands to run after a given delay, or to execute periodically.

It has methods that execute a Runnable or Callable task after a specified delay.

  • schedule(Callable<V> callable, long delay, TimeUnit unit) - Creates and executes a ScheduledFuture that becomes enabled after the given delay.
  • schedule(Runnable command, long delay, TimeUnit unit) - Creates and executes a one-shot action that becomes enabled after the given delay.

In addition, the interface defines scheduleAtFixedRate and scheduleWithFixedDelay, which executes specified tasks repeatedly, at defined intervals.

  • scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) - Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given period; that is executions will commence after initialDelay then initialDelay+period, then initialDelay + 2 * period, and so on.
  • scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) - Creates and executes a periodic action that becomes enabled first after the given initial delay, and subsequently with the given delay between the termination of one execution and the commencement of the next.

Example code

Here schedule method is used which will be executed after a delay of 1 Sec.

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;

import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class ExecutorServiceDemo {
    public static void main(String args[]) {
        // creating ScheduledExecutorService with pool of 2 threads
        ScheduledExecutorService  ex = Executors.newScheduledThreadPool(2);
        // Callable implemented as lambda
        Callable<String> c = ()->"Callable lambda is called";
        // scheduling tasks with callable as param
        // it will execute after a delay of 2 Secs
        Future f1 = ex.schedule(c, 1, TimeUnit.SECONDS);
        try {
            // getting the future value
            System.out.println("Future f1 " + f1.get());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        ex.shutdown();
        
    }
}

That's all for this topic Executor and ExecutorService in Java concurrency. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Callable and Future in Java concurrency
  2. ArrayBlockingQueue in Java Concurrency
  3. CopyOnWriteArrayList in Java
  4. CyclicBarrier in Java concurrency
  5. CountDownLatch in Java concurrency
  6. Java Concurrency interview questions

You may also like -

Monday, 25 April 2016

@Resource annotation in Spring autowiring

Apart from supporting JSR-330 annotations like @Inject and @Named for autowiring, Spring also supports injection using the JSR-250 @Resource annotation on fields or bean property setter methods.

@Resource takes a name attribute, and by default Spring interprets that value as the bean name to be injected. In other words, it follows by-name semantics. That's where it differs from other annotations for autowiring like @Autowired and @Inject which are equivalent to autowiring="byType" in autowiring using XML configuration file.

In case no name is provided with @Resource annotation explicitly, the default name is derived from the field name or setter method.

  • In case of a field, it takes the field name;
  • In case of a setter method, it takes the bean property name.

As example, if we take the following class, then bean with name "payment" will be injected into its setter method

public class PayServiceImpl {

 private IPayCash payment;

 @Resource
 public void setPayment(IPayCash payment) {
  this.payment = payment;
 }
}

But there is also default switching with @Resource annotation, if it doesn't find the bean with the same name it will try to match using type. So if you see how it compares with the other two annotations @Autowired and @Inject -

@Autowired and @Inject

  1. Matches by Type
  2. Restricts by Qualifiers
  3. Matches by Name

@Resource

  1. Matches by Name
  2. Matches by Type
  3. Restricts by Qualifiers (ignored if match is found by name)

So you can see in case of @Autowired and @Inject switch to "byType" happens only after restricting by Qualifier. Whereas with @Resource it switches to byType if it doesn't find the bean by name.

Another difference between these two types of annotation is that @Autowired and @Inject annotations use the 'AutowiredAnnotationBeanPostProcessor' to inject dependencies. Whereas '@Resource' annotation uses the 'CommonAnnotationBeanPostProcessor' to inject dependencies.

Source : http://stackoverflow.com/questions/4093504/resource-vs-autowired

Example code

Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also class CashPayment which implements IPayment interface.

PayServiceImpl class

import javax.annotation.Resource;

public class PayServiceImpl {
 
 @Resource(name="cashPaymentBean")
 private IPayment payment;
 
 public void performPayment() {
  payment.executePayment();
 }
 
 
 public IPayment getPayment() {
  return payment;
 }

 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }
}

Here note the @Resource annotation with name attribute on the field payment.

Interface IPayment

public interface IPayment {
 void executePayment();
}

CashPayment class

public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment "); 
 }
}

XML configuration file

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  
  <context:annotation-config />    
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.exp.Spring_Example.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl" >
  <!--     <property name="payment" ref="cashPaymentBean" /> -->
  </bean>
</beans>

Here note that the CashPayment class bean is defined with the same name "cashPaymentBean" as used in the @Resource annotation. <context:annotation-config /> tag is added which is required for autowired annotation. Also note that ref for cashPaymentBean is no longer required as a property in paymentBean (it is commented in the config).

You can use the following code to run this program -

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App 
{
    public static void main( String[] args ){
         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
     PayServiceImpl bean = (PayServiceImpl) context.getBean("payServiceBean");
     bean.performPayment();
        context.close();
    }
}

Checking switching to byType

As already mentioned @Resource annotation will switch to "byType" if it is not able to match the bean by name. You can test it by removing the "name" attribute from @Resource annotation.

@Resource
private IPayment payment;

In this case autowiring will be tried by looking for the bean named "payment". Since it is not there so it will match by type and the program will still run.

BeanNotOfRequiredTypeException

Since @Resource annotation tries to match by Name and then by type that may result in exception in some scenarios. Let's see an example. Here we have one more interface IPayCash and field payment in class PayServiceImpl is of type IPayCash.

IPayCash interface

public interface IPayCash {
 void executePayment();
}

PayServiceImpl class

import javax.annotation.Resource;

public class PayServiceImpl {
 
 @Resource(name="cashPaymentBean")
 private IPayCash payment;
 
 
 public void performPayment() {
  payment.executePayment();
 }
 
 
 public IPayCash getPayment() {
  return payment;
 }

 
 public void setPayment(IPayCash payment) {
  this.payment = payment;
 }
}

XML configuration

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
  
  <context:annotation-config />    
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.exp.Spring_Example.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl" >
  <!--     <property name="payment" ref="cashPaymentBean" /> -->
  </bean>
</beans>

If you see here in XML configuration CashPayment bean is defined with id "cashPaymentBean" and in Class PayServiceImpl @Resource annotation also has the same name attribute @Resource(name="cashPaymentBean") so name matching will be there and no problem.

If you have noticed types are different, in XML configuration CashPayment class is defined which is of type IPayment, whereas in PayServiceImpl payment field is of type IPayCash. Thus at run time because of type mismatch "BeanNotOfRequiredTypeException" will be thrown.

Output

WARNING: Exception encountered during context initialization - cancelling refresh attempt
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'payServiceBean': 
Injection of resource dependencies failed; nested exception is 
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'cashPaymentBean' 
must be of type [org.netjs.exp.Spring_Example.IPayCash], but was actually of type 
[org.netjs.exp.Spring_Example.CashPayment]
    at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessPropertyValues(CommonAnnotationBeanPostProcessor.java:311)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1214)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:543)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:305)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:301)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:196)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:834)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:537)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at org.netjs.exp.Spring_Example.App.main(App.java:10)


That's all for this topic @Resource annotation in Spring autowiring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Autowiring using XML configuration in Spring
  2. Autowiring using annotations in Spring
  3. Autodiscovery of bean using componenent-scan in Spring
  4. Constructor-based dependency injection in Spring
  5. Spring example program using automatic configuration

You may also like -

>>>Go to Spring tutorial page

Thursday, 21 April 2016

Check if given strings are anagram or not - Java program

Write a Java program to find whether the given strings are anagrams or not is a frequently asked Java interview question. Some other frequently asked Java programs are counting chars in a string and given string is a palindrome or not. First thing here is to know what exactly is Anagram.

What is anagram

Two strings are called anagram if you can rearrange the letters of one string to produce the second string, using all the letters of the first string only once. While doing that, usually, you don't consider spaces and punctuation marks.

Some Examples - "keep" and "peek", "School Master" and "The Classroom".

Logic

To check whether the given strings are anagrams or not can be done by -
  • sorting both the strings
  • or
  • by iterating one of the string char by char and making sure that the second string has the same character present

Sorting logic

Since both strings should have the same set of characters so sorting them will make them similar strings.
So the steps are -

  1. Convert the passed strings to lower case and remove spaces.
  2. Check if both strings are of same length.
  3. Sort both Strings.
  4. Check if strings are similar using equals() method.

Iteration logic

You can iterate one of the String character by character and make sure that another string also has that character present. Here one thing is important if char is found in second string you need to delete that character from the second string.

Not doing that will mean - If first string has some specific character more than once and in second string that character is present only once, that same character will match every time.

So the steps are -

  1. Convert the passed strings to lower case and remove spaces.
  2. Check if both strings are of same length.
  3. Convert one string to char array and iterate through that array.
  4. Look for that character in the second string.
  5. If found delete it from the second string. Note that in StringBuilder class there is a method deleteCharAt() which is used for deleting the char. If you want to use String class in place of StringBuilder then in order to delete the char you'll have to write -

    String2.substring(0, index) + String2.substring(index+1);

Java Program

import java.util.Arrays;

public class Anagram {

 public static void main(String[] args) {
  // Using Sorting logic
  areAnagramsBySorting("School Master", "The classroom");
  areAnagramsBySorting("Keep", "Peek");
  areAnagramsBySorting("Keep", "Peel");
  
  // using iteration and deletion
  areAnagramsByIteration("Abc", "ca B");
  areAnagramsByIteration("Keep", "pEek"); 
  areAnagramsByIteration("Mary", "Army");
  areAnagramsByIteration("Mary", "Aermy");

 }
 
 /**
  * To find out if two strings are anagram using sort logic 
  * @param string1
  * @param string2
  */
 public static void areAnagramsBySorting(String string1, String string2) {
  //convert String to all lower cases and remove spaces
  String temp1 = prepString(string1);
  String temp2 = prepString(string2);
  
  boolean flag = true;
  // check for length
  if(temp1.length() != temp2.length()){
   flag = false;
  }
  // sort the strings
  temp1 = sort(temp1);
  temp2 = sort(temp2);
  
  flag =  temp1.equals(temp2);
  if(flag){
   System.out.println(string1 + " and " + string2 + " are anagrams");
  }else{
   System.out.println(string1 + " and " + string2 + " are not anagrams");
  }
 }
 
 /**
  * To find out if two strings are anagram using iteration and deletion logic 
  * @param string1
  * @param string2
  */
 public static void areAnagramsByIteration(String string1, String string2) {
  //convert String to all lower cases and remove spaces
  String temp1 = prepString(string1);
  String temp2 = prepString(string2);
  
  boolean flag = true;
  int index;
  // check for length
  if(temp1.length() != temp2.length()){
   flag = false;
  }
  
  char[] strArray = temp1.toCharArray();
  StringBuilder sb = new StringBuilder(temp2);
  
  for(char c : strArray){
   // Look for the char in second String
   index = sb.indexOf(""+c);
   // If found delete it, otherwise second occurrence of the
   // similar char in first string will be found in second String
   if(index != -1){
    sb.deleteCharAt(index);
   }else{ 
    flag = false;
    break;
   }    
  }
  if(flag){
   System.out.println(string1 + " and " + string2 + " are anagrams");
  }else{
   System.out.println(string1 + " and " + string2 + " are not anagrams");
  }
  
 }
 
 // Sort the given String 
 protected static String sort(String string) {
     char[] charArray = string.toCharArray();
     Arrays.sort(charArray);
            return new String(charArray);
    }
 
 // Method to convert String to all lower cases and remove spaces
 protected static String prepString(String string) {
    
            return string.toLowerCase().replaceAll("\\s", "");
    } 
}

Output

School Master and The classroom are anagrams
Keep and Peek are anagrams
Keep and Peel are not anagrams
Abc and ca B are anagrams
Keep and pEek are anagrams
Mary and Army are anagrams
Mary and Aermy are not anagrams

So these are the ways to find if given strings are anagram or not. Please let me know if you have any other logic to do that.


Related Topics

  1. How to Sort elements in different order in TreeSet
  2. Count total number of times each character appears in a String
  3. How to sort arraylist of custom objects in Java
  4. Print odd-even numbers using threads and semaphore
  5. Count number of words in a String

You may also like -

>>>Go to Java Programs page

Tuesday, 19 April 2016

Difference between component-scan and annotation-config in Spring

To get the difference between annotation-config element and component-scan element you have to know about two terms -

  • Autowiring of beans
  • Autodiscovery of beans

Autowiring of beans

When you use only XML configuration for registering your beans and defining dependencies then you need to configure everything manually in your XML.

As Example If you have 2 classes PayServiceImpl and CashPayment where PayServiceImpl uses object of CashPayment class then in your spring configuration you will have something like this -

<?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:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
 
 <!-- defining CashPayment bean -->
  <bean id="cashPaymentBean" class="org.netjs.exp.Spring_Example.CashPayment" />
 
  <!-- Defining PayServiceImpl bean and injecting payment bean -->
  <bean id="payServiceBean" class="org.netjs.exp.Spring_Example.PayServiceImpl">
      <property name="payment" ref="cashPaymentBean" />
  </bean>
</beans>

If you use autowiring then also you have two options -

In case you use annotations, you need to activate annotations and you have to add <context:annotation-config /> in your XML file.

With that if we take the same example as above the configuration will be like this -

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
   <context:annotation-config/>  
 
   <bean id="cashPaymentBean" class="org.netjs.prog.CashPayment" />
 
   <!-- Defining PayServiceImpl bean and injecting payment bean -->
   <bean id="paymentBean" class="org.netjs.prog.PayServiceImpl">
      <!-- <property name="payment" ref="cashPaymentBean" /> -->
   </bean> 
</beans>

Note the inclusion of <context:annotation-config /> and exclusion of <property name="payment" ref="cashPaymentBean" /> (it is commented).

You don't need property as the dependency will be injected automatically but you need one more change for that in your PayServiceImpl class. You need to use @Autowired annotation to autowire the payment property.

import org.springframework.beans.factory.annotation.Autowired;
public class PayServiceImpl implements IPayService {
    private IPayment payment;

    public void performPayment() {
        // calling method on Ipayment implementing class
        payment.executePayment();
    }
    
    public IPayment getPayment() {
        return payment;
    }

    @Autowired
    public void setPayment(IPayment payment) {
        this.payment = payment;
    }
}

Here points to note are -

  • You have to include <context:annotation-config /> in your XML for autowiring using annotation to work.
  • You don't need to manually write the dependencies with property or constructor-arg tag and ref attribute.
  • You still have to define all your beans because <context:annotation-config /> only works on beans registered within the application context. That's where enters the auto discovery of beans.

Autodiscovery of beans

With autowiring you can simplify you XML configuration to the extent that you don't need to provide the dependencies. But auto-discovery goes one step further and eliminates the need to add the <bean> tag altogether in your xml.

That can be done using <context:component-scan> element and pointing the base package, it configures Spring to automatically discover beans and declare them for you.

This removes the need to use XML to perform bean registration and for most of the classes you don’t need <bean> element to declare and wire beans.

Annotations used for auto-discovery

Using componentscan element is half of the picture, you need to annotate your classes which needs to be auto-discovered with one of these annotations @Component, @Service, @Controller, @Repository

  • @Component - It is a generic stereotype for any Spring-managed component.
  • @Service - More suitable for a class used as a service.
  • @Repository - This annotation is a marker for any class that fulfills the role or stereotype of a repository (also known as Data Access Object or DAO).
  • @Controller - More suitable for a class used in presentation layer as a controller.
  • Any custom annotation that is itself annotated with @Component.

As Exp. If you have 2 classes PayServiceImpl and CashPayment where PayServiceImpl uses object of CashPayment class then you configuration will look like this -

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
    <context:component-scan base-package="org.netjs.prog" />  
 
</beans>

PayServiceImpl class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class PayServiceImpl implements IPayService {
 @Autowired
 private IPayment payment;

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }
}

Here note that the class is annotated with @Service annotation, that's how it is made sure that this class is discovered while a component scan is done. Also note that the dependency to the payment is annotated with the annotation @Autowired. That's how Spring will detect and automatically do the dependency injection.

Class CashPayment

import org.springframework.stereotype.Component;

@Component
public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment - "); 
 }
}

Note here that - The use of <context:component-scan> implicitly enables the functionality of <context:annotation-config>. There is usually no need to include the <context:annotation-config> element when using <context:component-scan>. So <context:component-scan> will do everything which <context:annotation-config> does and it provides the added functionality of auto-discovery of beans.

That's all for this topic Difference between component-scan and annotation-config in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Autodiscovery of bean using componenent-scan in Spring
  2. Autowiring using annotations in Spring
  3. How to inject prototype scoped bean in singleton bean
  4. Different bean scopes in Spring
  5. Setter-based dependency injection in Spring

You may also like -

>>>Go to Spring tutorial page

Monday, 18 April 2016

Autodiscovery of bean using componenent-scan in Spring

In the post how to autowire using XML config or how to autowire using annotation you have already seen how Spring can automate the injection of dependencies. That helps in cutting down the configuration you have to do by eliminating the use of <property> and <constructor-arg> tags for wiring the bean references.

Automatic discovery of beans

But Spring goes even further and it can automatically discover beans for you. That can be done using <context:component-scan> element, it configures Spring to automatically discover beans and declare them for you. This removes the need to use XML to perform bean registration and for most of the classes you don’t need <bean> element to declare and wire beans.

Note here that - The use of <context:component-scan> implicitly enables the functionality of <context:annotation-config>. There is usually no need to include the <context:annotation-config> element when using <context:component-scan>. So <context:component-scan> will do everything which <context:annotation-config> does and it provides the added functionality of auto-discovery of beans. In fact difference between <context:annotation-config> and <context:component-scan> is one of the frequently asked interview question.

Configuration needed for using component-scan

If you are using XML configuration then you need to use context:component-scan with base-package. The base-package attribute tells <context:component-scan> from which package it needs to start its scan.

<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    <context:component-scan base-package="org.example"/>
</beans>

If you are using Java class then you just need this -

@Configuration
@ComponentScan(basePackages="org.example")
public class AppConfig {
    
}

You can annotate a Java class with @ComponentScan and provide the package which is to be scanned with basePackage attribute. You don't need to provide any code with in the class.

Annotations used for auto-discovery

Using componentscan element is half of the picture, you need to annotate your classes which needs to be auto-discovered with one of these annotations @Component, @Service, @Controller, @Repository

  • @Component - It is a generic stereotype for any Spring-managed component.
  • @Service - More suitable for a class used as a service.
  • @Repository - This annotation is a marker for any class that fulfills the role or stereotype of a repository (also known as Data Access Object or DAO).
  • @Controller - More suitable for a class used in presentation layer as a controller.
  • Any custom annotation that is itself annotated with @Component.

According to the Spring reference doc -

"you can annotate your component classes with @Component, but by annotating them with @Repository, @Service, or @Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that @Repository, @Service, and @Controller may carry additional semantics in future releases of the Spring Framework."

Example Code

Here we have a class PayServiceImpl which has a field payment of type IPayment which we have to autowire. Also PayServiceImpl and CashPayment (implementing class of interface IPayment) should be auto discovered. Since Spring promotes loose coupling so it is always recommended to code to interfaces. So we'll also create interfaces for the classes.

IPayService Interface

public interface IPayService {
 void performPayment();
}

PayServiceImpl class

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Service
public class PayServiceImpl implements IPayService {
 @Autowired
 private IPayment payment;

 public void performPayment() {
  // calling method on Ipayment implementing class
  payment.executePayment();
 }
 
 public IPayment getPayment() {
  return payment;
 }
 
 
 public void setPayment(IPayment payment) {
  this.payment = payment;
 }
}

Here note that the class is annotated with @Service annotation, that's how it is made sure that this class is discovered while a component scan is done. Also note that the dependency to the payment is annotated with the annotation @Autowired. That's how Spring will automatically detect this dependency and inject it.

Interface IPayment

public interface IPayment {
 void executePayment();
}

Class CashPayment

import org.springframework.stereotype.Component;

@Component
public class CashPayment implements IPayment{
 public void executePayment() {
  System.out.println("Perform Cash Payment - "); 
 }
}

Configuration with XML

<?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:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
 
   <context:component-scan base-package="org.netjs.prog" />  
 
</beans>

If you are using XML configuration then you need to use context:component-scan with base-package. I have created Java classes in the package org.netjs.prog so that's what I'll give as the base package. Please change accordingly.

You can run it using the following program -

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main( String[] args ){  
     ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
        IPayService bean = (IPayService) context.getBean("payServiceImpl");
        bean.performPayment();
        context.close();
    }
}

Here note one thing by default Spring will use the class name as the bean id (camel cased) while registering it in Spring. That's why you can find the bean using this - context.getBean("payServiceImpl");

If you want to give your own name let's say payService then it can be done like this -

@Service("payService")
public class PayServiceImpl implements IPayService

Then in order to get the bean you have to use this name -

IPayService bean = (IPayService) context.getBean("payService");

Configuration with Java class

If you are using Java class then you just need this

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages="org.netjs.prog")
public class AppConfig {
 
}

In that case you can run it using the following program -

import org.netjs.config.AppConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;

public class App {
    public static void main( String[] args ){
     AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);
        IPayService bean = (IPayService) context.getBean("payServiceImpl");
        bean.performPayment();
        context.close();
    }
}

Here note that AnnotationConfigApplicationContext is used to create the Spring application context which takes the JavaConfig class as input.

That's all for this topic Autodiscovery of bean using componenent-scan in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. What is Dependency Injection in Spring
  2. Constructor-based dependency injection in Spring
  3. Spring example program using JavaConfig and Annotations
  4. Autowiring using annotations in Spring
  5. Autowiring using XML configuration in Spring
  6. Spring bean life cycle

You may also like -

>>>Go to Spring tutorial page

Tuesday, 12 April 2016

Producer-Consumer Java program using ArrayBlockingQueue

This Java program solves the Producer-Consumer problem using threads and ArrayBlockingQueue which is an implementation of the BlockingQueue interface.

Initial capacity of the ArrayBlockingQueue will be kept one so that producer and consumer both get a chance alternatively.

Values will be inserted in the ArrayBlockingQueue using put() method, which will block if the space is full.

Values will be retrieved from the ArrayBlockingQueue using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

In the program there is a class Buffer which is shared by both threads. In comparison to produce-consumer using wait notify this version using blocking queue is much simpler as you don't need to write the logic for making the thread wait or notifying the waiting thread.

Java program

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ArrayBQDemo {

    public static void main(String[] args) {
        Buffer buffer = new Buffer();
        // Starting two threads
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new ProdTask(buffer));
        executor.execute(new ConTask(buffer));
        executor.shutdown();
    }

}

/**
 * 
 * 
 *
 */
class ProdTask implements Runnable{
    Buffer buffer;
    ProdTask(Buffer buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 5; i++){
            buffer.put(i);
        }
    }
}

/**
 * 
 * 
 *
 */
class ConTask implements Runnable{
    Buffer buffer;
    ConTask(Buffer buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 5; i++){
            buffer.get();;
        }
    }    
}

//Shared class used by threads
class Buffer{
    int i;
    // Bouded ArrayBlockingQueue of size 1
    BlockingQueue<Integer> arrayBlockingQ = new ArrayBlockingQueue<Integer>(1);
    public void get(){
        try {
            // take method to get from blockingqueue
            System.out.println("Consumer recd - " + arrayBlockingQ.take());
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void put(int i){
        this.i = i;
        try {
            // putting in blocking queue
            arrayBlockingQ.put(i);
            System.out.println("Putting - " + i);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

Output

Putting - 0
Consumer recd - 0
Putting - 1
Consumer recd - 1
Putting - 2
Consumer recd - 2
Putting - 3
Consumer recd - 3
Putting - 4
Consumer recd - 4

That's all for this topic Producer-Consumer Java program using ArrayBlockingQueue. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Print odd-even numbers using threads and semaphore
  2. ArrayBlockingQueue in Java Concurrency
  3. LinkedBlockingQueue in Java Concurrency
  4. How to Sort elements in different order in TreeSet
  5. Java Multi-threading interview questions

You may also like -

>>>Go to Java Programs page

Producer-Consumer Java program using wait notify

This Java program solves the Producer-Consumer problem using threads and wait notify. Where one(Producer) thread produces data and another(consumer) thread retrieves it.

This program makes use of inter-thread communication using wait, notify, notifyAll. There is a shared object, a LinkedList of integers (note that LinkedList class implements Queue interface) which is used by both threads. There is a ProdClass which adds integers to the list and ConClass which retrieves those integers from the list. In the program looping is done for 5 times so there is a condition to break after iteration is done 5 times.

Logic here is that Producer puts one integer in the list and waits until the consumer consumes that integer, that's where wait/notify come into the picture. Producer puts one integer and then go to wait state, while notifying the other thread to wake up and vice versa and this is done with in a synchronized block.

Thus producer and consumer work sequentially where producer adds data and consumer retrieves it and so on.

Java program

import java.util.LinkedList;
import java.util.Queue;

public class ProdConDemo {

    public static void main(String[] args) {
        // This is the shared list shared between producer
        // and consumer.. LinkedList implements Queue interface
      Queue<Integer> sharedListObj = new LinkedList<Integer>();
        Thread t1 = new Thread(new ProdClass(sharedListObj), "ProdThread");
        Thread t2 = new Thread(new ConClass(sharedListObj), "ConThread");
        t1.start();
        t2.start(); 

    }

}

// Producer class
class ProdClass implements Runnable{
    Queue<Integer> sharedListObj;
    // Constructor
    ProdClass(Queue<Integer> sharedListObj){
        this.sharedListObj = sharedListObj;
    }
    @Override
    public void run() {
        int i = 0;
        while(true){
            synchronized (sharedListObj) {
                // While condition as mandated to avoid spurious wakeup
                while(sharedListObj.size() >= 1){
                    try {
                        sharedListObj.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                // Putting value in the list
                System.out.println("Adding to queue - " + Thread.currentThread().getName() + " " + ++i);
                sharedListObj.add(i);
                sharedListObj.notify();    
                // To get out of while(true) loop (running 5 times only)
                if(i > 4) break;
            }
        }
    }            
}

//Consumer class
class ConClass implements Runnable{
    Queue<Integer> sharedListObj;
    // Constructor
    ConClass(Queue<Integer> sharedListObj){
        this.sharedListObj = sharedListObj;
    }
    @Override
    public void run() {    
        while(true){
            synchronized (sharedListObj) {
                while(sharedListObj.size() < 1){
                    try {
                        sharedListObj.wait();
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }                    
                }
                int val = sharedListObj.remove();
                // Getting value from the list
                System.out.println("Getting from queue " + Thread.currentThread().getName() + " " + val);
                // To get out of while(true) loop
                if(val == 5) {
                    break;
                }
                sharedListObj.notify();        
                
            }
        }
    }
}

Output

Adding to queue - ProdThread 1
Getting from queue ConThread 1
Adding to queue - ProdThread 2
Getting from queue ConThread 2
Adding to queue - ProdThread 3
Getting from queue ConThread 3
Adding to queue - ProdThread 4
Getting from queue ConThread 4
Adding to queue - ProdThread 5
Getting from queue ConThread 5

That's all for this topic Producer-Consumer using wait notify. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Inter-thread communication using wait, notify and notifyAll
  2. Why wait(), notify() and notifyAll() methods are in Object class
  3. Why wait(), notify() and notifyAll() must be called inside a synchronized method or block?
  4. Print odd-even numbers using threads and wait-notify
  5. Java Multi-threading interview questions

You may also like -

>>>Go to Java Programs page

Monday, 11 April 2016

LinkedBlockingDeque in Java

LinkedBlockingDeque is an implementation of the BlockingDeque interface and it was added in Java 6.

LinkedBlockingDeque is an optionally bounded deque and it stores its elements as linked nodes. Since it is optionally bounded so it has constructor which takes initial capacity as parameter. In case capacity is not specified it is equal to Integer.MAX_VALUE.

LinkedBlockingDeque constructors

LinkedBlockingDeque has three constructors -

  • LinkedBlockingDeque() - Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE.
  • LinkedBlockingDeque(Collection<? extends E> c) - Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection's iterator.
  • LinkedBlockingDeque(int capacity) - Creates a LinkedBlockingDeque with the given (fixed) capacity.

Here note that Linked nodes are dynamically created upon each insertion unless this would bring the deque above capacity. In case initial capacity is defined then the blocking method like put(E e) will wait if necessary for space to become available.

Since elements are stored as linked nodes so most of the operation like add(), addFirst(), put(), putFirst() run in constant time (ignoring time spent blocking). Exceptions include remove(object o), removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.

Example code

Let's create a produce consumer bounded buffer using LinkedBlockingDeque which is an implmentation of BlockingDeque.

Values will be inserted in the LinkedBlockingDeque using put() method, which will block if the space is full.

Values will be retrieved from the LinkedBlockingDeque using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Here in the Produce class some delay is induced using sleep() method. You can see that in Consumer class, where it is taking elements out of the deque, no excpetion will be thrown but it will block. If you are using eclipse you can see that delay in the console when it is printing.

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDQDemo {
    public static void main(String[] args) {
        SharedClass buffer = new SharedClass();
        // Starting two threads
        ExecutorService executor = Executors.newFixedThreadPool(2);
        executor.execute(new Producer(buffer));
        executor.execute(new Consumer(buffer));
        executor.shutdown();

    }
}


/**
 * 
 * 
 *
 */
class Producer implements Runnable{
    SharedClass buffer;
    Producer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.put(i);
            if(i == 4){
                try {
                    // introducing some delay using sleep
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

/**
 * 
 * 
 *
 */
class Consumer implements Runnable{
    SharedClass buffer;
    Consumer(SharedClass buffer){
        this.buffer = buffer;
    }
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            buffer.get();;
        }
    }    
}

//Shared class used by threads
class SharedClass{
    int i;
    // Bounded LinkedBlockingDeque of size 10
    BlockingDeque<Integer> linkedBlockingDeque = new LinkedBlockingDeque<Integer>(10);
    
    public void get(){
       try {
            // take method to get from blockingdeque
           System.out.println("Consumer recd - " + linkedBlockingDeque.take());
       } catch (InterruptedException e) {
            // TODO Auto-generated catch block
           e.printStackTrace();
       }
    }
    
    public void put(int i){
       this.i = i;
       try {
            // putting in blocking deque
            linkedBlockingDeque.put(i);
            System.out.println("Putting - " + i);
       }
       catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
       } 
    }
}

Output

Putting - 0
Putting - 1
Putting - 2
Putting - 3
Putting - 4
Consumer recd - 0
Consumer recd - 1
Consumer recd - 2
Consumer recd - 3
Consumer recd - 4
Putting - 5
Consumer recd - 5
Putting - 6
Consumer recd - 6
Putting - 7
Consumer recd - 7
Putting - 8
Consumer recd - 8
Putting - 9
Consumer recd - 9

That's all for this topic LinkedBlockingDeque in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. BlockingDeque in Java Concurrency
  2. BlockingQueue in Java Concurrency
  3. LinkedBlockingQueue in Java Concurrency
  4. CopyOnWriteArrayList in Java
  5. Phaser in Java concurrency
  6. Java Concurrency interview questions

You may also like -

Thursday, 7 April 2016

Print odd-even numbers using threads and semaphore

This Java program prints odd-even numbers sequentially using two threads. One thread generates odd numbers and another even numbers.

This program makes use of inter-thread communication using Semaphore class which is present in concurrent util package.

The Semaphore class present in java.util.concurrent package is a counting semaphore in which a semaphore, conceptually, maintains a set of permits. Semaphore class has two methods that make use of permits -

  • acquire() - Acquires a permit from this semaphore, blocking until one is available, or the thread is interrupted. It has another overloaded version acquire(int permits).
  • release() - Releases a permit, returning it to the semaphore. It has another overloaded method release(int permits).

In the Java program there is class SharedPrinter whose object is shared between two threads. In this class there is a method printEvenNum() for printing even numbers and method printOddNum() for printing odd numbers.

These two methods are called by the respective threads EvenNumProducer and OddNumProducer and these threads communicate using semaphore. Idea is to have 2 semaphores when first is acquired release second, when second is acquired release first. That way shared resource has controlled access and there is inter-thread communication between the threads.

Note that one of the semaphore semEven is initialized with 0 permits that will make sure that even number generating thread doesn't start first.

Java Program

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class EvenOddSem {

 public static void main(String[] args) {
    SharedPrinter sp = new SharedPrinter();
    // Starting two threads
           ExecutorService executor = Executors.newFixedThreadPool(2);
           executor.execute(new EvenNumProducer(sp, 10));
           executor.execute(new OddNumProducer(sp, 10));
           executor.shutdown();
 }

}

//Shared class used by both threads
class SharedPrinter{
 boolean evenFlag = false;
 // 2 semaphores 
        Semaphore semEven = new Semaphore(0);
        Semaphore semOdd = new Semaphore(1);
 
 //Method for printing even numbers
 public void printEvenNum(int num){
  try {
   semEven.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semOdd.release(); 
 }
 
 //Method for printing odd numbers
 public void printOddNum(int num){
  try {
   semOdd.acquire();
  } catch (InterruptedException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println(num);
  semEven.release();
   
 }
}

//Thread Class generating Even numbers
class EvenNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    EvenNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 2; i <= index; i = i+2){
            sp.printEvenNum(i);
        }
        
    }
    
}

//Thread Class generating Odd numbers
class OddNumProducer implements Runnable{
    SharedPrinter sp;
    int index;
    OddNumProducer(SharedPrinter sp, int index){
        this.sp = sp;
        this.index = index;
    }
    @Override
    public void run() {
        for(int i = 1; i <= index; i = i+2){
            sp.printOddNum(i);
        }
    }
} 

Output

1
2
3
4
5
6
7
8
9
10

That's all for this topic Printing odd even numbers using threads and semaphore. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Print odd-even numbers using threads and wait-notify
  2. Semaphore in Java concurrency
  3. How to read input from console in Java?
  4. Armstrong number
  5. Check whether a given String/Number is a palindrome or not

You may also like -

>>>Go to Java Programs page