Sei sulla pagina 1di 8

What is synchronization ?

Synchronization is the ability to control the access of multiple threads to


shared resources. Synchronization stops multithreading. With
synchronization at a time only one thread will be able to access a shared
resource.

What is the difference between synchronized block and


synchronized method ?
1) One significant difference between synchronized method and block is that,
Synchronized block generally reduce scope of lock. As scope of lock is
inversely proportional to performance, its always better to lock only critical
section of code. One of the best example of using synchronized block is
double checked locking in Singleton pattern where instead of locking whole
getInstance() method we only lock critical section of code which is used to
create Singleton instance. This improves performance drastically because
locking is only required one or two times.

2) Synchronized block provide granular control over lock, as you can use
arbitrary any lock to provide mutual exclusion to critical section code. On the
other hand synchronized method always lock either on current object
represented by this keyword or class level lock, if its static synchronized
method.

3) Synchronized block can throw throw java.lang.NullPointerException if


expression provided to block as parameter evaluates to null, which is not the
case with synchronized methods.

4) In case of synchronized method, lock is acquired by thread when it enter


method and released when it leaves method, either normally or by throwing
Exception. On the other hand in case of synchronized block, thread acquires
lock when they enter synchronized block and release when they leave
synchronized block.

Read more: http://www.java67.com/2013/01/difference-between-


synchronized-block-vs-method-java-example.html#ixzz4eYrApBju

Similarities between Yield and Sleep method

1. Static method : Both yield and sleep method are static method . Hence ,
they always change the state of currently executing thread .

2. java.lang.Thread : Both yield and sleep method belongs to the


java.lang.Thread class.

3. Currently executing thread : Both methods affect the state of currently


executing thread .yield method may pause it while sleep method will stop it
for a specified time .

Difference between Yield and Sleep method in Java with Example

1. Currently executing thread state : Sleep method causes the currently


executing thread to sleep for the number of milliseconds or the nanoseconds
specified in the argument.

There are two overloaded sleep methods

sleep (long milliseconds) , takes milliseconds as an argument.


and
sleep (long milliseconds , int nanoseconds) specifies milliseconds and
nanoseconds as an argument.

According to Oracle docs,


Yield method temporarily pauses the currently executing thread to give a
chance to the remaining waiting threads of the same priority to execute.
If there is no waiting thread or all the waiting threads of low priority then the
current thread will continue its execution.

2. Interrupted Exception : Sleep method throws the Interrupted exception


if another thread
interrupts the sleeping thread . yield method does not throw Interrupted
Exception.

3. Give up monitors : Thread.sleep() method does not cause cause


currently executing thread to give up any monitors while yield() method give
up the monitors.
public static void sleep(long miliseconds)throws InterruptedException
public static void sleep(long miliseconds, int nanos)throws
InterruptedException
public static void yield()

Difference between Sleep and Wait method in Java

1. Class belongs : The wait() method belongs to java.lang.Object class, thus can
be called on any Object. The sleep() method belongs to java.lang.Thread class, thus
can be called on Threads.

2. Context : The wait() method can only be called from Synchronized context i.e.
using synchronized block or synchronized method. The sleep() method can be called
from any context.

3. Locking : The wait() method releases the lock on an object and gives others
chance to execute. The sleep() method does not releases the lock of an object for
specified time or until interrupt.

4. Wake up condition : A waiting thread can be awake by notify() or notifyAll()


method. A sleeping can be awaked by interrupt or time expires.

5. Execution : Each object has each wait() method for inter-communication


between threads. The sleep() method is static method belonging to Thread class.
There is a common mistake to write t.sleep(1000) because sleep() is a class method
and will pause the current running thread not t.

Similarities between wait() and sleep()

Thread state: Both the method wait() and sleep() makes the running thread into
Not Runnable state.

Running time: Both the method wait() and sleep() takes total execution time in
milliseconds as an argument, after that it will be expired.

public final void wait(long timeout)

Exception
IllegalArgumentException if the value of timeout is negative.
IllegalMonitorStateException if the current thread is not the
owner of the object's monitor.
InterruptedException if another thread has interrupted the current
thread. The interrupted status of the current thread is cleared when
this exception is thrown.
When to use wait()

The wait() is used for multi threaded synchronization, where single


resource is shared among multiple thread.

For example, file resources over network.

When to use sleep()

The wait() is used for time synchronization, where the thread actually
needs a delay in background.
For example, process something on specific interval.

What must be the order of catch blocks when catching more than
one exception?
The sub classes must come first. Otherwise it will give a compile time error.

What is Connection pooling ?

Connection pooling is a technique used for sharing server resources among


requesting clients. Connection pooling increases the performance of Web
applications by reusing active database connections instead of creating a
new connection with every request. Connection pool manager maintains a
pool of open database connections.

How do you handle your own transaction ?


Connection Object has a method called setAutocommit ( boolean flag) . For
handling our own transaction we can set the parameter to false and begin
your transaction . Finally commit the transaction by calling the commit
method.

Application Component Provider


The application component provider is the company or person who creates
web components, enterprise beans, applets, or application clients for use in
Java EE applications.

What modifiers may be used with an inner class that is a member of


an outer class?
Inner class may be declared as public, protected, private, static, final, or
abstract.
How you will enable front-end validation based on the xml in
validation.xml?
The < html:javascript > tag to allow front-end validation based on the xml in
validation.xml. For example the code: < html:javascript
formName=logonForm dynamicJavascript=true staticJavascript=true / >
generates the client side java script for the form logonForm as defined in the
validation.xml file. The < html:javascript > when added in the jsp file
generates the client site validation script.

Can we use the constructor, instead of init(), to initialize servlet ?


Yes. But you will not get the servlet specific things from constructor. The
original reason for init() was that ancient versions of Java couldnt
dynamically invoke constructors with arguments, so there was no way to
give the constructor a ServletConfig. That no longer applies, but servlet
containers still will only call your no-arg constructor. So you wont have
access to a ServletConfig or ServletContext.

What is the difference in using request.getRequestDispatcher() and


context.getRequestDispatcher() ?
In request.getRequestDispatcher(path) in order to create it we need to give
the relative path of the resource. But in
resourcecontext.getRequestDispatcher(path) in order to create it we need to
give the absolute path of the resource.

What is the difference in using request.getRequestDispatcher() and


context.getRequestDispatcher() ?
In request.getRequestDispatcher(path) in order to create it we need to give
the relative path of the resource. But in
resourcecontext.getRequestDispatcher(path) in order to create it we need to
give the absolute path of the resource.

Whats HQL ?
HQL is the query language used in Hibernate which is an extension of SQL.
HQL is very efficient, simple and flexible query language to do various type
of operations on relational database without writing complex database
queries.

How can we see hibernate generated SQL on console ?


We need to add following in hibernate configuration file to enable viewing
SQL on the console for debugging purposes <property name="show_sql"
>true</property>

Which two method you need to implement for key Object in


HashMap ?
In order to use any object as Key in HashMap, it must implements equals and
hashcode method in Java.
Explain the importance of hashCode() and equals() method ? Explain
the contract also ?

HashMap object uses Key object hashCode() method and equals() method to
find out the index to put the key-value pair. If we want to get value from the
HashMap same both methods are used . Somehow, if both methods are not
implemented correctly , it will result in two keys producing the same
hashCode() and equals() output. The problem will arise that HashMap will
treat both output same instead of different and overwrite the most recent
key-value pair with the previous key-value pair.
Similarly all the collection classes that does not allow the duplicate values
use hashCode() and equals() method to find the duplicate elements.So it is
very important to implement them correctly.

Contract of hashCode() and equals() method

a. If object1.equals(object2) , then object1.hashCode() ==


object2.hashCode() should always be true.

b. If object1.hashCode() == object2.hashCode() is true does not guarantee


object1.equals(object2)

public boolean equals(Object obj)


public int hashCode()

Difference between == and .equals() ?

Ans. "equals" is the member of object class which returns true if the content
of objects are same whereas "==" evaluate to see if the object handlers on
the left and right are pointing to the same object in memory.

What are the methods of Object Class ?

Ans. clone() - Creates and returns a copy of this object.


equals() - Indicates whether some other object is "equal to" this one.
finalize() - Called by the garbage collector on an object when garbage
collection determines that there are no more references to the object
getClass() - Returns the runtime class of an object.
hashCode() - Returns a hash code value for the object.
toString() - Returns a string representation of the object.
notify(), notifyAll(), and wait() - Play a part in synchronizing the activities of
independently running threads in a program.

Which class does not override the equals() and hashCode()


methods, inheriting them directly from class Object?
Ans. java.lang.StringBuffer.

1) use == to compare primitive e.g. boolean, int, char etc, while use equals()
to compare objects in Java.
2) == return true if two reference are of same object. Result of equals()
method depends on overridden implementation.
3) For comparing String use equals() instead of == equality operator.

Explain java.lang.OutOfMemoryError ?

Ans. This Error is thrown when the Java Virtual Machine cannot allocate an
object because it is out of memory, and no more memory could be made
available by the garbage collector.

Should we override finalize method ?

Ans. Finalize is used by Java for Garbage collection. It should not be done as
we should leave the Garbage Collection to Java itself.

Potrebbero piacerti anche