What is the difference between Multithreading vs Multiprocessing?
Multiprocessing is more than one process in execution where as Multithreading is executing multiple threads within same process. One of the main requirement of MultiProcessing is Multi Core Processor.

Multiprocessing: In a cinema, multiple movies are screened simultaneously in different theaters. Each screening represents a separate process. For instance, one theater might be showing an action movie, another might be showing a romantic comedy, and a third might be screening a documentary. Each screening operates independently, with its own audience and projection equipment.

Multithreading: Within a single screening, there are different tasks being performed concurrently to ensure a smooth movie-watching experience. For example, while the movie is playing, the cinema staff might be selling tickets at the box office, preparing popcorn at the concession stand, and monitoring the theater for any disturbances. These tasks can be seen as threads within the same process (screening). They share resources such as the cinema lobby, staff members, and facilities.

What is Context Switching?
A context switch (also sometimes referred to as a process switch or a task switch) is the switching of the CPU (central processing unit) from one process or thread to another.
Irrespective of Single or Multi Core Context Switching happens.

  1. suspending the progression of one process and storing the CPU’s state (i.e., the context) for that process somewhere in memory
  2. Retrieving the context of the next process from memory and restoring it in the CPU’s registers
  3. Returning to the location indicated by the program counter (i.e., returning to the line of code at which the process was interrupted) in order to resume the process.

Should Context Switch Happen Frequenlty or Less?
No. If that happens, It would be resource consuming and no task gets Completed.If that happens less, You see process hanging. Context Switching should be always decided by Operating system by taking no of threads.

Difference between Concurrency and Parallelism
You and your friend has visited restaurant and seated in a table.

You(Processor) have been tasked to Eat and Sing at same Time. If you take a bite – Stop Eating – Start Singing – Sing few lines – Stop Singing – Resume Eating this is concurrency in action
You(Processor1) and Your Friend(Processor2) have been tasked to Eat and Sing where one person sings and another eats at same time. This is Parallelism.

Concurrency is when two or more tasks can start, run, and complete in overlapping time periods. It doesn’t necessarily mean they’ll ever both be running at the same instant. context switching is a key part of enabling concurrency in a single-core system For example, multitasking on a single-core machine.In Concurrency Interruptability exists

Parallelism is when tasks literally run at the same time, e.g., on a multicore processor.In Parallelism Independabality exists.

Concurrency                 Concurrency + parallelism
(Single-Core CPU)           (Multi-Core CPU)
 ___                         ___ ___
|th1|                       |th1|th2|
|   |                       |   |___|
|___|___                    |   |___
    |th2|                   |___|th2|
 ___|___|                    ___|___|
|th1|                       |th1|
|___|___                    |   |___
    |th2|                   |   |th2|

In both cases we have concurrency from the mere fact that we have more than one thread running.If we ran this program on a computer with a single CPU core, the OS would be switching between the two threads, allowing one thread to run at a time.If we ran this program on a computer with a multi-core CPU then we would be able to run the two threads in parallel – side by side at the exact same time.

Concurrency is about dealing with lots of things at once. Parallelism is about doing lots of things at once.

How do you explain the following Scenarios?

Scenario 1:

 
                     Completed               Progressing
Timeline    <----------------------->|<-------------------------------->
      P1    |-----------|--------|------------|------|-----------------|
                 T1         T2         T3        T4         T5   

Scenario 2:

 
                Completed                    Progressing
Timeline    <---------------->|<----------------------------------------->
      P1    |--------|--------|---------|-----|--------|--------|--------|
                 T1      T2       T3       T1      T3      T4       T5

Scenario 3:

 
                     Completed                            Progressing
Timeline    <-------------------------------------->|<------------------->
      P1    |--------|--------|---------|-----|--------|--------|--------|
                 T1      T2       T3       T1      T6      T4       T2
      P2    |--------|--------|---------|-----|--------|--------|--------|
                 T2      T1       T1       T2      T3      T6       T3

Scenario 4:

 
                     Completed                            Progressing
Timeline    <-------------------------------------->|<------------------->
      P1    |--------|--------|---------|-----|--------|--------|--------|
                 T1      T2       T3       T1      T6      T2       T2
      P2    |--------|--------|---------|-----|--------|--------|--------|
                 T4      T5       T4       T7      T5      T4       T8

Scenario 1:
Completed Thread: T1, T2 (2)
Progressing Thread: T3 (1)

Neither Concurrent Nor Parallel – Sequential Execution

Scenario 2:
Completed Thread: T2 (1)
Progressing Thread: T1,T3 (>2)

Concurrent Not Parallel

Scenario 3:
Completed Thread: T1,T2 (2)
Progressing Thread: T3,T4,T6 (>3)

Concurrent and Parallel Execution

Scenario 4:
Completed Thread P1: T1,T3
Progressing Thread P1: T2,T6

Completed Thread P2: T8
Progressing Thread P2: T4,T5

In the above keeping the status of the completed and progressing threads aside, being Multi Core processor the threads are not shared
among the processor. This is example of

Parallel Not concurrent

  1. An application can be concurrent but not parallel, which means that it processes more than one task at the same time, but no two tasks are executing at the same time instant.
  2. An application can be parallel — but not concurrent, which means that it processes multiple sub-tasks of a task in multi-core CPU at the same time.
  3. An application can be neither parallel — nor concurrent, which means that it processes all tasks one at a time, sequentially.
  4. An application can be both parallel — and concurrent, which means that it processes multiple tasks concurrently in multi-core CPU at the same time.

What is Thread in Java?
Thread is an independent path of execution.

How Program, Process, Thread and Task are related?

  1. Program contains Multiple Process.
  2. Process is instance of Program in Execution. When the Process starts, it would always start with a Single Thread. From there the No of Threads increases by the Way program has written.
  3. Threads is instance of Program in Execution.Threads within the process share the same memory as the process. A thread is a basic unit of CPU utilization, consisting of a program counter, a stack, and a set of registers. A thread of execution results from a fork of a computer program into two or more concurrently running tasks.
  4. Task is a set of program instructions that are loaded in memory. The Piece of runnable code which is loaded or Set of instruction processed by Memory is Task. A “Task” is a piece of work that will execute, and complete at some point in the future.

Two process runs on different memory space unless forked, but all threads share same memory space.

Difference between Thread and Task
Suppose you are running a Resturant. You have four Orders and Four Chef. A Order is a thread, a Chef is a processor, and a Cooking is a task. The problem you face is how to efficiently schedule the Chef and Orders so that the tasks get done as quickly as possible.

A Task means an action or work you want to do. A Thread may be one of the doer or worker performing that work.

Why should I prefer Thread over process?
Inter-thread communication (sharing data etc.) is significantly simpler to program than inter-process communication.
Context switches between threads are faster than between processes. That is, it’s quicker for the OS to stop one thread and start running another than do the same with two processes.

Example:
Applications with GUIs typically use one thread for the GUI and others for background computation. The spellchecker in MS Office, for example, is a separate thread from the one running the Office user interface. In such applications, using multiple processes instead would result in slower performance and code that’s tough to write and maintain.

It entirely depends on the design perspective whether to go for a thread or process. When I want to set of logically co-related operations to be carried out parallel. For example, if you run a Notepad++ there will be one thread running in the foreground as an editor and other thread running in background auto saving the document at regular intervals so no one would design a process to do that autosaving task separately.

What is the difference between Asynchronous vs synchronous execution?
synchronous – When you execute something synchronously, you wait for it to finish before moving on to another task. You are in a queue to get a movie ticket. You cannot get one until everybody in front of you gets one, and the same applies to the people queued behind you.

asynchronous -When you execute something asynchronously, you can move on to another task before it finishes. i.e. You are in a restaurant with many other people. You order your food. Other people can also order their food, they don’t have to wait for your food to be cooked and served to you before they can order. In the kitchen, restaurant workers are continuously cooking, serving, and taking orders. People will get their food served as soon as it is cooked.

Synchronous (one thread):

Single Thread  |--------A--------||--------B--------|                  

Synchronous (Multi-Threaded):

Thread A |--------A--------|
Thread B                   |--------B--------|
Thread C                                     |--------C--------|

ASynchronous (One thread):

           A-Start ------------------------------------------ A-End   
               | B-Start -----------------------------------------|--- B-End   
	       |    |      C-Start ------------------- C-End      |      |   
	       |    |       |                           |         |      |
  	       V    V       V                           V         V      V      
Single thread->|--A-|---B---|--C-|-A-|-C-|--A--|-B-|--C---|---A---|--B-->|

Asynchronous (Multi-Threaded):

Thread A ->     |----A-----|
Thread B ----->     |-----B-----------| 
Thread C --------->     |-------C----------|

Thread Implementation using Runnable vs Callable
A Callable needs to implement call() method while a Runnable needs to implement run() method. A Callable can return a value and throw checked exception. Runnable interface for fire and forget calls, especially when you are not interested in result of the task execution. A Callable can be used with ExecutorService#invokeXXX(Collection> tasks) methods but a Runnable cannot be. Refer here

One important difference: the run() method in the Runnable interface returns void; the call() method in the Callable interface returns an object of type T. This allows you to access a response object easily.

public interface Runnable {
    void run();
}

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

What is ExecutorService?
It manages a pool of worker threads, and allows you to submit tasks for execution. ExecutorService abstracts away many of the complexities associated with the lower-level abstractions like raw Thread. It provides mechanisms for safely starting, closing down, submitting, executing, and blocking on the successful or abrupt termination of tasks (expressed as Runnable or Callable). ExecutorService handles creation, management, and reusability of threads, making it easier to handle concurrent tasks in multithreaded applications. Refer here

An ExecutorService is a utility in Java that provides a way to execute tasks concurrently and hides the complexities of underlying thread.

Below are some benefits:

  1. Executor service manage thread in asynchronous way
  2. Use Future to get the return result after thread completion.
  3. Manage allocation of work to free thread and resale completed work from thread for assigning new work automatically
  4. fork – join framework for parallel processing
  5. Better communication between threads
  6. invokeAll and invokeAny give more control to run any or all thread at once
  7. shutdown provide capability for completion of all thread assigned work
  8. Scheduled Executor Services provide methods for producing repeating invocations of runnables and callables Hope it will help you

What is Future?
The Future interface represents the result of an asynchronous computation.It provides methods to check if the computation is complete, wait for the result, and retrieve the result

What is difference between calling submit and execute in executorService?
execute: Use it for fire and forget calls
submit: Method submit extends base method Executor.execute(Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. In nutshell submit is wrapper around 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.

submit could take both Runnable and Callable as argument

submit(Callable task) : Submits a value-returning task for execution and returns a Future representing the pending results of the task.
Future submit(Runnable task) : Submits a Runnable task for execution and returns a Future representing that task.

submit() is wrapper around execute and hides exception in the framework itself unless you embed your task code in try{} catch{} block.

execute() throws output when Runnable code actually throws exeception

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService objExecService = Executors.newFixedThreadPool(2);

        objExecService.execute(new Runnable() {
            @Override
            public void run() {
                int num = 5/0;
                System.out.println("Division by zero successful");
            }
        });

        objExecService.shutdown();
    }
}

Output

Exception in thread "pool-1-thread-1" java.lang.ArithmeticException: / by zero
	at Main$1.run(Main.java:13)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
	at java.base/java.lang.Thread.run(Thread.java:832)

submit() throws output when Runnable code actually throws exeception

public class Main {
    public static void main(String[] args) throws Exception {
        ExecutorService objExecService = Executors.newFixedThreadPool(2);

        objExecService.submit(new Runnable() {
            @Override
            public void run() {
                int num = 5/0;
                System.out.println("Division by zero successful");
            }
        });

        objExecService.shutdown();
    }
}

Output


Why thread pools are needed? Refer here
Thread objects use a significant amount of memory, and in a large-scale application, allocating and deallocating many thread objects creates a significant memory management overhead.Thread pool is a pool of already created worker thread ready to do the job. It creates Thread and manage them. Instead of creating Thread and discarding them once task is done, thread-pool reuses threads in form of worker thread.

Because creation of Thread is time consuming process and it delays request processing.

Threadpool addresses below issues.

  • Run time latency for thread creation
  • Uncontrolled use of System Resources

What is Executor? What are different ways of Creating Thread using Executors?
It provides a way to separate the task execution logic from the application code, allowing developers to focus on business logic rather than thread management.

The Executor framework consists of two main components:

  1. Executor interface and the ExecutorService interface. The Executor interface defines a single method, execute(Runnable), which is used to submit tasks for execution.
  2. The ExecutorService interface extends the Executor interface and provides additional methods for managing the execution of tasks, such as the ability to submit callables and the ability to shut down the executor.

Executor framework also provides a static utility class called Executors ( similar to Collections) which provides several static factory method to create various type of Thread Pool implementation in Java e.g. fixed size thread pool, cached thread pool and scheduled thread pool.best way to get an executor is to use one of the static factory methods provided by the Executors utility class. Some of the available factory methods in Executors class are:

  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.

Executor framework is used for creating threadpool

 ExecutorService service = Executors.newFixedThreadPool(10);

Why we need shutdown in executor service?
shutdown() method does one thing: prevents clients to send more work to the executor service. This means all the existing tasks will still run to completion unless other actions are taken. This is true even for scheduled tasks, e.g., for a ScheduledExecutorService: new instances of the scheduled task won’t run. It also frees up any background thread resources.

shutdown() method provides graceful application shutdown Prevent your application to submit new tasks, and wait for all the existing tasks to complete before shutting down the JVM.

shutdown() vs shutdownNow()?
shutdown() – Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
shutdownNow() – Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.

What is Java Fork-Join pool
Fork-Join Pools allow you to break down a larger task into smaller subtasks that can be executed concurrently. This is particularly valuable for tasks that can be divided into independent parts, such as recursive algorithms, matrix multiplication, sorting, and searching.This framework is well-suited for tasks that follow a recursive structure. A task is divided into smaller tasks until it reaches the base case, at which point the results are computed.Fork-Join Pools employ work-stealing algorithms, enabling idle threads to ‘steal’ tasks from other threads’ task queues when they have completed their own work.

What is Reactor Pattern?
The Reactor pattern efficiently handles multiple concurrent service requests by dispatching them to appropriate event handlers using a single or a limited number of threads.The idea is that you create a lot of threads which don’t do anything at first. Instead, they “wait for work”. When work arrives (in the form of code), some kind of executor service (the reactor) identifies idle threads from the pool and assigns them work to do.Use when low-latency and high-throughput in server-side applications, making it an essential strategy for modern networking frameworks and web servers

What is Future?
If you have code that performs some long-time operations and only then returns the result Future is used. Future is a placeholder. It doesn’t contain any value as long as the new thread hasn’t finished its work.

Future<String> objFuture = objExecService.submit(() ->{
              Thread.sleep(3000);
              return Thread.currentThread().getName();
});
System.out.println(objFuture.get());

While the separate thread is calculating something, the main thread continues its work. And when you think it’s finally time the value has got calculated, you write future.get() and get the actual value. But be careful: this time if the value hasn’t yet been assigned and the future is still empty, the main thread will have to wait until it happens

What is Worker Thread?
The idea is that you create a lot of threads which don’t do anything at first. Instead, they “wait for work”. When work arrives (in the form of code), some kind of executor service (the reactor) identifies idle threads from the pool and assigns them work to do. Worker Thread makes sense when taking in terms of the reactor pattern, different types of events are run by the handler threads which is similar. A thread is not tied to a single event class but will run any number of different events as they occur.

What is Interprocess Communication?
Interprocess communication (IPC) is a set of programming interfaces that allow a programmer to coordinate activities among different program processes that can run concurrently in an operating system. This allows a program to handle many user requests at the same time. Since even a single user request may result in multiple processes running in the operating system on the user’s behalf, the processes need to communicate with each other. The IPC interfaces make this possible. Each IPC method has its own advantages and limitations so it is not unusual for a single program to use all of the IPC methods.

Java interprocess communication is based at the lowest level on turning state, requests, etc into sequences of bytes that can be sent as messages or as a stream to another Java process. You can do this work yourself, or you can use a variety of “middleware” technologies of various levels of complexity to abstract away the implementation details. Technologies that may be used include, Java object serialization, XML, JSON, RMI, CORBA, SOAP / “web services”, message queing, and so on.

Interprocess Communication vs Inter-Thread Communication?
The fundamental difference is that threads live in the same address spaces, but processes live in the different address spaces. This means that inter-thread communication is about passing references to objects and changing shared objects, but processes is about passing serialized copies of objects.In practice, Java interthread communication can be implemented as plain Java method calls on a shared object with appropriate synchronization thrown in.

Inter-Thread Communication = threads inside the same JVM talking to each other.Threads inside the same JVM can use pipelining through lock-free queues to talk to each other with nanosecond latency.

Inter-Process Communication (IPC) = threads inside the same machine but running in different JVMs talking to each other.Threads in different JVMs can use off-heap shared memory (usually acquired through the same memory-mapped file) to talk to each other with nanosecond latency.

What is Starvation?
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by “greedy” threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked.

What is Livelock?
A thread often acts in response to the action of another thread. If the other thread’s action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work. This is comparable to two people attempting to pass each other in a corridor: Alphonse moves to his left to let Gaston pass, while Gaston moves to his right to let Alphonse pass. Seeing that they are still blocking each other, Alphone moves to his right, while Gaston moves to his left. They’re still blocking each other, so…

Preemptive vs Non-Preemptive Scheduling
Scheduling is order of executuion of threads. JVM would simply use the underlying threading mechanism provided by the OS.
Non-preemptive Scheduling: The current process releases the CPU either by terminating or by switching to the waiting state. (Used in MS Windows family)

Advantages are Decreases turnaround time and Does not require special HW (e.g., timer)
Disadvantages are Limited choice of scheduling algorithm

Preemptive Scheduling: The current process needs to involuntarily release the CPU when a more important process is inserted into the ready queue or once an allocated CPU time has elapsed. (Used in Unix and Unix-like systems).This is determined by priority assigned to thread.Despite priority JVM may decide to execute thread of lower priority inorder to avoid starvation.

Advantages are No limitation on the choice of scheduling algorithm
Disadvantages are Additional overheads (e.g., more frequent context switching, HW timer, coordinated access to data, etc.)

How do you implement Thread in Java?
By extending java.lang.Thread class
By implementing java.lang.Runnable interface.

Which way of implementing Thread is better? Extending Thread class or implementing Runnable method?
Implementing Runnable is better because in Java we can only extend one class so if we extend Thread class we can not extend any other class while by implementing Runnable interface we still have that option open with us

What is the difference between start() and run() method of Thread class?
start() method is used to start newly created thread, while start() internally calls run() method

When you invoke run() as normal method, its called in the same thread, no new thread is started

Spring MVC uses HttpMessageConverter to convert the Http request to an object representation and back.Spring Framework then uses one of the Jackson message converters to marshall and unmarshall Java Objects to and from JSON over HTTP.Spring will use the “Accept” header to determine the media type that it needs to respond with and uses the “Content-Type” header to determine the media type of the request body.

Default Message Converters in Spring MVC
StringHttpMessageConverter: it converts Strings from the HTTP request and response.
FormHttpMessageConverter: it converts form data to/from a MultiValueMap.
ByteArrayHttpMessageConverter: it converts byte arrays from the HTTP request and response.
MappingJackson2HttpMessageConverter: it converts JSON from the HTTP request and response.
Jaxb2RootElementHttpMessageConverter: it converts Java objects to/from XML.
SourceHttpMessageConverter: it converts javax.xml.transform.Source from the HTTP request and response.
AtomFeedHttpMessageConverter: it converts Atom feeds.
RssChannelHttpMessageConverter: it converts RSS feeds.

Customizing HttpMessageConverters with Spring MVC

Annotation Usage
@RequestMapping
@RequestMapping(value = "/{name}", 
                method = RequestMethod.GET, 
                consumes="application/json"
                produces ="application/json",
                headers={"name=pankaj", "id=1"})
path (or) (or) name (or) and value: which URL the method is mapped to
method: compatible HTTP methods
params: filters requests based on presence, absence, or value of HTTP parameters
headers: filters requests based on presence, absence, or value of HTTP headers
consumes: which media types the method can consume in the HTTP request body
produces: which media types the method can produce in the HTTP response body
@RequestBody
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public HttpStatus something(@RequestBody MyModel myModel) 
{
    return HttpStatus.OK;
}
with @RequestBody, Spring will bind the incoming HTTP request body(for the URL mentioned in @RequestMapping for that method) to that parameter. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the HTTP request body into domain object [deserialize request body to domain object], based on Accept header present in request.
@ResponseBody
@RequestMapping(value = "/user/all", method = RequestMethod.GET)
public @ResponseBody List<User> listAllUsers() {
    return userService.findAllUsers();
}
with @ResponseBody, Spring will bind the return value to outgoing HTTP response body. While doing that, Spring will [behind the scenes] use HTTP Message converters to convert the return value to HTTP response body [serialize the object to response body], based on Content-Type present in request HTTP header
@RequestParam
http://localhost:8080/springmvc/hello/101?param1=10¶m2=20

public String getDetails(
    @RequestParam(value="param1", required=true) String param1,
        @RequestParam(value="param2", required=false) String param2){
...
}
@RequestParam is to obtain an parameter from the URI as well.@RequestParam annotation used for accessing the query parameter values from the request
defaultValue – This is the default value as a fallback mechanism if request is not having the value or it is empty.
name – Name of the parameter to bind
required – Whether the parameter is mandatory or not. If it is true, failing to send that parameter will fail.
value – This is an alias for the name attribute
@PathVariable
'http://localhost:8080/springmvc/hello/101?param1=10&param2=20

@RequestMapping("/hello/{id}")    public String getDetails(@PathVariable(value="id") String id,
    @RequestParam(value="param1", required=true) String param1,
    @RequestParam(value="param2", required=false) String param2){
.......
}

@GetMapping("/user/{firstName}/{lastName}")
   @ResponseBody
   public String handler(@MatrixVariable("firstName") String firstName,
         @MatrixVariable("lastName") String lastName
         ) {

      return "<br>Matxrix variable <br> "
            + "firstName =" + firstName +"<br>"
            + "lastName =" + lastName;
   }
@PathVariable is to obtain some placeholder from the URI
@MatrixVariable – a name-value pair within a path segment is referred as matrix variable. Matrix variables can appear in any path segment, each variable separated with a semicolon (;) and multiple values are separated by comma (,)
i.e.
http://www.example.com/employee/Mike;salary=45000;dept=HR
http://www.example.com/car/Audi;color=RED,BLACK,WHITE

@RequestHeader
@Controller
public class HelloController {
 @RequestMapping(value = "/hello.htm")
 public String hello(
   @RequestHeader(value="Accept") String accept,
   @RequestHeader(value="Accept-Language") String acceptLanguage,
   @RequestHeader(value="User-Agent", defaultValue="foo") String userAgent,
   HttpServletResponse response) {

  System.out.println("accept: " + accept);
  System.out.println("acceptLanguage: " + acceptLanguage);
  System.out.println("userAgent: " + userAgent);
  
  return null;
 }
}
Reading http requestheader is written in HelloController
The advantage of using Spring @RequestHeader is that it will automatically throw an exception like HTTP Status 400 – Missing request header ‘X’ for method parameter of type, if the header is NOT sent in the input request (by setting required=true)

@RequestHeader for facilitating use to get the header details easily in our controller class

GET

  1. GET is idempotent and can be requested any number of times
  2. GET requests can be cached, can be distributed & shared
  3. GET request is less secured compared to POST.

POST

  1. Used to Create a resource
  2. Post is not idempotent.x++ is not idempotent
  3. POST is NOT idempotent. So if you retry the request N times, you will end up having N resources with N different URIs created on server.

PUT

  1. Used to Create or Modify a resource
  2. PUT is idempotent, so if you PUT an object twice, it has no effect.
  3. x=5 is idempotent.You can PUT a resource whether it previously exists, or not (eg, to Create, or to Update)!

When to use Put and Post
You can use both PUT or POST for creating the resource until the client decides the resource location in the Server.But if the server decides the resource location using

POST /questions/ HTTP/1.1
Host: www.example.com/

Note that the following is an error:

POST /questions/ HTTP/1.1
Host: www.example.com/

If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a ‘resource not found’ error because does not exist yet. You should PUT the resource on the server first.

You could though do something like this to create a resources using POST:

POST /questions HTTP/1.1
Host: www.example.com/

Note that in this case the resource name is not specified, the new objects URL path would be returned to you.

PUT is Used to create a resource, or overwrite it. While you specify the resources new URL.

PUT /questions/ HTTP/1.1
Host: www.example.com/

To overwrite an existing resource:

PUT /questions/ HTTP/1.1
Host: www.example.com/

PATCH
Patch request says that we would only send the data that we need to modify without modifying or effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first name.PATCH – HTTP.PATCH can be used when the client is sending one or more changes to be applied by the server. The PATCH method requests that a set of changes described in the request entity be applied to the resource identified by the Request-URI. The set of changes is represented in a format called a patch document.

In PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.

In PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.

DELETE

DELETE is pretty easy to understand. It is used to delete a resource identified by a URI.On successful deletion, return HTTP status 200 (OK) along with a response body, perhaps the representation of the deleted item (often demands too much bandwidth), or a wrapped response (see Return Values below). Either that or return HTTP status 204 (NO CONTENT) with no response body. In other words, a 204 status with no body, or the JSEND-style response and HTTP status 200 are the recommended responses.

  1. Caching is the ability to store copies of frequently accessed data in several places along the request-response path. When a consumer requests a resource representation, the request goes through a cache or a series of caches (local cache, proxy cache or reverse proxy) toward the service hosting the resource.
  2. If any of the caches along the request path has a fresh copy of the requested representation, it uses that copy to satisfy the request. If none of the caches can satisfy the request, the request travels all the way to the service (or origin server as it is formally known).
  3. Using HTTP headers, an origin server indicates whether a response can be cached and if so, by whom, and for how long. Caches along the response path can take a copy of a response, but only if the caching metadata allows them to do so.
  4. Few are the advantages of Caching
    • Reduce bandwidth
    • Reduce latency
    • Reduce load on servers
    • Hide network failures
  5. GET requests are cachable by default – until special condition arises. Usually, browsers treat all GET requests cacheable.
  6. POST requests are not cacheable by default but can be made cacheable if either an Expires header or a Cache-Control header with a directive, to explicitly allows caching, is added to the response. Responses to PUT and DELETE requests are not cacheable at all.

There are two main HTTP response headers that we can use to control caching behavior:
Expires : The Expires HTTP header specifies an absolute expiry time for a cached representation. Beyond that time, a cached representation is considered stale and must be re-validated with the origin server. To indicate that a representation never expires, a service can include a time up to one year in the future.

Expires: Wed, 6 March 2019 15:09:49 IST

Cache-Control:
The header value comprises one or more comma-separated directives. These directives determine whether a response is cacheable, and if so, by whom, and for how long e.g. max-age or s-maxage directives.

Cache-Control: max-age=3600
ETag: "abcd1234567n34jv"
(or)
Last-Modified: Fri, 10 May 2016 09:17:49 IST

Cacheable responses (whether to a GET or to a POST request) should also include a validator — either an ETag or a Last-Modified header.

ETag
An ETag value is an opaque string token that a server associates with a resource to uniquely identify the state of the resource over its lifetime. When the resource changes, the ETag changes accordingly.

Last-Modified
Whereas a response’s Date header indicates when the response was generated, the Last-Modified header indicates when the associated resource last changed. The Last-Modified value cannot be later than the Date value.

Supplier Accounts.java

@FunctionalInterface
public interface Accounts{
  abstract String showAccountType(); 
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Supplier Method for Accounts Interface 
  Accounts squareRoot = () -> "Hi there";
  System.out.println(squareRoot.showAccountType());
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public String showAccountType() {
    return "Hi there";
   }
  };
  System.out.println(squareRoot.showAccountType());
 }
}
Consumer Accounts.java

@FunctionalInterface
public interface Accounts {
 abstract void showAccountType(String strAccType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Consumer Method for Accounts Interface
  Accounts squareRoot = (strAccType) -> System.out.println(strAccType);
  squareRoot.showAccountType("Savings");
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public void showAccountType(String strAccType) {
    System.out.println(strAccType);
   }
  };
 }
}
Predicate Accounts.java

@FunctionalInterface
public interface Accounts{
  abstract boolean showAccountType(String accountType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Predicate Method for Accounts Interface
  Accounts squareRoot = (accountType) -> {
   if ("Savings" == accountType)
    return true;
   else
    return false;
  };

  if (squareRoot.showAccountType("Savings"))
   System.out.println("Savings");
  else
   System.out.println("Invalid Account");
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public boolean showAccountType(String accountType) {
    if ("Savings" == accountType)
     return true;
    else
     return false;
   }
  };

  if (squareRoot.showAccountType("Savings"))
   System.out.println("Savings");
  else
   System.out.println("Invalid Account");   
 }
}
Function Accounts.java

@FunctionalInterface
public interface Accounts  
{
 abstract String showAccountType(String accountType, String returnAccType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Function Method for Accounts Interface
  Accounts squareRoot = (accountType, returnType) -> {
   if (accountType == "Savings")
    return "Credit";
   else
    return "Debit";
  };

  System.out.println(squareRoot.showAccountType("Savings", null));
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public String showAccountType(String accountType, String returnAccType) {

    if (accountType == "Savings")
     return "Credit";
    else
     return "Debit";
   }
  };

  System.out.println(squareRoot.showAccountType("Savings", null));
 }
}
Urnary Operator Accounts.java

@FunctionalInterface
public interface Accounts{
 abstract String showAccountType(String accountType);
}

AccountImpl.java

public class AccountImpl {
 public static void main(String[] args) {
  //Implementation of Custom Operator Method for Accounts Interface
  Accounts squareRoot = (accountType) -> {
   return "AccountType is " + accountType;
  };
  squareRoot.showAccountType("Savings");
 }
}

The above code could be expanded as below using Anonymous Inner Class

public class AccountImpl {
 public static void main(String[] args) {
  Accounts squareRoot = new Accounts() {
   @Override
   public String showAccountType(String accountType) {
    return "AccountType is " + accountType;
   }
  };

  System.out.println(squareRoot.showAccountType("Savings"));
 }
}
  1. Optional is a wrapper class which makes a field optional which means it may or may not have values.
  2. ptional as a single-value container that either contains a value or doesn’t (it is then said to be “empty”)
  3. The advantage compared to null references is that the Optional class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.
  4. The intention of the Optional class is not to replace every single null reference. Instead, its purpose is to help design more-comprehensible APIs so that by just reading the signature of a method, you can tell whether you can expect an optional value. This forces you to actively unwrap an Optional to deal with the absence of a value.

Lets take the below code

String version = computer.getSoundcard().getUSB().getVersion();

In the above piece of java code if any of the 3 values other the Version is NULL will throw a null pointer exception. To prevent this lets add a null check

String version = "UNKNOWN";
if(computer != null){
  Soundcard soundcard = computer.getSoundcard();
  if(soundcard != null){
    USB usb = soundcard.getUSB();
    if(usb != null){
      version = usb.getVersion();
    }
  }
}

Now the above code has become Clumsy with less readability and lot of boilerplate code has been added.
In languages like Groovy these conditions could be handles like one below

String version = computer?.getSoundcard()?.getUSB()?.getVersion();
(or)
String version = 
    computer?.getSoundcard()?.getUSB()?.getVersion() ?: "UNKNOWN";

Now lets replace the above code with new Optional in Java 8

public class Computer {
  private Optional<Soundcard> soundcard;  
  public Optional<Soundcard> getSoundcard() { ... }
  ...
}

public class Soundcard {
  private Optional<USB> usb;
  public Optional<USB> getUSB() { ... }

}

public class USB{
  public String getVersion(){ ... }
}

The advantage compared to null references is that the Optional class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

What is the Point of Optional when the same could be done using NULL Check?
If you are doing NULL check the traditional way there would be no much difference. However, the difference is felt when you are carrying out chaining operations in streams and the datatypes returned are optional.The difference may not be significant in this case but as the chain of objects increases e.g. person.getAddress.getCity().getStreet().getBlock(),

Methods in Optional
get()
If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException

void ifPresent(Consumer consumer)
If a value is present, it invokes the specified consumer with the value, otherwise does nothing.

boolean isPresent()
Returns true if there is a value present, otherwise false.

static Optional ofNullable(T value)
Returns an Optional describing the specified value, if non-null, otherwise returns an empty Optional.

T orElse(T other)
Returns the value if present, otherwise returns other.

T orElseGet(Supplier other)
Returns the value if present, otherwise invokes other and returns the result of that invocation.

orElseThrow(Supplier exceptionSupplier)
Returns the contained value, if present, otherwise throws an exception to be created by the provided supplier.

Lets take a simple example where Optional returns Empty or Value based on some Condition

package com.example.demo;
import java.util.Optional;
public class Test {

 public static void main(String[] args) {
  //IfPresent
  Optional < String > strOpt = getName(" Piggy");
  System.out.print("First Call -");
  strOpt.ifPresent(System.out::println);


  Optional < String > strOpt2 = getName("");
  System.out.print("Second Call -");
  strOpt2.ifPresent(System.out::println);

  System.out.println();

  //IsPresent and get
  Optional < String > strOpt3 = getNewName(" Biggy");
  System.out.print("Third Call -");

  if (strOpt3.isPresent())
   System.out.println(strOpt3.get());


  //orElse
  Optional < String > strOpt4 = getNewName(null);
  System.out.print("Fourth Call -");
  System.out.println(strOpt4.orElse(" Hippi"));


 }

 public static Optional < String > getName(String strName) {
  if (strName.length() > 0)
   return Optional.of(strName);
  else
   return Optional.empty();
 }

 public static Optional < String > getNewName(String strName) {
  //Optional strNewName = (strName!=null)?Optional.of(strName):Optional.empty();
  return Optional.ofNullable(strName);
 }
}

Output

First Call - Piggy
Second Call -
Third Call - Biggy
Fourth Call - Hippi

@RequestBody, spring will try to convert the content of the incoming request body to your parameter object on the fly.@ResponseBody, spring will try to convert its return value and write it to the http response automatically

@Controller
@RequestMapping(value = "/bookcase")
public class BookCaseController 
{ 
    private BookCase bookCase;
 
    @RequestMapping(method = RequestMethod.GET)
    @ResponseBody
    public BookCase getBookCase() {
        return this.bookCase;
    }
 
    @RequestMapping(method = RequestMethod.PUT)
    @ResponseStatus(HttpStatus.NO_CONTENT)
    public void setBookCase(@RequestBody BookCase bookCase) {
        this.bookCase = bookCase;
    } 
}

Depending on your configuration, spring has a list of HttpMessageConverters registered in the background. A HttpMessageConverters responsibility is to convert the request body to a specific class and back to the response body again, depending on a predefined mime type. Every time an issued request is hitting a @RequestBody or @ResponseBody annotation spring loops through all registered HttpMessageConverters seeking for the first that fits the given mime type and class and then uses it for the actual conversion.

Refer here

A Bean definition contains the following piece of information called configuration metadata, which helps the container know the following things.

• The way a bean should be created.
• Life cycle details of a bean.
• Associated Bean dependencies.

The above metadata for the bean configuration is provided as a set of properties or attributes in an XML file (configuration file) which together prepare a bean definition. The following are the set of properties.

Properties Usage
class In a bean definition, it is a mandatory attribute. It is used to specify the bean class which can be used by the container to create the bean.
name In a bean definition, this attribute is used to specify the bean identifier uniquely. In XML based configuration metadata for a bean, we use the id and/or name attributes in order to specify the bean identifier(s).
scope This attribute is used to specify the scope of the objects which are created from a particular bean definition.
constructor-arg In a bean definition, this attribute is used to inject the dependencies.
properties In a bean definition, this attribute is used to inject the dependencies.
autowiring mode In a bean definition, this attribute is used to inject the dependencies.
lazy-initialization mode In a bean definition, a lazy-initialized bean informs the IoC container to create a bean instance only when it is first requested, instead of startup.
initialization method In a bean definition, a callback to be called after all required properties on the bean have been set up by the container.
destruction method In a bean definition, a callback to be used when the container that contains the bean is destroyed.

In the following example, we are going to look into an XML based configuration file which has different bean definitions. The definitions include lazy initialization (lazy-init), initialization method (init-method), and destruction method (destroy-method) as shown below. This configuration metadata file can be loaded either through BeanFactory or ApplicationContext

<?xml version = "1.0" encoding = "UTF-8"?>

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   <!-- A simple bean definition -->
   <bean id = "..." class = "...">
      <!— Here will be collaborators and configuration for this bean -->
   </bean>

   <!-- A bean definition which has lazy init set on -->
   <bean id = "..." class = "..." lazy-init = "true">
      <!-- Here will be collaborators and configuration for this bean -->
   </bean>

   <!-- A bean definition which has initialization method -->
   <bean id = "..." class = "..." init-method = "...">
      <!-- Here will be collaborators and configuration for this bean -->
   </bean>

   <!-- A bean definition which has destruction method -->
   <bean id = "..." class = "..." destroy-method = "...">
      <!-- collaborators and configuration for this bean go here -->
   </bean>

   <!-- more bean definitions can be written below -->
   
</beans>

Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

3 types of method references:

  1. Reference to a static method
  2. Reference to an instance method
  3. Reference to a constructor

Reference to a static method
Syntax

  ClassName::MethodName
import java.util.function.BiFunction;
class Arithmetic 
 {
 public static int add(int a, int b) 
 {
  return a + b;
 }
}
public class MethodReference 
{
 public static void main(String[] args) 
 {
  BiFunction < Integer, Integer, Integer > adder = Arithmetic::add;
  int result = adder.apply(10, 20);
  System.out.println(result);
 }
}

Reference to an instance method
Syntax

Object::methodName
import java.util.function.BiFunction;
class Arithmetic 
 {
 public int add(int a, int b) 
 {
  return a + b;
 }
}
public class MethodReference 
{
 public static void main(String[] args) 
 {
  Arithmetic objArithmetic = new Arithmetic();
  BiFunction < Integer, Integer, Integer > adder = objArithmetic::add;
  int result = adder.apply(10, 20);
  System.out.println(result);
 }
}

Reference to a constructor
Syntax

ClassName::new  
interface Messageable {
 Message getMessage(String msg);
}
class Message {
 Message(String msg) {
  System.out.print(msg);
 }
}
public class ConstructorReference {
 public static void main(String[] args) {
  Messageable hello = Message::new;
  hello.getMessage("Hello");
 }
}