DISHA NIRDESHAN

Enlightens your career

Tuesday, June 28, 2011

Questions on Threads


Questions on Threads:

 

Q: What is Thread ?

A :  Thread is a program's path of execution.

Every thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread, and is a daemon thread if and only if the creating thread is a daemon.

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs:

  • The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place.
  • All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.

There are two ways to create a new thread of execution. One is to declare a class to be a subclass of Thread. This subclass should override the run method of class Thread. An instance of the subclass can then be allocated and started. For example, a thread that computes primes larger than a stated value could be written as follows:

 

     class PrimeThread extends Thread {

         long minPrime;

         PrimeThread(long minPrime) {

             this.minPrime = minPrime;

         }

 

         public void run() {

             // compute primes larger than minPrime

              . . .

         }

     }

 

 

The following code would then create a thread and start it running:

     PrimeThread p = new PrimeThread(143);

     p.start();

 

The other way to create a thread is to declare a class that implements the Runnable interface. That class then implements the run method. An instance of the class can then be allocated, passed as an argument when creating Thread, and started. The same example in this other style looks like the following:

 

     class PrimeRun implements Runnable {

         long minPrime;

         PrimeRun(long minPrime) {

             this.minPrime = minPrime;

         }

 

         public void run() {

             // compute primes larger than minPrime

              . . .

         }

     }

 

 

The following code would then create a thread and start it running:

     PrimeRun p = new PrimeRun(143);

     new Thread(p).start();

 

Every thread has a name for identification purposes. More than one thread may have the same name. If a name is not specified when a thread is created, a new name is generated for it.

 

 Q  : What are the advantages or usage of threads?

A :

Ø Threads support concurrent operations.

Ø Threads often result in simpler programs.

Ø  Threads provide a high degree of control.

Ø Threaded applications exploit parallelism.

 

Q : What are the two ways of creating thread?

A There are two ways to create a new thread.

1)Extend the Thread class and override the run() method in your class. Create an instance of the subclass and invoke the start() method on it, which will create a new thread of execution. e.g.

public class NewThread extends Thread{

public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String         ] args){
NewThread c = new NewThread();
c.start();
}

}

2)Implements the Runnable interface.The class will have to implement the run() method in the Runnable interface. Create an instance of this class. Pass the reference of this instance to the Thread constructor a new thread of execution will be created. e.g. class

public class NewThread implements Runnable{

public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String         ] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}

}


Q:What are the different states of a thread's lifecycle?

A: The different states of threads are as follows:

 

1) New – When a thread is instantiated it is in New state until the start() method is called on the thread instance. In this state the thread is not considered to be alive.


2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.

3) Running – When the thread scheduler picks up the thread from the Runnable thread's pool, the thread starts running and the thread is said to be in Running state.

 4) Waiting/Blocked/Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i/o resource so blocked.


5)      Dead – When the thread finishes its execution i.e. the run() method execution completes, it is said to be in dead state. A dead state can not be started again. If a start() method is invoked on a dead thread a runtime exception will occur.

            

Q: What is use of synchronized keyword?

Ans) 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 a = 0;

 

    public synchronized void increment() {

        a++;

    }

 

    public synchronized void decrement() {

        a--;

    }

 

    public synchronized int value() {

        return a;

    }

}

If count is an instance of Synchronized Counter, 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.

Note:  constructors cannot be synchronized — using the synchronized keyword with a constructor is a syntax error. Synchronizing constructors doesn't make sense, because only the thread that creates an object should have access to it while it is being constructed.

 

Q  What all constructors are present in the Thread class?

A:

Ø Thread()

Ø  Thread(Runnable target)

Ø Thread(Runnable target, String name)

Ø Thread(String name)

Q : Can the variables or classes be Synchronized?

A : No. Only methods can be synchronized.

 

 

Q: What is the difference when the synchronized keyword is applied to a static method or to a non static method?


A: When Synchronization is applied on a static Member or a static block, the lock is performed on the Class and not on the Object, while in the case of a Non-static block/member, lock is applied on the Object and not on class.         Trail 2: There is a class called Class in Java whose object is associated with the object(s) of your class. All the static members declared in your class will have reference in this class(Class). As long as your class exists in memory this object of Class is also present. Thats how even if you create multiple objects of your class only one Class object is present and all your objects are linked to this Class object. Even though one of your object is Garbage Collected after some time, this object of Class is not GCed untill all the objects associated with it are Garbage Collected.


This means that whenever you call a "static synchronized" block, JVM locks access to this Class object and not any of your objects. Your client can till access the non-static members of your objects.

 

 Q  How many locks does an object have?

Ans) Each object has only one lock.


Q : Can a class have both Synchronized and non-synchronized methods?

A Yes a class can have both synchronized and non-synchronized methods.

 

 

Q12) What happens if a start method is not invoked and the run method is directly invoked?

A:

 After a thread is started, via its start() method or that of the Thread class, the JVMinvokes the thread's run() method when the thread is initially executed.

If a thread has been instantiated but not started its is said to be in new state. Unless until a start() method is invoked on the instance of the thread, it will not said to be alive. If you do not call a start() method on the newly created thread instance thread is not considered to be alive. If the start() method is not invoked and the run() method is directly called on the Thread instance, the code inside the run() method will not run in a separate new thread but it will start running in the existing thread.

Q What happens when start() is called?

A:  

Whenever a start is called the state of thread changes from new to runnable. When the thread gets chance to execute its target run() method starts to run.

 

Q If code running is a thread creates a new thread what will be the initial priority of the newly created thread?

A:  

It creates a new thread object and  the priority of the new thread is set equal to the priority of the thread which has created it.


Q :  When jvm starts up, which thread will be started up first?

A : When jvm starts up the thread executing main method is started.

 

Q :  What are the daemon threads?

A:

1.      A daemon thread is a background thread.

2.     It is subordinate to the thread that creates it.

3.     When the thread that created the daemon thread ends, the daemon thread dies with it.

Example : Garbage Collector


Q What is a volatile keyword?

A:

Ø  volatile is used to indicate that a variable's value will be modified by different threads.

Ø Declaring a volatile Java variable means:

The value of this variable will never be cached thread-locally: all reads and  writes will go straight to "main memory";

Access to the variable acts as though it is enclosed in a synchronized block, synchronized on itself.


0 comments :