Answers
Answers
Answers
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.
6.
java.lang.OutOfMemoryError Example
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.
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:
7.
A Web server exclusively handles HTTP requests, whereas an application server serves business logic to
application programs through any number of protocols.
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.
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.
To summarize, a Web server simply processes HTTP requests by responding with HTML pages.
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
Although it is not completely possible to avoid deadlock condition, but we can follow certain measures
or pointers to avoid them:
12.
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.
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.
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.
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:
In the above output, we can observe that variable c is giving wrong values.
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.
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:
13.
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.
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.
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
throws TransactionException;
int getPropagationBehavior();
int getIsolationLevel();
String getName();
int getTimeout();
boolean isReadOnly();
boolean isNewTransaction();
boolean hasSavepoint();
void setRollbackOnly();
boolean isRollbackOnly();
boolean isCompleted();
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.
XML
</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">
</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>
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>
XML
</bean>
File Name: City.java
Java
class City {
{
this.s = sta;
}
{
}
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>
</beans>
@SpringBootApplication
{
SpringApplication.run(DemoApplication.class, args);
cty.setId(01);
cty.setName("Varanasi");
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
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.