Search the Web for JAVA Answers:

Search the Web for more JAVA Answers:
Hint: Press Ctrl+ to increase the font size of this blog and Ctrl- to decrease the font size of this blog.

Java Thread Answers


1. What is a process?
Answer: A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.
--------------------------------------------------------------------------------
2. What are threads?
Answers: Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process. Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but  problematic communications.
--------------------------------------------------------------------------------
3. Describe the Life of a Thread.
Answer: Thread objects have a distinct life cycle with four basic states: new, runnable, blocked, and dead .



New state – After the creation of a Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive.
     
Runnable (Ready-to-run) state – A thread starts its life from the runnable state. A thread first enters the runnable state after the invoking of the start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. 
     
Running state – A thread is in running state that means the thread is currently executing. There are several ways to enter in runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool.

Blocked - A thread can enter in this state because of waiting the resources that are hold by another thread.
     
Dead state – A thread can be considered dead when its run() method completes. If any thread comes on this state that means it cannot ever run again.





-------------------------------------------------------------------------------
4. What is the difference between yielding and sleeping?
Answer: When a task invokes its yield() method, it returns to the ready state whereas when a task invokes its sleep() method, it returns to the waiting state.
-------------------------------------------------------------------------------
5. When a thread blocks on I/O, what state does it enter?
Answer: A thread enters the waiting(blocked) state when it blocks on I/O.
-------------------------------------------------------------------------------
6. When a thread is created and started, what is its initial state? 
Answer: A thread is in the ready state after it has been created and started.
-----------------------------------------------------------------------------
7. What invokes a thread's run() method?
Answer: After a thread is started, via its start() method or that of the Thread class, the JVM invokes the thread's run() method when the thread is initially executed.
----------------------------------------------------------------------------------
8. What method is invoked to cause an object to begin executing as a separate thread?
Answer: The start() method of the Thread class is invoked to cause an object to begin executing as a separate thread.
--------------------------------------------------------------------------------
9. What is the purpose of the wait(), notify(), and notifyAll() methods?
Answer: The wait(),notify(), and notifyAll() methods are used to provide an efficient way for threads to wait for a shared resource. When a thread executes an object's wait() method, it enters the waiting state. It only enters the ready state after another thread invokes the object's notify() or notifyAll() methods.
--------------------------------------------------------------------------------
10. What are the high-level thread states? 
Answer:  The high-level thread states are ready, running, waiting, and dead .
--------------------------------------------------------------------------------
11. What happens when a thread cannot acquire a lock on an object? 
Answer:  If a thread attempts to execute a synchronized method or synchronized statement and is unable to acquire an object's lock, it enters the waiting state until the lock becomes available.
----------------------------------------------------------------------------------
12. How does multithreading take place on a computer with a single CPU?
Answer: The operating system's task scheduler allocates execution time to multiple tasks. By quickly switching between executing tasks, it creates the impression that tasks execute sequentially.
------------------------------------------------------------------------------
13. What happens when you invoke a thread's interrupt method while it is sleeping or waiting?
Answer:  When a task's interrupt() method is executed, the task enters the ready state. The next time the task enters the running state, an InterruptedException is thrown.
--------------------------------------------------------------------------------
14. What are three ways in which a thread can enter the waiting state? 
Answer: A thread can enter the waiting state by invoking its sleep() method, by blocking on I/O, by unsuccessfully attempting to acquire an object's lock, or by invoking an object's wait() method. It can also enter the waiting state by invoking its (now deprecated) suspend() method.
--------------------------------------------------------------------------------
15. What method must be implemented by all threads? 
Answer: All tasks must implement the run() method, whether they are a subclass of Thread or implement the Runnable interface.
--------------------------------------------------------------------------------
16.  What are the two basic ways in which classes that can be run as threads may be defined? 
Answer: A thread class may be declared as a subclass of Thread, or it may implement the Runnable interface.
--------------------------------------------------------------------------------
Why “implements Runnable” is Preferred over “extends Thread”?
When you extend Thread class, you can’t extend any other class which you require. (As you know, Java does not allow inheriting more than one class). When you implement Runnable, you can save a space for your class to extend any other class in future or now.

However, the significant difference is:

When you extends Thread class, each of your thread creates unique object and associate with it. When you implements Runnable, it shares the same object to multiple threads.
----------------------------------------------------------------------------------
17. If there are 20 threads waiting in the waiting pool with same priority, how can you invoke 15th thread from the waiting pool?
Answer: Its not possible do call a particular thread. The methods notify() will call threads from waiting pool, but there is no guaranty which thread is invoked. The method notifyAll() method puts all the waiting threads from the waiting pool in ready state.
----------------------------------------------------------------------------------
18. Explain the concept of Synchronization.
Answer: Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. The tool needed to prevent these errors is synchronization.

The Java programming language provides two basic synchronization idioms: synchronized methods and synchronized statements.

To make a method synchronized, simply add the synchronized keyword to its declaration:
public class SynchronizedCounter
{
    private int c = 0;
    public synchronized void increment()
    {
        c++;
     }

    public synchronized void decrement()
   {
        c--;
    }

    public synchronized int value()
   {
        return c;
    }
}

If count is an instance of class SynchronizedCounter, then making these methods synchronized has two effects:
- First, it is not possible for two invocations of synchronized methods on the same object to interleave. When one thread is executing a synchronized method for an object, all other threads that invoke synchronized methods for the same object block (suspend execution) until the first thread is done with the object.
- Second, when a synchronized method exits, it automatically establishes a happens-before relationship with any subsequent invocation of a synchronized method for the same object. This guarantees that changes to the state of the object are visible to all threads.

Synchronized Statements:
Another way to create synchronized code is with synchronized statements. Unlike synchronized methods, synchronized statements must specify the object that provides the intrinsic lock:

public void addName(String name)
{
    synchronized(this)
   {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

In this example, the addName method needs to synchronize changes to lastName and nameCount, but also needs to avoid synchronizing invocations of other objects' methods.
-------------------------------------------------------------------------------
19. What is a deadlock?
Answer: Deadlock describes a situation where two or more threads are blocked forever, waiting for each other.
Here's an example: Alphonse and Gaston are friends, and great believers in courtesy. A strict rule of courtesy is that when you bow to a friend, you must remain bowed until your friend has a chance to return the bow. Unfortunately, this rule does not account for the possibility that two friends might bow to each other at the same time.
-------------------------------------------------------------------------------
20. What is starvation?
Answer: 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.
-------------------------------------------------------------------------------
21. Explain Livelock.
Answer: A thread often acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. As with deadlock, livelocked threads are unable to make further progress. However, the threads are not blocked — they are simply too busy responding to each other to resume work.
This is comparable to two people attempting to pass each other in a corridor: Jack moves to his left to let Jill pass, while Jill moves to her right to let Jack pass. Seeing that they are still blocking each other, Jack moves to his right, while Gaston moves to her left. They still block each other!
-------------------------------------------------------------------------------
22. What is a daemon thread?
Answer: Daemon threads are service providers for other threads running in the same process as the daemon thread. When the only remaining threads in a process are daemon threads, the interpreter exits. This is because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service. An example would be a mail daemon. When a mail message is received by a mail server it generally needs to be forwarded on to another machine. One way to do this is to have a daemon check for mail every so often and cause the mail to be forwarded.
-------------------------------------------------------------------------------
23. Can you explain the difference between green threads and native threads?
Answer: Green threads is thread mechanism implemented in JVM itself. It is blind and can run on any Operating System, so actually all threads are run in one native thread and scheduling is up to JVM. This is disadvantageously for SMP systems, since only one processor can serve Java application.


Native threads is a mechanism based on the Operating System threading mechanism. This allows us to use features of hardware and the Operating System. For example,there is IBM's JDK for AIX that supports native threads. The perfomance of applications can be highly improved by this.
-------------------------------------------------------------------------------
24. I have created a program with a main method that instantiates and starts three threads, the first two of which are daemons. Why daemons does die when normal thread die?
Answer: Because of nature of daemon threads. They are alive if there exists atleast one "normal user" thread. Otherwise they die immediately!
-------------------------------------------------------------------------------
25. When will a Thread Object be garbage collected?
Answer: Since threads are also Objects, it will only be garbage collected when the reference count is zero.

Why? Think that if the thread is useless when it enters "dead" state, why not garbage collect it?
That's because the thread object itself may contain some other useful information even the thread dead, e.g. the result of the execution of the thread. Thus, it is not sensible to do garbage collect when the reference count is not zero.
-------------------------------------------------------------------------------
26. What happens when you call yield() on a thread?
Answer: Causes the currently executing thread object to temporarily pause and allow other threads to execute.