Tuesday, 14 February 2012

Is there a separate stack for each thread in Java? | Java Threads


Yes. Every thread maintains its own separate stack, called Runtime Stack but they share the same memory. Elements of the stack are the method invocations, called activation records or stack frame. The activation record contains pertinent information about a method like local variables.

How would you implement a thread pool? | Java Threads


public class ThreadPool implements ThreadPoolInt
This class is an generic implementation of a thread pool, which takes the following input
a) Size of the pool to be constructed
b) Name of the class which implements Runnable and constructs a thread pool with active threads that are waiting for activation. Once the threads have finished processing they come back and wait once again in the pool.

  This thread pool engine can be locked i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be locked. Locking ensures that no new threads are issued by the engine. However, the currently executing threads are allowed to continue till they come back to the passivePool.

What state does a thread enter when it terminates its processing? | Java Threads


When a thread terminates its processing, it enters the dead state.

What is an objects lock and which objects have locks? | Java Threads


An objects lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the objects lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

When you will synchronize a piece of your code? | Java Threads


When you expect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption, then they are placed in a synchronized construct or a synchronized method.

Why would you use a synchronized block vs. synchronized method? | Java Threads


Synchronized blocks place locks for shorter periods than synchronized methods.

What do you understand by Synchronization? | Java Threads


With respect to multithreading, Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. Synchronization prevents such type of data corruption which may otherwise lead to dirty reads and significant errors.
E.g. synchronizing a function:
public synchronized void Method1 () 
{
// method code.
}
E.g. synchronizing a block of code inside a function:
public Method2 ()
{
synchronized (this) 
{
// synchronized code here.
}