You are on page 1of 21

1.

PUT POST
This method is idempotent. This method is not idempotent.
PUT method is call when you have to modify a single POST method is call when you have to add a child
resource, which is already a part of resource collection. resource under resources collection.
RFC-2616 depicts that the PUT method sends a request for This method requests the server to accept the entity
an enclosed entity stored in the supplied request URI. which is enclosed in the request.
PUT method syntax is PUT /questions/{question-id} POST method syntax is POST /questions
PUT method answer can be cached. You cannot cache PUT method responses.
POST /vi/juice/orders indicates that you are creating a
PUT /vi/juice/orders/1234 indicates that you are updating
new resource and return an identifier to describe the
a resource which is identified by “1234”.
resource.
If you send the same request multiple times, the result will If you send the same POST request more than one time,
remain the same. you will receive different results.
PUT works as specific. POST work as abstract.
We use UPDATE query in PUT. We use create query in POST.
In PUT method, the client decides which URI resource In POST method, the server decides which URI resource
should have. should have.

5.we can use self join as:

SELECT e1.name FROM Employee e1


JOIN Employee e2 ON e1.ManagerId = e2.Id
WHERE e1.salary > e2.salary

6.

A java.lang.OutOfMemoryErrorusually means that something is wrong in the application - for example,


the application code is referencing large objects for too long or trying to process large amounts of data
at a time. The problems could also exist in third-party libraries used within an application.

java.lang.OutOfMemoryError Example

Here is an example of a java.lang.OutOfMemoryError thrown due to insufficient Java heap space:

public class OutOfMemoryErrorExample {


public static void main(String[] args) {
Integer[] myArray = new Integer[1000 * 1000 * 1000];
}
}
In this example, an Integer array with a very large size is attempted to be initialized. Because the Java
heap is insufficient to allocate this array, it throws a java.lang.OutOfMemoryError: Java heap space

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space


at OutOfMemoryErrorExample.main(OutOfMemoryErrorExample.java:8)

A java.lang.OutOfMemoryError: Java heap space can also occur in applications that use finalizers
excessively. If a class has a finalize() method, the GC does not clean up any objects of that class and they
are instead queued for finalization, which occurs at a later stage. If the finalizer thread cannot keep up
with the finalization queue (due to excessive usage of finalizers), the Java heap space can fill up and
a java.lang.OutOfMemoryError can occur.

How to Catch java.lang.OutOfMemoryError

Since the java.lang.OutOfMemoryError descends from the Throwable class, it can be caught and


handled in application code. In some cases, especially when the lines of code that may be causing
the OutOfMemoryError are known, it can be a good idea to handle the error. Where it’s possible to do
so, it is best practice to clean up the resources, log the reason for the failure and exit the program
gracefully. As an example:

public class OutOfMemoryErrorExample {


public void createArray(int size) {
try {
Integer[] myArray = new Integer[size];
} catch (OutOfMemoryError oome) {
//Log the info
System.err.println("Array size too large");
System.err.println("Max JVM memory: " + Runtime.getRuntime().maxMemory());
}
}

public static void main(String[] args) {


OutOfMemoryErrorExample oomee = new OutOfMemoryErrorExample();
oomee.createArray(1000 * 1000 * 1000);
}
}

In this case, because the line of code that may cause an OutOfMemoryError is known, it is handled in a
try-catch block and the reason for the error is logged (the large size of the array) along with the
maximum size of the JVM, which helps the caller of the method to take corrective action. The program
exits with the following message:

Array size too large


Max JVM memory: 4294967296
It is also a good idea to handle an OutOfMemoryError when the application needs to be left in a
consistent state in case the error occurs. This enables the program to continue running normally if new
objects are not attempted to be allocated.

7.

A Web server exclusively handles HTTP requests, whereas an application server serves business logic to
application programs through any number of protocols.

Let's examine each in more detail.

The Web server

A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds
with an HTTP response, such as sending back an HTML page. To process a request, a Web server may
respond with a static HTML page or image, send a redirect, or delegate the dynamic response
generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active
Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose,
such server-side programs generate a response, most often in HTML, for viewing in a Web browser.

Understand that a Web server's delegation model is fairly simple. When a request comes into the Web
server, the Web server simply passes the request to the program best able to handle it. The Web server
doesn't provide any functionality beyond simply providing an environment in which the server-side
program can execute and pass back the generated responses. The server-side program usually provides
for itself such functions as transaction processing, database connectivity, and messaging.

While a Web server may not itself support transactions or database connection pooling, it may employ
various strategies for fault tolerance and scalability such as load balancing, caching, and clustering—
features oftentimes erroneously assigned as features reserved only for application servers.

The application server

As for the application server, according to our definition, an application server exposes business logic to
client applications through various protocols, possibly including HTTP. While a Web server mainly deals
with sending HTML for display in a Web browser, an application server provides access to business logic
for use by client application programs. The application program can use this logic just as it would call a
method on an object (or a function in the procedural world).

Such application server clients can include GUIs (graphical user interface) running on a PC, a Web server,
or even other application servers. The information traveling back and forth between an application
server and its client is not restricted to simple display markup. Instead, the information is program logic.
Since the logic takes the form of data and method calls and not static HTML, the client can employ the
exposed business logic however it wants.

In most cases, the server exposes this business logic through a component API, such as the EJB
(Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application
servers. Moreover, the application server manages its own resources. Such gate-keeping duties include
security, transaction processing, resource pooling, and messaging. Like a Web server, an application
server may also employ various scalability and fault-tolerance techniques.

An example

As an example, consider an online store that provides real-time pricing and availability information.
Most likely, the site will provide a form with which you can choose a product. When you submit your
query, the site performs a lookup and returns the results embedded within an HTML page. The site may
implement this functionality in numerous ways. I'll show you one scenario that doesn't use an
application server and another that does. Seeing how these scenarios differ will help you to see the
application server's function.

Scenario 1: Web server without an application server


In the first scenario, a Web server alone provides the online store's functionality. The Web server takes
your request, then passes it to a server-side program able to handle the request. The server-side
program looks up the pricing information from a database or a flat file. Once retrieved, the server-side
program uses the information to formulate the HTML response, then the Web server sends it back to
your Web browser.

To summarize, a Web server simply processes HTTP requests by responding with HTML pages.

Scenario 2: Web server with an application server


Scenario 2 resembles Scenario 1 in that the Web server still delegates the response generation to a
script. However, you can now put the business logic for the pricing lookup onto an application server.
With that change, instead of the script knowing how to look up the data and formulate a response, the
script can simply call the application server's lookup service. The script can then use the service's result
when the script generates its HTML response.

In this scenario, the application server serves the business logic for looking up a product's pricing
information. That functionality doesn't say anything about display or how the client must use the
information. Instead, the client and application server send data back and forth. When a client calls the
application server's lookup service, the service simply looks up the information and returns it to the
client.

By separating the pricing logic from the HTML response-generating code, the pricing logic becomes far
more reusable between applications. A second client, such as a cash register, could also call the same
service as a clerk checks out a customer. In contrast, in Scenario 1 the pricing lookup service is not
reusable because the information is embedded within the HTML page. To summarize, in Scenario 2's
model, the Web server handles HTTP requests by replying with an HTML page while the application
server serves application logic by processing pricing and availability requests.

8.

JDBC is java database API, while JNDI is java native directory API.

The main thing in here is that in a JNDI directory you’re actually storing a JDBC DataSource, so,
you’re simply using JDBC and obtain a Connection via JNDI lookup.
In short words: JDBC is a Database realm, JNDI lets you store Objects in a virtual context (the Directory)
that can be local, remote (Implementation details usually don’t matters).

You access this context via names, obtaining stored objects, it is good to share things among different
modules.

Application Servers usually have a JNDI Context for sharing global objects amon different application,
Connection Poolers happen to be one of the most clear examples of why sharing via JNDI is good. 

JNDI is the directory that contains the list of objects defined on the server. When the user requests for a
connection pool, the code would look for the object on the JNDI and would get the requested
connection pool from the data source. JDBC is the one which does all the interactions with the database.
An application will lookup the JNDI to get a connection pool for it to interact with the database.

11.

Deadlock in Java is a condition where two or more threads are blocked forever, waiting for each other.

This usually happens when multiple threads need the same locks but obtain them in different
orders. Multithreaded Programming in Java suffers from the deadlock situation because of the
synchronized keyword.

It causes the executing thread to block while waiting for the lock, or monitor, associated with the
specified object.
Deadlock Example

1 public class Example{


2  public static void main(String[] args){
3    final String r1 = "edureka";
4    final String r2 = "java";
5  
6    Thread t1 = new Thread() {
7      public void run(){
8        synchronized(r1){
9         System.out.println("Thread 1: Locked r1");
10         try{ Thread.sleep(100);} catch(exception e) {}
11       synchronized(r2){
12         System.out.println("Thread 1: Locked r2");
13         }
14      }
15   }
16 };
17  Thread t2 = new Thread() {
18       public void run(){
19        synchronized(r1){
20         System.out.println("Thread 2: Locked r1");
21         try{ Thread.sleep(100);} catch(exception e) {}
22       synchronized(r2){
23        System.out.println("Thread 2: Locked r2");
24       }
25     }
26   }
27 };
28  
29 t1.start();
30 t2.start();
31 }
32 }
Output: Thread 1: Locked r1
Thread 2: Locked r2
How To Avoid Deadlock in Java?

Although it is not completely possible to avoid deadlock condition, but we can follow certain measures
or pointers to avoid them:

12.

What is race condition?

A condition in which the critical section (a part of the program where shared memory is accessed) is
concurrently executed by two or more threads. It leads to incorrect behavior of a program.

In layman terms, a race condition can be defined as, a condition in which two or more threads compete
together to get certain shared resources.

For example, if thread A is reading data from the linked list and another thread B is trying to delete the
same data. This process leads to a race condition that may result in run time error.

There are two types of race conditions:

1. Read-modify-write
2. Check-then-act

The read-modify-write patterns signify that more than one thread first read the variable, then alter the
given value and write it back to that variable. Let's have a look at the following code snippet.

1. public class number  
2. {  
3. protected long number = 0;  
4. public void add(long value)  
5. {  
6. this.number = this.number + value;  
7. }  
8. }  

Why it occurs?

It occurs when two or more threads operate on the same object without proper synchronization and
their operation incorporates each other.

Example of Race condition

Suppose, there are two processes A and B that are executing on different processors. Both processes are
trying to call the function bankAccount() concurrently. The value of the shared variable that we are
going to pass in the function is 1000.

Consider, A call the function bankAccount() and passing a value 200 as a parameter. In the same way,
process B is also calling the function bankAccount() and passing a value of 100 as a parameter.

The result look like as follows:

o Process A loads 1100 into the CPU register.


o Process B will load 1100 into its register.
o Process A will add 200 to its register then the result will be 1300
o Process B will add 100 its register and the calculated result will be 1200
o Process A will store 1400 in a shared variable and process B will store 1150 in a shared variable.

RaceConditionProgram.java

1. class Counter implements Runnable  
2. {  
3. private int c = 0;  
4. public void increment()   
5. {  
6. try   
7. {  
8. Thread.sleep(10);  
9. }   
10. catch (InterruptedException e)   
11. {  
12. //Auto-generated catch block  
13. e.printStackTrace();  
14. }  
15. c++;  
16. }  
17. public void decrement()   
18. {      
19. c--;  
20. }  
21. public int getValue()   
22. {  
23. return c;  
24. }  
25. @Override  
26. public void run()   
27. {  
28. //incrementing  
29. this.increment();  
30. System.out.println("Value for Thread After increment " + Thread.currentThread().getName() + " " + this.
getValue());  
31. //decrementing  
32. this.decrement();  
33. System.out.println("Value for Thread at last " + Thread.currentThread().getName() + " " + this.getValue()
);          
34. }  
35. }  
36. public class RaceConditionDemo  
37. {  
38. public static void main(String args[])   
39. {  
40. Counter counter = new Counter();  
41. Thread t1 = new Thread(counter, "Thread-1");  
42. Thread t2 = new Thread(counter, "Thread-2");  
43. Thread t3 = new Thread(counter, "Thread-3");  
44. t1.start();  
45. t2.start();  
46. t3.start();  
47. }      
48. }  

Output:

Value for Thread After increment Thread-1 2


Value for Thread at last Thread-1 2
Value for Thread After increment Thread-3 3
Value for Thread at last Thread-3 1
Value for Thread After increment Thread-2 2
Value for Thread at last Thread-2 0

In the above output, we can observe that variable c is giving wrong values.

How to avoid it?

There are the following two solutions to avoid race conditions.

o Mutual exclusion
o Synchronize the process

AD

In order to prevent the race conditions, one should ensure that only one process can access the shared
data at a time. It is the main reason why we need to synchronize the processes.

Another solution to avoid race condition is mutual exclusion. In mutual exclusion, if a thread is using a
shared variable or thread, another thread will exclude itself from doing the same thing.

Let's see a Java program for the same.

AvoidRaceCondition.java

1. class Counter implements Runnable  
2. {  
3. private int c = 0;  
4. public void increment()   
5. {  
6. try   
7. {  
8. Thread.sleep(10);  
9. }   
10. catch (InterruptedException e)   
11. {  
12. e.printStackTrace();  
13. }  
14. c++;  
15. }  
16. public void decrement()   
17. {      
18. c--;          
19. }  
20. public int getValue()   
21. {  
22. return c;  
23. }  
24. @Override  
25. public void run()   
26. {  
27. synchronized(this)  
28. {  
29. // incrementing  
30. this.increment();  
31. System.out.println("Value for Thread After increment " + Thread.currentThread().getName() + " " + this.
getValue());  
32. //decrementing  
33. this.decrement();  
34. System.out.println("Value for Thread at last " + Thread.currentThread().getName() + " " + this.getValue()
);  
35. }          
36. }  
37. }  
38. public class RaceConditionDemo  
39. {  
40. public static void main(String args[])   
41. {  
42. Counter counter = new Counter();  
43. Thread t1 = new Thread(counter, "Thread-1");  
44. Thread t2 = new Thread(counter, "Thread-2");  
45. Thread t3 = new Thread(counter, "Thread-3");  
46. t1.start();  
47. t2.start();  
48. t3.start();  
49. }      
50. }  

Output:

Value for Thread After increment Thread-1 1


Value for Thread at last Thread-1 0
Value for Thread After increment Thread-3 1
Value for Thread at last Thread-3 0
Value for Thread After increment Thread-2 1
Value for Thread at last Thread-2 0
It can be seen from the output how threads are accessing the shared resource one at a time now.
Synchronizing the access within the run() method made it happen.

13.

Step 1: Find process id by using ps command like

$ ps -ef | grep java


user 22031 22029   0   Jan 29 ?          24:53 java -Xms512M -Xmx512 Server

here 22031 is process id or PID. By the way, if there are more than one Java process running in your
server than you might want to use a more specific grep command to find PID. 

Step 2: Find the Runtime or start time of a process


Once you found PID, you can look into proc directory for that process and check creation date, that's the
time when your process was started. 

By looking that timestamp you can easily find from how long your process is running in Linux. 

In order to check the timestamp of any process id procs directory, you can use following ls UNIX
command with option -ld as shown below :

$ ls -ld /proc/22031
dr-x--x--x   5 user     group           832 Jan 22 13:09 /proc/22031

Here process with PID 22031 has been running from Jan 22, 13:09.

If you are lucky, sometimes PS command also shows when a particular program has been started as
shown in the following image:

14.
a. Programmatic Transaction Management in Spring

Spring Programmatic Transaction Management allows you to manage transaction with programming in
your source code. It gives you lot of flexibility which might be hard to maintain. For Programmatic
approach, PlatformTransactionManager is used for implementation. For creating new transactions, you
need an instance of TransactionDefinition. You should create ofDefaultTransactionDefinition instances
for using default transaction attributes. Once the TransactionDefinition gets created you can call
getTransaction() for starting a transaction. This method returns an instance of TransactionStatus which
helps in tracking current status. If everything goes well you can use commit() of
PlatformTransactionManager.

b. Declarative Transaction Management in Spring

Spring Declarative Transaction Management allows you to manage transaction using configuration,
unlike Programmatic approach. Declarative Transaction allows separating transactions from business
code. So, you can use XML configurations for managing transactions. The bean configuration helps in
specifying the methods to be transactional. Some of the steps required for the Declarative approach:

 Make use of the tag <tx: advice /> for creating transaction-handling advice. Also, at the same time
define pointcut which matches all methods you wish to make a transaction.
 If the method is there in the configuration then the advice will begin transaction before calling the
method.
 The Target() will get executed in a try block.
 If Target() finishes the AOP commits transaction successfully else rollback happens.
c. Spring Transaction Abstractions

Spring Transaction Management uses org.springframework.transaction.PlatformTransactionManager


which is defined as below:

public interface PlatformTransactionManager {

TransactionStatus getTransaction(TransactionDefinition definition);

throws TransactionException;

void commit(TransactionStatus status) throws TransactionException;

void rollback(TransactionStatus status) throws TransactionException;

Some above methods are described as follow:


i. TransactionStatus getTransaction(TransactionDefinition def) 
This method is for returning current active transaction or creates a new one.
ii. Void commit(TransactionStatus stat)
This method commits when the given transaction gets completed.
iii. Void rollback(TransactionStatus stat)
This method does rollback of the given transaction.
The TransactionDefinition is a core interface which is defined as follows along with the description of the
methods:
public interface TransactionDefinition {

int getPropagationBehavior();

int getIsolationLevel();

String getName();

int getTimeout();

boolean isReadOnly();

iv. Int getPropagationBehavior()


This method returns the propagation behavior an integer. Spring offers all the transaction options
similar to EJB CMT.
v. Int getIsolationLevel()
This method returns the degree of which transaction is separated from other transactions.
vi. String getName()
This method is of string type which returns the name of a transaction.
vii. Int getTimeout()
This is an integer method which returns the time up to which the transaction should get completed.
viii. Bool isReadOnly()
This Boolean type method returns whether the transaction is a read-only transaction or not.
Now the TransactionStatus interface which controls query transaction status and execution in Spring
Framework along with its methods are as follows:
public interface TransactionStatus extends SavepointManager {

boolean isNewTransaction();

boolean hasSavepoint();

void setRollbackOnly();

boolean isRollbackOnly();

boolean isCompleted();

ix. Bool hasSavepoint()


This method returns Boolean type for the transactions. It tells whether the transaction internally carries
savepoint or not.
x. Bool isCompleted()
This method returns Boolean type for the transactions. It tells whether the transactions are complete or
not.

xi. Bool isNewTransaction()


This method returns Boolean type. It returns true when the present transaction is new.
xii. Void setRollbackOnly()
This makes the transactions to be rollback only.
xiii. Bool isRollbackOnly()
It is a Boolean type method. This method returns whether the transaction is rollback only.

15.

Spring framework does not do anything under the hood concerning the multi-threaded behavior of a
singleton bean. It is the developer’s responsibility to deal with concurrency issue and thread safety of
the singleton bean.

While practically, most spring beans have no mutable state, and as such are trivially thread safe. But if
your bean has mutable state, so you need to ensure thread safety. The most easy and obvious solution
for this problem is to change bean scope of mutable beans from “singleton” to “prototype“.

17.

There are five modes of autowiring:


1. No
This mode tells the framework that autowiring is not supposed to be done. It is the default mode used
by Spring.

 XML

<bean id="state" class="sample.State">

 <property name="name" value="UP" />

</bean>

<bean id="city" class="sample.City"></bean>

2. byName
It uses the name of the bean for injecting dependencies. However, it requires that the name of the
property and bean must be the same. It invokes the setter method internally for autowiring.

 XML
<bean id="state" class="sample.State">

 <property name="name" value="UP" />

</bean>

<bean id="city" class="sample.City" autowire="byName"></bean>

3. byType
It injects the dependency according to the type of the bean. It looks up in the configuration file for the
class type of the property. If it finds a bean that matches, it injects the property. If not, the program
throws an error. The names of the property and bean can be different in this case. It invokes the
setter method internally for autowiring.

 XML

<bean id="state" class="sample.State">

 <property name="name" value="UP" />

</bean>

<bean id="city" class="sample.City" autowire="byType"></bean>

4. constructor
It injects the required dependencies by invoking the constructor. It works similar to the “byType”
mode but it looks for the class type of the constructor arguments. If none or more than one bean are
detected, then it throws an error, otherwise, it autowires the “byType” on all constructor arguments.

 XML

<bean id="state" class="sample.State">

 <property name="name" value="UP" />

</bean>

<bean id="city" class="sample.City" autowire="constructor"></bean>


5. autodetect
The autodetect mode uses two other modes for autowiring – constructor and byType. It first tries to
autowire via the constructor mode and if it fails, it uses the byType mode for autowiring. It works in
Spring 2.0 and 2.5 but is deprecated from Spring 3.0 onwards.

 XML

<bean id="state" class="sample.State">

 <property name="name" value="UP" />

</bean>

<bean id="city" class="sample.City" autowire="autodetect"></bean>

Sample Program for the byType Mode


File Name: State.java
 Java

public class State {

    private String name;

    public String getName() { return name; }

    public void setName(String s) { this.name = s; }

File Name: City.java
 Java

class City {

    private int id;

    private String name;


    private State s;

    public int getID() { return id; }

    public void setId(int eid) { this.id = eid; }

    public String getName() { return name; }

    public void setName(String st) { this.name = st; }

    public State getState() { return s; }

    @Autowired public void setState(State sta)

    {

        this.s = sta;

    }

    public void showCityDetails()

    {

        System.out.println("City Id : " + id);

        System.out.println("City Name : " + name);

        System.out.println("State : " + s.getName());

    }

Spring bean configuration file:


 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: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">

<bean id="state" class="sample.State">

<property name="name" value="UP" />

</bean>

<bean id="city" class="sample.City" autowire="byName"></bean>

</beans>

Test Program file: DemoApplication.java


 Java

@SpringBootApplication

public class DemoApplication {

    public static void main(String[] args)

    {
        SpringApplication.run(DemoApplication.class, args);

        ApplicationContext context = new


ClassPathXmlApplicationContext("applicationContext.xml");

        City cty = context.getBean("city", City.class);

        cty.setId(01);

        cty.setName("Varanasi");

        State st = context.getBean("state", State.class);

        st.setName("UP");

        cty.setState(st);

        cty.showCityDetails();

    }

Output: 
City ID : 01
City Name : Varanasi
State : UP

Advantage of Autowiring

It requires less code because we don’t need to write the code to inject the dependency explicitly.

Disadvantage of Autowiring

 No control of the programmer.


 It can’t be used for primitive and string values.
18. To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig
encounters such a method, it will execute that method and register the return value as a bean within a
BeanFactory .

23. A heap dump is a snapshot of all the objects that are in memory in the JVM at a certain moment.
They are very useful to troubleshoot memory-leak problems and optimize memory usage in Java
applications.
Heap dumps are usually stored in binary format hprof files. We can open and analyze these files using
tools like jhat or JVisualVM. Also, for Eclipse users, it's very common to use MAT.
In the next sections, we'll go through multiple tools and approaches to generate a heap dump, and we'll
show the main differences between them.

You might also like