Friday, 22 May 2020

Latest Java Interview Questions- Part 3

1.How many objects are create when we use the new keyword with the string


eg: a="syed"

    b=new String("syed")

It will create the different objects moreover both are not same.

2. Difference between the filter and map in java 8.

FIlter will check the condition and inserts in to the List only if it satisfies.

        List<EmployeeClass> empSet1 = new ArrayList<>();

        empSet1=empSet.stream().filter(e->e.getId().equals("1")).collect(Collectors.toList());

Map will insert the boolean of list based on the condition .

        List<Boolean> empSet1 = new ArrayList<>();

        empSet1=empSet.stream().filter(e->e.getId().equals("1")).collect(Collectors.toList());

3. what are Java Executors, Also Explain Important terms in it.

The Java Executor Framework has been introduced in Java 1.5 and it is a part of java concurrency package. The Executor framework is an abstraction layer over the actual implementation of java multithreading. It is the first concurrent utility framework in java and used for standardizing invocation, scheduling, execution and control of asynchronous tasks in parallel thread.

Executor implementation in java uses thread pools which consists of worker threads. The entire management of worker threads is handled by the framework. So the overhead in memory management is much reduced compared to earlier multithreading approaches.

The Java Executor framework provides multi-threading applications an easy abstraction layer. The executor abstraction layer hides the critical parts of concurrent execution and the programmer only concentrates on the business logic implementation.

The Java Executor framework creates tasks by using instances of Runnable or Callable. In case of Runnable, the run () method does not return a value or throw any checked exception. But Callable is a more functional version in that area. It defines a call () method that allows the return of some computed value which can be used in future processing and it also throws an exception if necessary.

The FutureTask class is another important component which is used to get future information about the processing. An instance of this class can wrap either a Callable or a Runnable. You can get an instance of this as the return value of submit () method of an ExecutorService. You can also manually wrap your task in a FutureTask before calling execute () method

4. What are the functional steps to implement the java Thread Pool Executor?

Following are the functional steps to implement the Java ThreadPoolExecutor.

●     A pool of multiple threads is created.

●     A queue is created holding all the tasks but these tasks are not yet assigned to threads from the pool.

●     Rejection handler is used to handle the situation when one or more tasks are not able to assign in the queue. As per the default rejection policy, it will simply throw a RejectedExecutionException runtime exception, and the application can catch it or discard it.

5. What are the types of executors?

SingleThreadExecutor

This thread pool executor has only a single thread. It is used to execute tasks in a sequential manner. If the thread dies due to an exception while executing a task, a new thread is created to replace the old thread and the subsequent tasks are executed in the new one.

ExecutorService executorService = Executors.newSingleThreadExecutor()

FixedThreadPool(n)

As the name indicates, it is a thread pool of a fixed number of threads. The tasks submitted to the executor are executed by the n threads and if there is more task they are stored on a LinkedBlockingQueue. This number is usually the total number of the threads supported by the underlying processor.

ExecutorService executorService = Executors.newFixedThreadPool(4);

CachedThreadPool

This thread pool is mostly used where there are lots of short-lived parallel tasks to be executed. Unlike the fixed thread pool, the number of threads of this executor pool is not bounded. If all the threads are busy executing some tasks and a new task comes, the pool will create and add a new thread to the executor. As soon as one of the threads becomes free, it will take up the execution of the new tasks. If a thread remains idle for sixty seconds, they are terminated and removed from cache.

However, if not managed correctly, or the tasks are not short-lived, the thread pool will have lots of live threads. This may lead to resource thrashing and hence performance drop.

ExecutorService executorService = Executors.newCachedThreadPool();

ScheduledExecutor

This executor is used when we have a task that needs to be run at regular intervals or if we wish to delay a certain task.

ScheduledExecutorService scheduledExecService = Executors.newScheduledThreadPool(1);

The tasks can be scheduled in ScheduledExecutor using either of the two methods scheduleAtFixedRate or scheduleWithFixedDelay.

scheduledExecService.scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit)

scheduledExecService.scheduleWithFixedDelay(Runnable command, long initialDelay, long period, TimeUnit unit)

The main difference between the two methods is their interpretation of the delay between consecutive executions of a scheduled job.

scheduleAtFixedRate executes the task with fixed interval, irrespective of when the previous task ended.

scheduleWithFixedDelay will start the delay countdown only after the currently task completes.

6. Understanding the Future Object,Why the Task submitted to the executor is asynchronous.

The result of the task submitted for execution to an executor can be accessed using the java.util.concurrent.Future object returned by the executor. Future can be thought of as a promise made to the caller by the executor.

Future<String> result = executorService.submit(callableTask);

A task submitted to the executor, like above, is asynchronous i.e. the program execution does not wait for the completion of task execution to proceed to the next step. Instead, whenever the task execution is completed, it is set in this Future object by the executor.

The caller can continue executing the main program and when the result of the submitted task is needed he can call .get() on this Future object. If the task is complete the result is immediately returned to the caller or else the caller is blocked until the execution of this is completed by the executor and the result is computed.

If the caller cannot afford to wait indefinitely before retrieving the result, this wait can be timed as well. This is achieved by the Future.get(long timeout, TimeUnit unit) method which throws a TimeoutException if the result is not returned in the stipulated timeframe. The caller can handle this exception and continue with the further execution of the program.

If there is an exception when executing the task, the call to get method will throw an ExecutionException.

An important thing with respect to result being returned by Future.get() method is that it is returned only if the submitted task implements java.util.concurrent.Callable. If the task implements the Runnable interface, the call to .get() will return null once the task is complete.

Another important method is the Future.cancel(boolean mayInterruptIfRunning) method. This method is used to cancel the execution of a submitted task. If the task is already executing, the executor will attempt to interrupt the task execution if the mayInterruptIfRunning flag is passed as true.



7.Write a Sample program explaining the Executors using the callable and Runnable,Executors.

Sample Program using callable.

package com.sample.executor;

import java.util.concurrent.Callable;

public class HelloWorldTask implements Callable<String> {



 private String message;

 public HelloWorldTask(String message) {

  super();

  this.message = message;

 }

 public String getMessage() {

  return message;

 }

 public void setMessage(String message) {

  this.message = message;

 }

 @Override

 public String call() throws Exception {



  if(getMessage().equals("syed")) {

   throw new NullPointerException();

  }

  return "Hello"+ getMessage();

 }

}



Using Runnable:

package com.sample.executor;

public class HelloWorldRunnable implements Runnable {



 private String message;

 public HelloWorldRunnable(String message) {

  this.message = message;

 }

 public String getMessage() {

  return message;

 }

 public void setMessage(String message) {

  this.message = message;

 }

 @Override

 public void run() {

  if(getMessage().equals("syed")) {

   throw new NullPointerException();

  }

  System.out.println("Hello"+getMessage());

 }

}

Using Executor:

package com.sample.executor;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

public class HelloWorldExecutor {

 public static void main(String[] args) {

  ExecutorService exec = Executors.newFixedThreadPool(4);

  HelloWorldTask helloTask = new HelloWorldTask(args[0]);

  HelloWorldRunnable helloRunnable = new HelloWorldRunnable(args[0]);

   Future<String> resultCallable = exec.submit(helloTask);

   Future<String> resultRunnable = (Future<String>) exec.submit(helloRunnable);

   try {

   System.out.println(resultCallable.get());

   System.out.println(resultRunnable.get());

   }catch(InterruptedException | ExecutionException e) {

              e.printStackTrace();

   }

   exec.shutdown();

 }

}



8. Difference between callable and runnable interfaces in java.

●        A Callable needs to implement call() method while a Runnable needs to implement run() method.

●        A Callable can return a value but a Runnable cannot.

●        A Callable can throw checked exception but a Runnable cannot.

●        A Callable can be used with ExecutorService#invokeXXX(Collection<? extends Callable<T>> tasks) methods but a Runnable cannot be

Also when we look carefully at the call() method in the CallableThread, the method signatures defines 'throws Exception'. This is not possible in Runnable.run() method. The compiler will give a error on writing throws Exception 'Exception Exception is not compatible with throws clause in Runnable.run()'. What we can write on Runnable.run() is 'throws RuntimeException'. The behind the run() method can throw only a RuntimeException is that the compiler has no bonding on the caller of this method to catch the Exception. Also with Runnable we do not know when calling start() whether the thread has started, completed, or isInProgress




No comments:
Write comments