MY mENU


Friday 16 March 2012

Can we place only parameterized constructors in a servlet class?


 No.. Because Web-container creates object of our servlet class using zero argument constructor. If servlet class contains only parameterized constructor the java compiler does not generate zero argument constructor so web-container fails to create an object of servlet class. So a programmer must make sure that the servlet class is going to contain zero argument constructor explicitly or implicitly. Because web-container uses zero argument constructor to create object of a servlet.

Note: When java class is not having any constructor the compiler automatically generates zero argument constructor. If java class is having user-defined constructors the compiler does not generate the default zero argument constructor.

Different ways to develop servlets?

How can you develop a servlet?

                            (OR)
      What are different ways to develop servlets?

Every servlet is a java class.There are 3 ways to develop a servlet based on servlet-API.

 1.Take a public java class implementing javax.servlet. servlet interface & provide implementation for all the 5 methods of that interface.

 2. Take a public java class extending from javax.servlet. Generic servlet &provide implementation for abstract method called service(servlet request, servlet response) method.

 3. Take a public java class extending from javax.servlet.http servlet &override either one of the                 7 doxxx() methods (or) one of the two service ()methods.

Difference between GET and POST ?




               GET
            
                   POST   


Designed to get the data from web server


Designed to send the data to web server    

Can send limited amount of data to the server along with request.


Can send unlimited amount of data to the server

Query string will be visible in the browser address bar due to this there is no data secrecy


Query string will not be visible in the browser address bar  due to this there will be data secrecy.       

Not suitable for file uploading


 Suitable for file uploading   

Can’t send the data by applying encryption


Can send the data by applying encryption.

Default  HttpRequest method for request is Get()


This  is not default

Use  doGet() mehod or service() to receive request  and to process request in HttpServlet

Use  doPost() method or service() method to receive request and to process the request.     
    

Get is idempotent

Post is not idempotent.


Difference between Web server and Application server?




           Web Server


      Application Server     

Manages and executes only web applications


 Manages and executes web applications , EJB Components and web enterprise applications 


Comes with only web container


Comes with web container ,EJB Container

Allows only Http Clients

Allows all types of java clients including Http Clients like Java App , AWT , Swing etc


Recognizes only war files as applications           

Recognizes WAR , JAR , EAR And RAR files as Applications.
  EAR = WAR + RAR


Gives less amount of middleware services

Gives more amount of middleware services (nearly 16)   


Examples : Tomcat , Resin , Jws , Pws     

WebLogic , WebSphere , JBoss , JRun , O10gAs         


Web Server implements only Servlet ,Jsp Api’s of J2EE Specification.

Application server implements all API’  



Can you explain Servlet Life Cycle methods ?


Servlet Life Cycle:
Life cycle diagram of servlet:


To perform operations related to these three events & to handle these event there are  3 life cycle methods.
   1.Public void init(-)  [Servlet object is just created.]
   
   2.Public void service (ServletRequest req, ServletResponse res)
                                [Servlet object is ready for request processing]

   3.public void destroy() [Servlet object is about to destroy.]

Life cycle methods of a servlet helps the programmer events that are raised on the servlet object.
Step 1:
                      init(-) is a one time execution method in the life cycle of servlet object. This method executes automatically when underlying web-container creates the servlet object. We place initialization logic in the init(-) method like creating JDBC connection object.

Step 2:
                   service(-,-) method is a repeatedly executing method for servlet object. This method executes automatically when servlet gets the request so we place request processing logic in this method.
If multiple requests are given to a servlet multiple times the service (-,-) method of that servlet executes.

Step 3:
             destroy()  is a one time execution life cycle method. This method executes automatically when servlet object is about to destroy. So we place un initialization logic in the destroy() method like closing JDBC connection.

Servlet Interview Questions-Part2


Servlet webapplication Architecture?


Why is Servlet so popular?   

 Because servlet  are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.


How can you say servlet is a single instance & multiple threads component?
             When you give multiple request to a java class acting as servlet, the web-server/applications server creates only one object of servlet but multiple threads will be started on that object representing multiple requests. Due to this server is called single instance & multiple threads based server side java component.
                          
Why Generic Servlet is abstract class ?         
 GenericServlet class implements Servlet interface and it gives definition of all the methods present in Servlet interface except service() method. service() method is abstract in Generic Servlet class, that's why Generic Servlet is an abstract class.

 Why HttpServlet is abstract class?
                   (OR)
 All methods in HttpServlet is concrete then why HttpServlet is abstract class?
we can declare a class as abstract even though the class  contains all concrete methods(with implementations). HttpServelt is also has all implemented methods  but they do nothing i.e Java People provided default implementation , that is not usefull. And also doGet() and doPost()  methods are implemented to return an error message  as  “ GET not supported, or POST not supported”. Due to cause of this the HttpServlet extending class  must need to override at least one of  HttpServlet class   method and there he need to write actual business logic.

What happens if I call destroy() method from service() method?
 Servlet object will not be destroyed & logic of destroy() method executes as a ordinary method logic.
Conclusion :
 When events are raised on servlet object then automatically life cycle methods will execute. And by calling life cycle methods events will not be raised on the servlet object.

What happens if I call init() method in the service() method?
 init() method executes as a ordinary java method but servlet object will not be created.

Can we call destroy() method inside the init() method is yes what will happen?
 Yes we can call like this but  if we did’t not override this method(destroy()) container will call the default destroy() method and nothing will happen . after calling this if any we have override default() method then the code written inside is executed.

What is Idempotent Behavior?
                        (OR)
       doPost() is idempotent nature or not ?
 When request  is submitted from form before completion of the request processing , if another request comes from same form and same browser window logic placed in doGet() method executes two times this behavior is called Idempotent Behavior. Idempotent Behavior means allowing double submission and this is a bad behavior and it has to be prevented. So better not to keep sensitive business logic like Credit Cards processing and other database operations in doGet() method.
 doPost() method is not idempotent so it does not allows double submit ions. so it is recommended to place sensitive business logic in doPost() method.

When Servlet gets First request then what will happen ?
                    (or)
Why First Request processing will take more time with compare to other requests?
 When servlet gets 1st request , all of following steps will execute ……
 Step 1.    Web container/web server loads servlet class from  WEB-INF/classes of   deployed web-application & creates object for it.
            Class c = class.forName(“yourservletname”);
            c.newInstance();
step 2 .     Zero Argument Constructor will execute.
Step 3.     Servletconfig object will be created for servlet object
Step 4.     init(-) method executes.
Step 5:     service (-,-) method executes & response goes to browser.
from next request onwords (second request onwords) the above "step 1 to  4 “ will not occur directly "step 5" step will be execute. That's why first request will take more time.

How to Develope Our Servlet As the Best Http Servlet?


Step 1: 
 Keep programmers initialization logic [like getting  DB  connection] by overriding public void init() method.
 If programmers initialization logic is placed by overriding public void init(servltconfig eg) make sure that you are calling super.init(eg) method from it .
Step 2:
 Instead of placing request processing logic in the service() method it is recommended to place request processing logic by overriding  doxxx() methods like doGet(),doPost() method. Because these are developed based on HTTP protocol and provides error messages .
Step 3:
Close All opened resources (Jdbc connections , File closing,network connections) in destroy().

What problem(s) does abstraction and encapsulation solve?

 Both abstraction and encapsulation solve same problem of complexity in different dimensions. Encapsulation exposes only the required details of an object to the caller by forbidding access to certain members, whereas an abstraction not only hides the implementation details, but also provides a basis for your application to grow and change over a period of time. For example, if you abstract out the make and model of a vehicle as class attributes as opposed to as individual classes like Toyota, ToyotaCamry, ToyotaCorolla, etc, you can easily incorporate new types of cars at runtime by creating a new car object with the relevant make and model as arguments as opposed to having to declare a new set of classes.

DataBase Interview Questions?

What do you understand by the terms clustered index and non-clustered index?
          When you create a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage space separate from the table data storage. Clustered and non-clustered indexes are stored as binary search tree (i.e. keep data sorted and has the average performance of O(log n) for delete, inserts, and search) structures with the leaf level nodes having the index key and it's row locator for a faster retrieval.

What is the difference between primary key and unique key?
    Both primary key and unique key enforce uniqueness of the column on which they are defined. But by default, a primary key creates a clustered index on the column, whereas a unique key creates a non clustered index by default. Another major difference is that, a primary key doesn't allow NULL values, but unique key allows a single NULL.

What are the pros and cons of an index?
PROS: If an index does not exist on a table, a table scan must be performed for each table referenced in a database query. The larger the table, the longer a table scan takes because a table scan requires each table row to be accessed sequentially. So, indexes can improve search performance, especially for the reporting requirements.

CONS: Excessive non-clustered indexes can consume additional storage space. Excessive non-clustered indexes can adversely impact performance of the INSERT, UPDATE, and DELETE statements as the indexes need to recreated after each of the above operation.So, it is essential to have a right balance based on the usage pattern.

What are the pros and cons of stored procedures?
PROS:pre-compiled and less network trips for faster performance,less susceptible to SQL injection attacks,more precise control over transactions and locking,can abstract complex data processing from application by acting as a facade layer.

CONS: There are chances of larger chunks of business logic and duplications creeping into stored procedures and causing maintenance issues. Writing and maintaining stored procedures is most often a specialized skill set that not all developers possess. This situation may introduce bottlenecks in the project development schedule.
  • Less portable.The stored procedures are specific to a particular database.
  • Scaling a database is much harder than scaling an application.
  • The application performance can be improved by caching the relevant data to reduce the network trips
when should stored procedures be used ?
Stored procedures are ideal when there is a complex piece of business logic that needs complex data logic to be performed involving a lot of database operations. If this logic is required in many different places, then store procedure makes even more sense. For example, batch jobs and complex report generation that performs lots of database operations.

when shouldn't stored procedures be used ?
When you are performing basic CRUD (Create, Read, Update, and Delete) operations. For example, in a Web application a user creates some data, read the created data, and then updates or deletes some of the created data. 

 How would you go about writing a stored procedure that needs to loop through a number of selected rows?
  You need to use a cursor. A cursor is basically a pointer to row by operation. For example, you can create a cursor by selecting a number of records into it. Then, you can fetch each row at a time and perform some operations like invoking another stored proc by passing the selected row value as an argument, etc. Once uou have looped through all the records, you need to close and deallocate the cursor. For example, the stored procedure below written in Sybase demonstrates the use of a cursor.

Drop the stored procedure if it already exists

IF OBJECT_ID('dbo.temp_sp') IS NOT NULL
BEGIN 
    DROP PROCEDURE dbo.temp_sp
IF OBJECT_ID('dbo.temp_sp') IS NOT NULL
PRINT '<<< FAILED DROPPING PROCEDURE dbo.temp_sp >>>'
ELSE
PRINT '<<< DROPPED PROCEDURE dbo.temp_sp >>>'
END

 Create the stored procedure that uses cursor
 
create proc temp_sp  as DECLARE @ADVISERID char(10) DECLARE advisers_cur cursor  for select adviser_id FROM tbl_advisers where adviser_id like 'Z%' -- select adviser_ids starting with 'Z' for read only 
open advisers_cur -- open the cursor
FETCH advisers_cur INTO @ADVISERID -- store value(s) from the cursor into declared variables
--@@sqlstatus is a sybase implcit variable that returns success/failure status of previous statement execution
WHILE (@@sqlstatus = 0)
BEGIN
SELECT @ADVISERID -- select the adviser_id stored into @ADVISERID
FETCH advisers_cur INTO @ADVISERID --store value(s) from the cursor into declared variables
END
close advisers_cur
deallocate cursor advisers_cur
go

Execute the stored procedure that uses a cursor

exec mydatabase..temp_sp

Why should you deallocate the cursors?
    You need deallocate the cursor to clear the memory space occupied by the cursor. This will enable the cleared space to be availble for other use.

 How would you go about copying bulk data in and out of a database? 
  The process is known as bulk copy, and the tools used for this are database specific. For example, in Sybase and SQLServer use a utility called "bcp", which allows you to export bulk data into comma delimited files, and then import the data in csv or any other delimited formats back into different database or table. In Oracle database, you achieve this via the SQLLoader. The DB2 database has IMPORT and LOAD command to achieve the same.

 What are triggers? what are the different types of triggers?
   Triggers are stored procedures that are stored in the database and implicitly run, or fired, when something like INSERT, UPDATE , or DELETE happens to that table. There are 3 types of DML triggers that happens before or after events like INSERT, UPDATE, or DELETE. There could be other database specific triggers.

When to not use a trigger, and when is it appropriate to use a trigger?
The database triggers need to be used very judiciously as they are executed every time an event like insert, update or delete occur. Don't use a trigger where database constraints like unique constraint, not null, primary key, check constraints, etc can be used to check for data validity.
triggers are recursive.

Where to use a trigger?
Maintaining complex integrity constraints (referential integrity) or business rules where other types of constraints cannot be used. Because triggers are executed as part of the SQL statement (and its containing transaction) causing the row change event, and because the trigger code has direct access to the changed row, you could in theory use them to correct or reject invalid data.
Auditing information in a table by recording the changes. Some tables are required to be audited as part of the non-functional requirement for changes.
Automatically signaling other programs that action needs to take place when changes are made to a table.
Collecting and maintaining aggregate or statistical data. 

 If one of your goals is to reduce network loads, how will you about achieving it?
you can use materialized views to distribute your load from a master site to other regional sites. Instead of the entire company accessing a single database server, user load is distributed across multiple database servers with the help of multi-tier materialized views. This enables you to distribute the load to materialized view sites instead of master sites. To decrease the amount of data that is replicated, a materialized view can be a subset of a master table or master materialized view. Write stored procedures to minimize network round trips.

Carefully crafting your SQL to return only required data. For example Don't do select * from tbl_mytable. Instead, specify the columns you are interested in. For example, select firstname, surname from tbl_mytable.

You can set the fetch size to an appropriate value to get the right balance between data size and number of network trips made. Q. What are the other uses of materialized views?
Materialized view is one of the key SQL tuning approaches to improve performance by allowing you to pre-join complex views and pre-compute summaries for super-fast response time.

Materialized views are schema objects that can be used to summarize, precompute, replicate, and distribute data. E.g. to construct a data warehouse, reporting, etc. A materialized view can be either read-only, updatable, or writable. Users cannot perform data manipulation language (DML) statements on read-only materialized views, but they can perform DML on updatable and writable materialized views.

A materialized view provides indirect access to table data by storing the results of a query in a separate schema object. Unlike an ordinary view, which does not take up any storage space or contain any data. You can define a materialized view on a base table, partitioned table or view and you can define indexes on a materialized view.

 If you are working with a legacy application, and some of the database tables are not properly designed with the appropriate constraints, how will you go about rectifying the situation?
  One possible solution is to write triggers to perform the appropriate validation. Here is an example of an insert trigger.
CREATE TRIGGER TableA_itrig
ON TableA FOR INSERT
AS
BEGIN
IF @@rowcount = 0
RETURN
IF NOT EXISTS
(
SELECT *
FROM inserted ins, TableB ol
WHERE ins.code = ol.code
)
BEGIN
RAISERROR 20001, "The associated object is not found"
ROLLBACK TRAN
RETURN
END
END

If you are working on a new application that requires stringent auditing requirements, how would you go about achieving it?
Since it is a new application, there are a number of options as listed below. The application is designed from the beginning so that all changes are logged either synchronously or asynchronously. Asynchronously means publishing the auditing messages to a queue or topic, and a separate process will receive these messages and write a database or flat file. All data changes go through a data access layer of the application which logs all changes. The database is constructed in such a way that logging information is included in each table, perhaps set via a trigger. This approach may adversely impact performance when inserts and updates are very frequent.

What if you have to work with an existing legacy application?
 Use triggers.

JavaeEE Framework Questions?

What are the benefits of the asynchronous processing support that was introduced in Servlet 3.0 in JEE 6?
1. If you are building an online chess game or a chat application, the client browser needs to be periodically refreshed to reflect the changes. This used to be achieved via a technique known as the server-polling (aka client pull or client refresh). You can use the HTML tag for polling the server. This tag tells the client it must refresh the page after a number of seconds. 

The URL newPage.html will be refreshed every 10 seconds. This approach has the downside of wasting network bandwidth and server resources. With the introduction of this asynchronous support, the data can be sent via the mechanism known as the server push as opposed to server polling. So, the client waits for the server to push the updates as opposed to frequently polling the server.

2. The Ajax calls are integral part of any web development as it provides richer user experience. This also means that with Ajax, the clients (i.e. browsers) interact more frequently with the server compared to the page-by-page request model. If an Ajax request needs to tap into server side calls that are very time consuming (e.g. report generation), the synchronous processing of these Ajax requests can degrade the overall performance of the application because these threads will be blocked as the servers generally use a thread pool with finite number of threads to service concurrent requests. The asynchronous processing will allow these time consuming requests to be throttled via a queue, and the same thread(s) to be recycled to process queued requests without having to chew up the other threads from the server thread-pool. This approach can be used for non Ajax requests as well.

Note: In JEE 6, The EJB 3.1 can also specify a Session Bean to be asynchronous.


 What are benefits of web fragements introduced in Servelt 3.0 spec? 

       Web applications use frameworks like JSF, Struts, Spring MVC, Tapestry, etc. These frameworks normally bootsrap (i.e register) via the web.xml file using the and tags. For example

The web.xml file
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

If a particular application uses more than one framework, the above approach is not modular as you will have to bootstrap all the frameworks within the same web.xml file, making it large and difficult to isolate framework specific descriptors. The Servlet 3.0 specification addresses this issue by introducing web fragments. A web fragment can be considered as one of the segment of the whole web.xml and it can be thought of as one or more web fragments constituting a single web.xml file. The fragment files are stored under /META-INF/web-fragment.xml, and it is the responsibility of the container to scan the fragement files during the server start-up.
Note: The Servlet 3.0 specification also provides enhanced pluggability by providing an option to add servlets, filters, servlet mappings and filter mappings during the run time.


 What do you understand by the term "Web profile" in Java EE 6?

   Java EE 6 introduces the concept of profiles as a way to slimming the footprint of the Java EE platform and better target it for specific audiences. Profiles are configurations of the Java EE platform that are designed for specific classes of applications. For example, the required elements for a Web profile are
  • Java EE 6 (JSR-316)
  • Common Annotations for Java Platform 1.1 (JSR-250)
  • Dependency Injection for Java 1.0 (JSR-330)
  • Contexts and Dependency Injection for Java EE platform 1.0 (JSR-299)
  • Servlet 3.0 (JSR-315)
  • JavaServer Pages (JSP) 2.2 (JSR-245)
  • Expression Language (EL) 2.2 (JSR-245)
  • Debugging Support for Other Languages 1.0 (JSR-45)
  • Standard Tag Library for JavaServer Pages (JSTL) 1.2 (JSR-52)
  • JavaServer Faces (JSF) 2.0 (JSR-314)
  • Enterprise JavaBeans (EJB) 3.1 Lite (JSR-318)
  • Java Transaction API (JTA) 1.1 (JSR-907)
  • Java Persistence API (JPA) 2.0 (JSR-317)
  • Bean Validation 1.0 (JSR-303)
  • Managed Beans 1.0 (JSR-316)
  • Interceptors 1.1 (JSR-318)
The JEE 6 has also introduced the concept known as "pruning" to manage complexities. This is similar to the concept introduced in Java SE 6. Pruning is performed as a multistep process where a candidate is declared in one release but may be relegated to an optional component in the next release, depending on community reaction. For example, JAX-RPC will be pruned and replaced by JAX-WS. However, if Java EE application server vendors do include a pruned technology, they must do so in a compatible way, such that existing applications will keep running. The profiles and pruning are debatable topics and only time will tell if they work or not.

MultiThreading Interview Questions


What is the difference between processes and threads? 
           A process is an execution of a program but a thread is a single execution sequence within the process. A process can contain multiple threads. A thread is sometimes called a lightweight process.



A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space. This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.



 Explain different ways of creating a thread?
     Threads can be used by either


1.Extending the Thread class.

class Counter extends Thread {

//method where the thread execution will start 

public void run(){
//logic to execute in a thread 
}
    //let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new Counter();
Thread t2 = new Counter();
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method. 
}



2.Implementing the Runnable interface.

class Counter extends Base implements Runnable{
    //method where the thread execution will start 
public void run(){
//logic to execute in a thread 
}
    //let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new Counter());
Thread t2 = new Thread(new Counter());
t1.start(); //start the first thread. This calls the run() method.
t2.start(); //this starts the 2nd thread. This calls the run() method. 
}


 Which one would you prefer and why? 
        The Runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the threads are started in each of the different cases as shown in the code sample. In an OO approach you should only extend a class when you want to make it different from it’s superclass, and change it’s behavior. By implementing a Runnable interface instead of extending the Thread class, you are telling to the user that the class Counter that an object of type Counter will run as a thread. 



Briefly explain high-level thread states? 





Runnable — waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.
Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently.
Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
Blocked on synchronization: Will move to Runnable when a lock is acquired.
Dead: The thread is finished working.



 What is the difference between yield and sleeping? What is the difference between the methods sleep( ) and wait( )?       When a task invokes yield( ), it changes from running state to runnable state. When a task invokes sleep (), it changes from running state to waiting/sleeping state.



The method wait(1000), causes the current thread to sleep up to one second. A thread could sleep less than 1 second if it receives the notify( ) or notifyAll( ) method call. The call to sleep(1000) causes the current thread to sleep for 1 second.



How does thread synchronization occurs inside a monitor? What levels of synchronization can you apply? What is the difference between synchronized method and synchronized block?     In Java programming, each object has a lock. A thread can acquire the lock for an object by using the synchronized keyword. The synchronized keyword can be applied in method level or block level of code. Often using a lock on a method level is too coarse. Why lock up a piece of code that does not access any shared resources by locking up an entire method. Since each object has a lock, dummy objects can be created to implement block level synchronization. The block level is more efficient because it does not lock the whole method. 





The JVM uses locks in conjunction with monitors. A monitor is basically a guardian who watches over a sequence of synchronized code and making sure only one thread at a time executes a synchronized piece of code. Each monitor is associated with an object reference. When a thread arrives at the first instruction in a block of code it must obtain a lock on the referenced object. The thread is not allowed to execute the code until it obtains the lock. Once it has obtained the lock, the thread enters the block of protected code. When the thread leaves the block, no matter how it leaves the block, it releases the lock on the associated object. 



 Why synchronization is important? 
        Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often causes dirty data and leads to significant errors. The disadvantage of synchronization is that it can cause deadlocks when two threads are waiting on each other to do something. Also synchronized code has the overhead of acquiring lock, which can adversely affect the performance. 

What is a ThreadLocal class? 
         ThreadLocal is a handy class for simplifying development of thread-safe concurrent programs by making the object stored in this class not sharable between threads. ThreadLocal class encapsulates non-thread-safe classes to be safely used in a multi-threaded environment and also allows you to create per-thread-singleton. 


What is a daemon thread? 
           Daemon threads are sometimes called "service" or “background” threads. These are threads that normally run at a low priority and provide a basic service to a program when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. The JVM exits whenever all non-daemon threads have completed, which means that all daemon threads are automatically stopped. To make a thread as a daemon thread in Java
myThread.setDaemon(true);
The JVM always has a main thread as default. The main thread is always non-daemon. The user threads are created from the main thread, and by default they are non-daemon. If you want to make a user created thread to be daemon (i.e. stops when the main thread stops), use the setDaemon(true) as shown above.
 How can threads communicate with each other? How would you implement a producer (one thread) and a consumer (another thread) passing data (via stack)?               The wait( ), notify (), and notifyAll( ) methods are used to provide an efficient way for threads to communicate with each other. This communication solves the ‘consumer-producer problem’. This problem occurs when the producer thread is completing work that the other thread (consumer thread) will use. 


Example: If you imagine an application in which one thread (the producer) writes data to a file while a second thread (the consumer) reads data from the same file. In this example the concurrent threads share the same resource file. Because these threads share the common resource file they should be synchronized. Also these two threads should communicate with each other because the consumer thread, which reads the file, should wait until the producer thread, which writes data to the file and notifies the consumer thread that it has completed its writing operation.


Let’s look at a sample code where count is a shared resource. The consumer thread will wait inside the consume( ) method on the producer thread, until the producer thread increments the count inside the produce( ) method and subsequently notifies the consumer thread. Once it has been notified, the consumer thread waiting inside the consume( ) method will give up its waiting state and completes its method by consuming the count (i.e. decrementing the count).

Class ConsumerProducer{
 Private int count;
public synchronized void consume();
    while(count==0){
try{
wait()
}
catch(InterruptedException ie){
        }
}
count--;//consumed
}
private synchronized void produce(){
count++;
notify();//notify the consumer that count has been incremented;
}
}


Why wait, notify, and notifyall methods are defined in the Object class, and not in the Thread class?
      Every Java Object has a monitor associated with it. The threads using that object can lock or unlock the monitor associated with the object.Wait and notify/notifyAll methods are responsible for acquiring and relinquishing the lock associated with the particular object. Calling wait causes the current thread to wait to acquire the lock of the Object, and calling notify/notifyAll relinquishes the lock and notify the threads waiting for that lock.


What does join() method do? 
       t.join( ) allows the current thread to wait indefinitely until thread “t” is finished. t.join (5000) allows the current thread to wait for thread “t” to finish but does not wait longer than 5 seconds.

try {
t.join(5000); //current thread waits for thread “t” to complete but does not wait more than 5 sec
if(t.isAlive()){
//timeout occurred. Thread “t” has not finished
}
else {
//thread “t” has finished
}


For example, say you need to spawn multiple threads to do the work, and continue to the next step only after all of them have completed, you will need to tell the main thread to wait. this is done with thread.join() method. Here is the RunnableTask. The task her is nothing but sleeping for 10 seconds as if some task is being performed. It also prints the thread name and timestamp as to when this task started 

import java.util.Date;
public class RunnableTask implements Runnable {
 @Override
public void run() {
Thread thread = Thread.currentThread();
System.out.println(thread.getName() + " at " + new Date());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}     }      }


     The taskmanager manages the tasks by spawing multiple user threads from the main thread. The main thread is always created by default. The user threads 1-3 are run sequentially, i.e. thread-2 starts only after thread-1 completes, and so on. The user threads 4-6 start and executes concurrently.

public class TaskManager {

public static void main(String[] args) throws InterruptedException {
  RunnableTask task = new RunnableTask();

//threads 1-3 are run sequentially
Thread thread1 = new Thread(task, "Thread-1");
Thread thread2 = new Thread(task, "Thread-2");
Thread thread3 = new Thread(task, "Thread-3");


thread1.start();    //invokes run() on RunnableTask
thread1.join();     // main thread blocks (for 10 seconds)
thread2.start();    //invokes run() on RunnableTask
thread2.join();    // main thread blocks (for 10 seconds)
thread3.start();   //invokes run() on RunnableTask
thread3.join();   // main thread blocks (for 10 seconds)



Thread thread4 = new Thread(task, "Thread-4");
Thread thread5 = new Thread(task, "Thread-5");
Thread thread6 = new Thread(task, "Thread-6");


thread4.start();    //invokes run() on RunnableTask
thread5.start();    //invokes run() on RunnableTask
thread6.start();   //invokes run() on RunnableTask
}
}
Notice the times of the output. There is a 10 second difference bewteen threads 1-3. But Threads 4-6 started pretty much the same time.
 Thread-1 at Fri Mar 02 16:59:22 EST 2012
Thread-2 at Fri Mar 02 16:59:32 EST 2012
Thread-3 at Fri Mar 02 16:59:42 EST 2012
Thread-4 at Fri Mar 02 16:59:47 EST 2012
Thread-6 at Fri Mar 02 16:59:47 EST 2012
Thread-5 at Fri Mar 02 16:59:47 EST 2012



 If 2 different threads hit 2 different synchronized methods in an object at the same time will they both continue?          No. Only one thread can acquire the lock in a synchronized method of an object. Each object has a synchronization lock. No two synchronized methods within an object can run at the same time. One synchronized method should wait for the other synchronized method to release the lock. This is demonstrated here with method level lock. Same concept is applicable for block level locks as well. 



 Explain threads blocking on I/O? 
     Occasionally threads have to block on conditions other than object locks. I/O is the best example of this. Threads block on I/O (i.e. enters the waiting state) so that other threads may execute while the I/O operation is performed. When threads are blocked (say due to time consuming reads or writes) on an I/O call inside an object’s synchronized method and also if the other methods of the object are also synchronized then the object is essentially frozen while the thread is blocked. Be sure to not synchronize code that makes blocking calls, or make sure that a non-synchronized method exists on an object with synchronized blocking code. Although this technique requires some care to ensure that the resulting code is still thread safe, it allows objects to be responsive to other threads when a thread holding its locks is blocked.


 If you have a circular reference of objects, but you no longer reference it from an execution thread, will this object be a potential candidate for garbage collection?         Yes. Refer diagram below.





Which of the following is true?

a) wait( ),notify( ),notifyall( ) are defined as final & can be called only from with in a synchronized method
b) Among wait( ),notify( ),notifyall( ) the wait() method only throws IOException
c) wait( ),notify( ),notifyall( ) & sleep () are methods of object class

 a and b. The c is wrong because the sleep method is a member of the Thread class.The other methods are members of the Object class.


What are some of the threads related problems abd what causes those problems?
  DeadLock, LiveLock, and Starvation.



Deadlock occurs when two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on the same resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other resource to release the lock, unless one of the user processes is terminated. The thread deadlock can occur in conditions such as:
1.two threads calling Thread.join() on each other.
2.two threads use nested synchronized blocks to lock two objects and blocks lock the same objects in different order.

Starvation and livelock are much less common a problem than deadlock, and it occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available.


The thread livelock can occur in conditions such as:
1. all the threads in a program are stuck in infinite loops.
2. all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify( ) or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.



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. The thread starvation can occur in conditions such as:
1.one thread cannot access the CPU because one or more other threads are monopolizing the CPU.
setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time. 

  

What happens if you call the run( ) method directly instead of via the start method?
      Calling run( ) method directly just executes the code synchronously (in the same thread), just like a normal method call. By calling the start( ) method, it starts the execution of the new thread and calls the run( ) method. The start() method returns immediately and the new thread normally continues until the run( ) method returns. So, don't make the mistake of calling the run( ) method directly.