Showing posts with label Multithreading. Show all posts
Showing posts with label Multithreading. Show all posts

Sunday, October 11, 2009

Why wait(),notify() and notifyAll() in the Object class?


Why wait(), notify() and notifyAll() methods have been defined in the Object class?

Java concurrency model uses locks to implement mutually exclusive access to objects in a multi-threaded environment and locks are associated with every object in Java (of type 'Object'), not only with Threads.


wait
, notify/notifyAll methods are used by threads to communicate with each other while trying to access a common object. Putting it differently, objects become a medium via which threads communicate with each other. For example: suppose there is a 'telephone' object, which at one point of time can be used by only one thread. Like every other object in Java, 'telephone' object would also have an intrinsic lock (monitor) associated with it which at one point of time can be acquired by only one thread. Suppose the 'telephone' object requires activation before it can be used and suppose only a few admin threads can activate the 'telephone' object.


As soon as a thread needs access to the 'telephone' object, it checks if the lock on that 'telephone' object is available or not, if yes, it acquires that and checks if the 'telephone' is active or not. If yes, it starts using it otherwise it calls 'wait()' on the telephone object which effectively releases the monitor of the 'telephone' object (eventually to be acquired by one of the admin threads for its activation) and puts the requester thread into the wait-set of the 'telephone' object. The requester thread goes into WAITING state. The way every object in Java has an intrinsic lock associated with it, it has an intrinsic wait-set associated with it as well.


Every other non-admin requester thread goes through the same process as discussed above till one of the admin threads acquire lock on the 'telephone' object and eventually activates it and subsequently calls 'notify()' or 'notifyAll()' on the 'telephone' object. 'notify()' will simply pick one of the threads from the wait-set of the 'telephone' object (which one will be picked is an implementation dependent stuff and Java Language specification doesn't enforce any restriction on which one to be picked) and the chosen thread will now get out of WAITING mode and start trying to acquire the monitor/lock of the 'telephone' object along with any other thread that might be vying to access the 'telephone' at that point of time.


The only difference between 'notify' and 'notifyAll' is that in case of the latter all the threads of the corresponding wait-set are picked and they all start trying to acquire the lock on the object (with any other incoming requester thread) at the same time.


Evidently you see that these three methods are essentially object-related and not thread-related and hence the designers of Java Language considered it wise to put them in the Object class instead of putting them into the Thread class. The usage of the 'object' (in our case 'telephone') is the particular object's prerogative and not that of the requester threads'. Putting these three methods in the Object class helps the objects owning/controlling their usage in a better way as in that case a thread needs to first acquire the lock on the object (kind of getting a license to use the object) and then calling either wait (in case the thread doesn't find the object in the state it would have wished it to be in and hence thought of waiting for some time to let the object become useful for it) or notify/notifyAll to alert other threads waiting on the object once it finishes using the object (of course in the case when the thread find the object useful in its current state).

Additionally, the communication among the interested threads becomes far too easier when the control is kept at the object's level - one common shared resource/medium and all interested threads communicating via it. Not that the communication won't be possible if these methods are kept in the Thread class, but the handling of the communication and usage of the objects in a multi-threaded environment will probably become more complex and less flexible in that case.

Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Monday, August 3, 2009

per-thread Singleton and per-thread Logging in Java


Usage of ThreadLocal: per-thread Singleton and per-thread Logging

Should you require a refresh of what ThreadLocals in Java are and how they work, refer to this article first. You can then proceed with the current article for understanding two of the most common uses of ThreadLocals in Java.


per-thread Singleton impl using ThreadLocal


Suppose you have a need of having a JDBC Connection objects per thread of your application. The moment you hear the term 'per-thread', ThreadLocal automatically comes into mind as that's what it's primarily meant for. Below is a sample implementation of how easily can you actually use ThreadLocal for a per-thread JDBC Connection object in Java.



public class ConnectionDispenser {

private static class ThreadLocalConnection extends ThreadLocal {

public Object initialValue() {

return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());

}

}

private static ThreadLocalConnection conn = new ThreadLocalConnection();

public static Connection getConnection() {

return (Connection) conn.get();

}

}


Most of the code is self-explanatory and you can easily see how overriding the 'initialValue()' method of ThreadLocal is doing the trick of getting a Connection object by calling 'getConnection' method of the 'DriverManager' class. As you know the 'initialValue()' method is called only once for a ThreadLocal object and hence the Connection object will be obtained only once per thread (as a ThreadLocal object is created per thread only). From then on, whenever the particular thread requires the Connection object it simply calls the static 'getConnection' method of the your 'ConnectionDispenser' class, which in turn calls the 'get()' method of ThreadLocal to fetch the Connection object associated with that particular thread.

per-thread Debug Logging impl using ThreadLocal


Ever thought of having a per-thread DEBUG logging for any of your applications? Few multi-threading applications do get trickier at times and having per-thread DEBUG logs might be of great help in such situations as you probably can't visualize the actual order in which the threads might have executed and changed the shared objects. Here goes a sample implementation of per-thread DEBUG logging in Java using ThreadLocal.



public class DebugLogger {

private static class ThreadLocalList extends ThreadLocal {

public Object initialValue() {

return new ArrayList();

}

public List getList() {

return (List) super.get();

}

}


private ThreadLocalList list = new ThreadLocalList();

private static String[] stringArray = new String[0];


public void clear() {

list.getList().clear();

}


public void put(String text) {

list.getList().add(text);

}


public String[] get() {

return list.getList().toArray(stringArray);

}

}


As you can identify we are using an ArrayList object to store the logging info for a thread. 'initialValue' has been overridden to initialize every thread with a new ArrayList object. Whenever your multi-threaded application calls the 'put' method of your 'DebugLogger' class then all that method does is that it adds the logging info (passed as an String parameter to the 'put' call) to the corresponding ArrayList object of the current thread. Similarly a 'get' call of your 'DebugLogger' class simply returns the associated ArrayList object of the current thread in form of an String array. Evidently the 'clear' method of your 'DebugLogger' class is for clearing the logging info captured so far for the current thread - it'll simply clear the ArrayList object holding logging info for the current thread. This might help you getting rid of the non-essential logging info, maybe based on some condition, when you know for sure that all that you need for your debugging is what you are going to capture next and now what has already been captured so far.


Source: a nice article on ThreadLocals in Java, which I thoroughly enjoyed.


Liked the article? Subscribe to this blog for regular updates. Wanna follow it to tell the world that you enjoy GeekExplains? Please find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Sunday, February 22, 2009

ThreadLocal & InheritableThreadLocal in Java, initialValue() v/s set(), Uses of childValue()


ThreadLocal in Java - what is it used for?

As the name suggests this Java library class is used for supporting thread-local variables - the variables which are local to the particular thread instance and hence each thread will have their own copy of such variables which will be initialized every time a new thread is spawned.


To be more clear, let's take one simple example. If you have a class having some private/public static fields defined in it then all the objects created in all threads will share the same instances of those static fields. What if you want every thread to have a separate copy of it? ThreadLocal class will be of use in such cases, in fact they are mainly used for this purpose only. You can't just switch to a non-static field as in that case all the objects (even those created in the same thread) will have their own copies. You may come across situations asking you to have copies based on threads and not based on instances. This is where you will probably like to use ThreadLocal.


This class was introduced to Java in the version 1.2 and it has only three methods - one protected (initialValue()) and two public (get() and set()). The method set() is only rarely used as for most of the applications use the initialValue() method does the trick.

  • protected Object initialValue() - as the name suggests this method returns the initial value of the ThreadLocal variable for the current thread and it's invoked at most once per thread. This method will be executed only if the thread calls the get() method on the ThreadLocal variable for the time and also only if the thread doesn't call set() method on the ThreadLocal variable prior to calling get() on it. As already mentioned that initialValue() method is called only when get() is called for the first time and hence if the thread calls set() method before get() then the initialValue() will never be executed on that ThreadLocal variable.
  • public Object get() - evidently it will return the value of the ThreadLocal variable for the current thread. As discussed above, if it's called for the first time then the ThreadLocal variable is created and initialized by calling the initialValue() method internally.
  • public void set(Object value) - like any other setter this method will also set the current thread's copy of the ThreadLocal variable to the passed 'value'. This method is used only rarely as in most of the cases initialValue() method solves the purpose in a better way.

initialValue() method v/s set() method for a ThreadLocal variable


  • initialValue() method is called at most once and it's called only implicitly whereas set() method can be called any number of times and every time the call will be an explicit call.
  • initialValue() is called when get() method is called for the first time on the ThreadLocal variable in the current thread and that too only when set() method has not been called before the first get() call (in which case initialValue() method is never called in that thread on that ThreadLocal variable).

Overriding the initialValue() method and using it in an application

initialValue() method is a protected method which initializes the ThreadLocal variable with 'null' in its default implementation and almost every time we need to override this method to initialize the ThreadLocal variable as per our requirements. Anonymous inner classes are normally used for this overriding to make the code more readable and maintainable. Let's walk through the sample code given in the Sun Javadoc for ThreadLocal.



public class SerialNum {
// The next serial number to be assigned
private static int nextSerialNum = 0;

private static ThreadLocal serialNum = new ThreadLocal() {
protected synchronized Object initialValue() {
return new Integer(nextSerialNum++);
}
};

public static int get() {
return ((Integer) (serialNum.get())).intValue();
}
}


In the above example, changes made to the private static int field named 'nextSerialNum' will be reflected in all the threads using the 'SerialNum' class as it's a normal static field and will be shared across all the instances created in all the threads, but the static ThreadLocal field named 'serialNum' will be created and maintained separately for all the threads and will not be shared across all the threads.


As you can see that anonymous inner class has been used to override the initialValue() method which sets the initial value of the ThreadLocal variable 'serialNum' to the Integer object created with the current value of the static field 'nextSerialNum'.


A call to the get method of the 'SerialNum' class will ultimately call the get() method on the ThreadLocal variable 'serialNum' and if the first outer get (of the SerialNum class) call will obviously make the first inner get (of the ThreadLocal class) call on the ThreadLocal instance 'serialNum' which will subsequently invoke the initialValue() on the ThreadLocal variable in the current thread.


InheritableThreadLocal - what's this and when to use it?


Suppose you have a requirement of setting the value of a ThreadLocal variable in a child thread as a function of the value of a ThreadLocal variable in the parent thread, then using a normal ThreadLocal variable won't do the needful as for ThreadLocal variables the initial values are set independently in every thread including any child threads as well.


InheritableThreadLocal which subclasses ThreadLocal class is used in such situations. This class has only one method 'protected Object childValue(Object parentValue)' which is used to set the initial value of the InheritableThreadLocal variable in the child thread as a function of a ThreadLocal variable (passed as a parameter) in the parent thread. This method is called from within the parent thread before the child thread is created and the default implementation will make the child values identical to parent's, but we can override the childValue() method to set the child value as a function of the parent value for those ThreadLocals which have values in the parent thread. By default the childValue() returns the same input argument, but again an override of the childValue method might change this behavior as well.


Liked the article? Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. Interested? Find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Thursday, July 31, 2008

Guarded Block in Java - what's it & why is it used?


Guarded Blocks in Java - what are they & why are they used?

This is one of the most popular mechanisms of co-ordinating the execution of multiple threads in a multithreaded application. Such a block keeps checking for a particular condition to become true and only in that case the actual execution of the thread resumes.

Why should a thread's execution required to be co-ordinated with that of other threads? There may be several reasons - one of them being, if multiple threads are modifying a shared data and one (or maybe more) threads can't really proceed unless the shared data acquires a particular value (otherwise the execution may cause some incosistency/business-error or something of that sort) then in such a case we can have a condition checking the value of that shared data in that particular thread and can allow the execution of the thread to proceed only when the condition is true.

Now what the thread will do until then? Based on how the thread reacts to a 'false' condition, guarded blocks are of two types:-

  • synchronized guarded block - in this case if the condition is false then the block (which is a synchronized block) simply calls the Object.wait() method to release the acquired monitors on that object and leaves the processor to be used by other threads (probably more effectively as the current thread would not have done anything significant in this case unless the condition becomes true).
  • non-synchronized guarded block - in this case we simply cause the execution to keep executing a blank loop until the condition becomes true. This approach has an obvious disadvantage of wasting the precious CPU time, which could have been better utilized by some other threads otherwise.

Example: synchronized guarded block - Java code snippet

public synchronized guardedBlock() {

while(!sharedBooleanFlag) {
try {
wait();
} catch (InterruptedException e) {}
}

System.out.println("Shared Boolean Flag is true - you may proceed now!");

}

non-synchronized guarded block - Java code snippet

public guardedBlock() {

while(!sharedBooleanFlag) {
//... empty loop
}


System.out.println("Shared Boolean Flag is true - you may proceed now!");

}

A thread which is in waiting state on an object may be interrupted/notified by some other thread either intentionally or accidentally and hence may start execution after getting re-scheduled, but that doesn't guarantee that the condition (which is required to be true for the thread to proceed further) has also become true and hence one needs to make sure that the wait() method is always called inside the loop which checks for the condition. If the thread wakes up and starts its execution before the condition becomes true then it'll immediately go to the waiting state once again which will obviously save the precious CPU time to be utilized by other threads and at the same time such an approach will always guarantee that the execution of the thread will proceed only in the expected manner.

Don't forget to ensure that the application has other threads which acquire locks on the objects (on which few other threads have previously called wait() method) and call either notify() and notifyAll() methods so that the application can avoid startvation of those threads which have called wait() on the objects under consideration. notifyAll() scheduled all the waiting threads whereas notify() randomly picks one of the waiting threads and schedules it. Use the method which suits the design of your application. Read more aout the differences between the two methods in this article - notify()vs notifyAll() >>.



Share/Save/Bookmark


Tuesday, July 29, 2008

Deadlock - what's it? How to deal with this situation?


Deadlock - what's it? How to deal with a Deadlock situation?


What's Deadlock?


It's basically a situation where two or more threads are blocked forever waiting for each other to release an acquired monitor to proceed further.


Let me try to explain it using an example. Suppose we have two thread - threadA and threadB. There are two objects of a class TestClass - objA and objB and we have two synchronized instance methods in TestClass named A and B. Method A accepts an argument of type TestClass and calls method B from the passed object reference. Now, consider a situation where the first thread - threadA acquires the monitor of objA and enteres into the synchronized method A() on objA with the passed object reference as objB and at the same time threadB enteres into the same synchronized method 'A' on the object reference - objB with the passed object reference to the method as objA. Now, both the threads will keep waiting for the monitors of the objects - objB and objA respectively to complete the execution of the synchronized method A() and hence such a situation will result into a Deadlock. Of course such a situation will probably happen only rarely, but it's definitely a possible scenario. Calling the start() method on a Thread instance only ensures that the particular thread will participate in the CPU Scheduling, but we never know when exactly the thread will actually be allocated the CPU and in turn will start the execution.


Example: Java program having a possibility of Deadlock


public class PossibleDeadlockDemo {


static class TestClass {

...

...


public synchronized void A (TestClass testClass) {

...

testClass.B();

}


public synchronized void B () {

...

}

}


public static void main(String[] args) {

final TestClass objA = new TestClass("ObjectA");

final TestClass objB = new TestClass("ObjectB");


Thread threadA = new Thread(new Runnable() {

public void run() { objA.A(objB); } });


Thread threadB = new Thread(new Runnable() {

public void run() { objB.A(objA); } });


threadA.start();

threadB.start();

}


}


How to deal with a Deadlock situation?


Probably the only possible way to rectify a Deadlock situation is to avoid it. Once the deadlock has already happened then you'll probably left with the only option of restarting the JVM process again OR it may even require you to restart the underlying OS. This is very hard to reproduce and debug because one can never be sure about when exactly the threads will be executed and hence the deadlock may not happen when you test it and eventually it may happen when the code actually goes into production. So, review the design of your mulithreaded application before you really start coding. You may somehow manage to escape any such situation or at least minimize the possibility to a great extent with a better design.



Share/Save/Bookmark


Monday, July 21, 2008

Concurrent execution of static and non-static synchronized methods


Concurrent execution of static and non-static synchronized methods


We have a scenario where we have a static synchronized method and a non-static synchronized method. As we know that a static method can only access static members of the class whereas a non-static method can access both static as well as non-static members. This liberty can put us into a situation where a non-static method might be updating some static data which a static method would also be changing. What will happen if two different threads try to access the static and non-static synchronized methods concurrently and in turn try to change the static data using the two methods? Will the synchronization guarantee mutual exclusion in such a case?


No... synchronization won't guarantee mutual exclusion in such a case as both the threads may access the static and non-static synchronized methods concurrently because a non-static synchronized method requires the invoking thread to acquire a lock of the particular object on which the thread invokes the non-static synchronized method whereas a static synchronized method will require the invoking thread to acquire a lock on the java.lang.Class object associated with the particular class (which the static method is a part of). Both these locks have nothing to do with each other and they can be acquired by different threads at the same time and hence two different threads may execute a static method and a non-static synchronized method of a class respectively at the same time (of course once they acquire the two locks).


It is certainly not advisable to allow such a thing to happen and hence the design of such a class needs to be re-checked. Otherwise the errors caused by simultaneaous modification of the same static data by different threads may infuse some really-hard-to-detect bugs.


Thus, we see that only declaring the methods as synchronized doesn't ensure mutual exclusion and the programmer should always think about the locks involved to achieve the actual purpose of synchronization.


Have a look at the following simple example where the same static data is being modified by two public synchronized methods - one being static and the other being non-static. The whole purpose of synchronization is getting defeated here as in such a case mutual exclusion can't be guaranteed, which is one of main purposes of using synchronization.


public final class BadDesign{

private static int sensitiveData;

public synchronized static void changeDataViaStaticMethod(int a){

//... updating the sensitiveData

sensitiveData = a;

}


public synchronized void changeDataViaNonStaticMethod(int b){

//... updating the sensitiveData

sensitiveData = b;

}


public static void showSensitiveDataStatic(){

System.out.println("Static: " + Thread.currentThread().getName()+ " - " + sensitiveData);

}


public void showSensitiveData(){

System.out.println(Thread.currentThread().getName() + " - " + sensitiveData);

}


public static void main(String[] args){

new Thread(new TestThread11()).start();

new Thread(new TestThread11()).start();

}


}


class TestThread11 implements Runnable{


public void run(){

int i = 0;

do{

BadDesign.changeDataViaStaticMethod(5);

BadDesign.showSensitiveDataStatic();


//... new object for every iteration

//... so synchronization of non-static method

//... doesn't really do anything significant here

BadDesign bd = new BadDesign();

bd.changeDataViaNonStaticMethod(10);

bd.showSensitiveData();

}while (i++ < 100);

}

}


An excerpt from the output:-

...

Static: Thread-0 - 5

Thread-0 - 10

Static: Thread-0 - 5

Thread-0 - 10

Thread-1 - 10

Static: Thread-0 - 5

Static: Thread-1 - 5

Thread-1 - 10

...


By looking at the above exceprt you can easily conclude that the static and non-static synchronized method calls are intermixed between the two threads: Thread-0 and Thread-1. In this case the non-static synchronized method is always being called on a new object (as the do-while loop of the run() method is creating a new object of the class BadDesign for every non-static synchronized method call) by both the threads and hence synchronization doesn't really do anything significant for them as every new object will have its own lock which will be easily acquired by the invoking thread everytime the do-while loop iterates. I've kept this just to make the code simple as my purpose of the above example is just to show that static synchronized methods and non-static synchronized methods are completely independent of each other and both of them can run at the same time by different threads for the simple reason that both these methods are governed by different locks which may be acquired at the same time by two different threads.


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Saturday, July 5, 2008

Synchronization of static and instance methods in Java


Synchronization of static methods/fields in Java

What's an Intrinsic lock OR a monitor lock in Java?

An intrinsic lock, a monitor lock, or a monitor - all three refer to the same internal entity associated with every object in Java which enables the implementation of the Synchronization mechanism. This lock is used to enforce an exclusive and consistent access in Java as a monitor can be acquired by only one thread at a time.

A thread needs to acquire the monitor of an appropriate object before entering a synchronized method/block which it releases when the thread returns from the method (or completes the block). The monitor is released even if an uncaught exception is thrown from the method/block.

Synchronized methods vs Synchronized blocks

These are the two ways of achieving synchronized access in Java. In Java, a method is also a block only, but we normally refer to a block as a part of the method definition. As we know that a thread needs to acquire an appropriate monitor (which it releases when the method returns) before entering any synchronized method/block, so we can easily figure out that in case of a synchronized method a thread may need to have the lock for a longer period of time as compared to that in case of synchronized block.

Another difference is that we don't specify the particular object whose monitor is required to be obtained by a thread for entering a synchronized method whereas we can specify the particular object in case of a synchronized block.

static synchronized method vs instance synchronized method

When a thread needs to enter a static synchronized method, it acquires the monitor of the Class object associated with the particular class to which the static method belongs to whereas in case of a synchronized instance method, the thread requires to obtain the monitor of the particular object on which the method call is being made. Easy to understand the reason... right?

Synchronization of static fields in an instance synchronized method

As we just saw that a thread needs to acquire the monitor of the Class object of the class in case synchronized static method, but how can you handle the synchronization of static fields in instance methods?

In Java, an instance method can access static fields as well (vice versa is not possible for the obvious reason), suppose a synchronized instance method having code accessing static fields, is being accessed on different objects by different threads (which is quite possible as each of the different threads would have acquired monitor of one of the different objects) then in such a case we can't guarantee a exclusive access to those static fields. The reason is very simple - a static field doesn't belong to an instance instead to the class and hence the access to it is not controlled by monitors associated with the instances of the class instead the access to them is controlled by the monitor of the Class object associated with the class. Hence, we need to be very careful in such scenarios and any synchronized instance method should have an explicit synchronized block for accessing static fields if the static fields require an exclusive access. This synchronized block can specify the Class object associated with the class and hence a thread which enters the synchronized instance method after acquiring the monitor of the particular instance will first need to acquire the monitor of the Class object as well before executing the code which accesses static fields. And this way we can guarantee exclusive access to the static fields accessed inside a synchronized instance method.

Read next: Why synchronization of constructors is not allowed? Do you know Re-entrant Synchronization? You may like to read the article - What's Reentrant Synchronization in Java?


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Synchronization of constructors not allowed in Java - why?


Synchronization of constructors not allowed in Java - why?


In Java, synchronization of contructors is not allowed (results in a compile time error) as only the thread which is constructing the object should have access to the object and hence any other thread is not granted access until the construction of the object is complete. So, no explicit synchronization needed for constructors.


Caution: even though other threads will be given the access to an object only when it's already constructed, but if the constructor itself is allowing a memory leak then an imcomplete object can also be accessed by other threads which is obviously undesirable as the behavior is undefined. This may happen in case we are maintaining a Collection of instances (say with the reference 'instances') of the class and if the constructor is using the statement 'instances.add(this);' to add the current instance to the Collection then a half-baked object may be accessed by other threads.


Read next - static method/field synchronization >> The article tries to answer these questions: How does the static method synchronization differ from instance method synchronization? How do we ensure exclusive access to static fields being accessed in synchronized instance methods?


Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


What is Reentrant Synchronization in Java?


What is Reentrant Synchronization in Java?

We know that a thread can not acquire a monitor which is owned by another thread. A thread own a monitor for the period between the time it acquires the monitor for entering a synchronized method/block and the time when it releases the monitor when the thread either returns from the method (or completes the block) OR throws an uncaught exception.

But, a thread is allowed to acquire a monitor owned by itself. Confused? Why would a thread need to acquire a monitor which it already owns? It heppens when a synchronized code either directly or indirectly invokes a synchronized method/block which requires the same monitor. For example: a recursive synchronized method. Allowing a thread to acquire the monitor it already owns is called Reentrant Synchronization and without which it'll be very difficult to ensure that a thread in Java doesn't block itself.

Read Next - Synchronization of static fields/methods in Java >> - the article discusses how static methods and static fields are synchronized in Java? How can we ensure exclusive and consistent access to static fields in instance synchronized methods? To understand the why constructors can't be synchronized and how can a half-baked object be exposed to other threads read the article - Why constructors can't be synchronized in Java?



Share/Save/Bookmark


Thursday, July 3, 2008

Thread.State in Java? BLOCKED vs WAITING


What is Thread.State in Java? What's it used for?

Thread.State - This is a static nested class (Read more about nested classes in the article - Nested Classes & Inner Classes in Java >>) of the Thread class. This is one of the additions of Java 5 and this class actually inherits the abstract class Enum which is the common base class of all Java language enumeration types i.e., Thread.State is actually is actually an enumeration type.

Thread.State enumeration contains the possible states of a Java thread in the underlying JVM. These states are different from the Operating System thread states. The possible values of the Thread.State are:-

  • NEW - this state represents a new thread which is not yet started.
  • RUNNABLE - this state represents a thread which is executing in the underlying JVM. Here executing in JVM doesn't mean that the thread is always executing in the OS as well - it may wait for a resource from the Operating system like the processor while being in this state.
  • BLOCKED - this state represents a thread which has been blocked and is waiting for a moniotor to enter/re-enter a synchronized block/method. A thread gets into this state after calling Object.wait method.
  • WAITING - this state represnts a thread in the waiting state and this wait is over only when some other thread performs some appropriate action. A thread can get into this state either by calling - Object.wait (without timeout), Thread.join (without timeout), or LockSupport.park methods.
  • TIMED_WAITING - this state represents a thread which is required to wait at max for a specified time limit. A thread can get into this state by calling either of these methods: Thread.sleep, Object.wait (with timeout specified), Thread.join (with timeout specified), LockSupport.parkNanos, LockSupport.parkUntil
  • TERMINATED - this state reprents a thread which has completed its execution either by returning from the run() method after completing the execution OR by throwing an exception which propagated from the run() method and hence caused the termination of the thread.
Difference between BLOCKED state and WAITING / TIMED_WAITING states?

When a thread calls Object.wait method, it releases all the acquired monitors and is put into WAITING (or TIMED_WAITING if we call the timeout versions of the wait method) state. Now when the thread is notified either by notify() or by notifyAll() call on the same object then the waiting state of the thread ends and the thread starts attempting to regain all the monitors which it had acquired at the time of wait call. At one time there may be several threads trying to regain (or maybe gain for the first time) their monitors. If more than one threads attempt to acquire the monitor of a particular object then only one thread (selected by the JVM scheduler) is granted the monitor and all other threads are put into BLOCKED state. Got the difference?

Difference between WAITING and TIMED_WAITING states?

The difference is quite obvious between the two. A thread in a TIMED_WAITING state will wait at max for the specified timeout period whereas a thread in the WAITING state keeps waiting for an indefinite period of time. For example, if a thread has called Object.wait method to put itself into WAITING state then it'll keep waiting until the thread is interrupted either by notify() method (OR by notifyAll() method) call on the same object by another thread. Similarly, if a thread has put itself into WAITING state by calling Thread.join method then it'll keep waiting until the specified thread terminates.

We can easily figure out that a thread in a WAITING state will always be dependent on an action performed by some other thread whereas a thread in TIMED_WAITING is not completely dependent on an action performed by some other thread as in this case the wait ends automatically after the completion of the timeout period.



Share/Save/Bookmark


Tuesday, July 1, 2008

Alternatives of stop, suspend, resume of a Thread


Did you go through the first part of the article which discussed - Why Thread.stop() method is deprecated in Java? Why ThreadDeath is a subclass of Error and not of Exception? Can't we catch the ThreadDeath and fix the damaged objects? What will happen if stop() method is called on a thread which is yet to start? ... You may like to go through the first part before proceeding with this part.

This part of the article tries to answer the following questions:-

  • What should we do instead of using stop() method?
  • How can we stop a long waiting (maybe due to I/O) thread?
  • What if a thread doesn't respond to Thread.interrupt() call?
  • Why are Thread.suspend & Thread.resume deprecated?
  • What should be done instead of using suspend & resume?
  • What's Thread.destroy()?
What should be done instead of using stop() method?

If stop() is deprecated and therefore suggested not to be used then how should a situation requiring the usage of stop() method should be handled? Good question... we can follow the recommended approach by Sun which requires to have a variable, which should either be volatile or the access to the variable should be synchronized. The thread will check this variable regularly and hence the thread may be stopped in an orderly fashion by setting an appropriate value to the variable which will communicate the thread that it should stop in an orderly way now.

For example:

Instead of having the stop() as

...
private Thread theCurrentThread;
...
public void run(){
theCurrentThread = Thread.currentThread();
...
...
}

public void stop(){
theCurrentThread.stop();
}

we can have a graceful and safe stop as

...
public void stop(){
theCurrentThread = null;
}

What'll happen if we use the above mentioned graceful stop alternative on a thread which is into an infinite loop? Read this article to understand that - Impact of assigning null to a running thread executing an infinite loop >>.

How can we stop a thread that waits for long periods maybe for I/O?

We can follow the same graceful stop technique discussed above in this case as well. We just need to call the interrupt() method of the thread after assigning null to the thread. For example, we may have the stop method as:-

...
public void stop(){

Thread t = theCurrentThread;
theCurrentThread = null;
t.interrupt();

}

Why do we need to have another reference to call interrupt() on? Why don't we call on the same thread reference 'theCurrentThread' in this case? Easy question, I know. But leaving for you to think ... just to ensure that you're still awake :-)

Ans yes, in this approach if any method catches this InterruptedException thrown from the stop() method, then that method should either have InterruptedException in its throws list OR it should re-interrupt itself by throwing calling the interrupt() method again otherwise the purpose of rasing the InterruptedException from the stop() method will go in vain.

What if Thread.interrupt doesn't affect a thread?

It's bizarre, but if the thread stops responding to Thread.interrupt() method then we need to some application specific tricks to overcome the situation. For example, if the thread is waiting on a Socket and stops responding to interrupt() method, then we may close the Socket which will cause the thread to return immediately.

Be sure that if a thread doesn't respond to interrupt() method, it will not respond to the stop() method either. So, don't be tempted to use stop() in such situations.

Why are Thread.suspend and Thread.resume deprecated?

suspend() and resume() methods are deprecated as it may cause a deadlock to happen. The reason for this is that the suspend() method doesn't release the acquired monitors and if a suspended thread has already acquired the monitor of a critical resource then an attempt to acquire the same resource in the thread which would resume the suspended target thread will cause a deadlock.

What should be done instead if using suspend() and resume()?

The same approach what we follow to have a graceful stop can be followed in this case as well. We'll simply have a variable which will signify the various states of the thread and the target thread will keep polling the value of the variable and if the value indicates a suspend state then the thread will wait by calling the Object.wait method and if a value indicating the resumed state will cause the target thread to be notified using Object.notify method.

What does the method Thread.destroy do?

public void destroy() - this method was originally designed to destroy a thread without any clean-up i.e., without releasing any of the acquired monitors, which may cause deadlocks. This method was never implemented and a call to this method throws
NoSuchMethodError always.



Share/Save/Bookmark


Why stop, suspend, & resume of Thread are Deprecated


This is a slightly longer article and hence divided into two parts. This is the first part of the article, which will try to answer the following questions:-

  • Why Thread.stop() method is deprecated in Java?
  • Why ThreadDeath is a subclass of Error and not of Exception?
  • Can't we catch the ThreadDeath and fix the damaged objects?
  • What will happen if stop() method is called on a thread which is yet to start?
Why Thread.stop() has been deprecated?

Thread.stop() - public final void stop() - This method is deprecated for the simple reason that it's unsafe and may lead the program to some unexpected circumstances. Thread.stop() when called, it causes the thread to release all the acquired monitors and throw a ThreadDeath error, which ultimately causes the thread to die. Since, the thread releases all the acquired monitors immediately, so it may leave few objects (whose monitors were acquired by the thread) in an inconsistent state. Such objects are called damaged objects and obviously they may result into some arbitrary behavior.

In case a Security Manager is installed, the this method causes the checkAccess method to be called first which may result into a SecurityException and this exception will of course be raised in the calling thread. If the stop() method is being used to stop a different thread (than the calling thread) then the Security Manager's checkPermission method will also be called in addition to the checkAccess method. Both of these methods may result into a SecurityException to be thrown in the calling thread.

Can't the ThreadDeath object be caught and all the damaged objects be fixed?

Thoretically yes, but practically NOT possible as a thread may throw this ThreadDeath error almost anywhere and what if a ThreadDeath is thrown while executing the catch or finally block of the first ThreadDeath which we just caught... and so on. Don't you think that it may soon become practically infeasible to guarantee a fixed version of all the damaged objects? This is why the designers of Java preferred to deprecate the method than to ask the developers to do such a complex and almost infeasible work to ensure damage-control in all the cases while using stop method.

Why did they have it in the first place and why didn't they remove it altogether?

Maybe because we may face scenarios (of course not frequently, but only very rarely) where the side effect of stop() method (or any other deprecated method for that matter) may become insignificant than the actual affect which the method can do. So, designers can't simply remove the method to maintain the completeness of the language - they either need to design an equivalent method free from all the side-effects OR to allow the developers to use if they badly need it. Marking such methods as deprecated simply serves the purpose of discouraging the developers for using those methods and noe they will use them only if they are left with no other possible workaround.

Why Thread.stop(Throwable) has been deprecated?

Thread.stop(Throwable) - public final void stop(Throwable obj) - this variant of the stop method causes the thread to complete abnormally and to throw the passed parameter of type Throwable as an exception. This abnormal completion of the thread makes this method unsafe and potentially dangerous for the same reasons as discussed in the other variant of the stop() method and hence it's deprecated. In addition this variant may require a checked exception to be thrown which the target thread may not be prepared to handle and throw. This may lead to a very awkward situation and a defined behavior is probably not guaranteed in such a case.

A null value passed as the parameter will expectedly result into a NullPointerException in the calling thread. In case a Security Manager is installed, this variant may also throw SecurityException the same way as the other variant may.

What will happen if we call stop() method on a thread which is not yet started?

Interesting question, isn't it? Well... We're allowed to call stop() method (both the variants) on a thread which is yet to be started. In such a case, if the thread starts then the stop() method causes it to die immediately.

Why are they allowed then? Okay... how can we handle it otherwise? At compile time we can't check if the thread is started or not and at run time the stop() (with zero arguments) method call requires a ThreadDeath object to be thrown, so how will this requirement be met if we don't wait for the thread to eventually start and then be terminated by throwing ThreadDeath? Maybe we can create, start and terminate a dummy thread immediately when such a call is encountered. But, what will we gain by doing this? In fact that will be the same as the worst possible scenario where all such threads (un-started threads) actually get
started and terminated. In all possibilities, we may even have few such threads which don't start for the entire life cycle of the application. So why to waste time doing something in advance which will ultimately be done if required. Similar explanation can be given for the other variant of the stop() method because that also requires the target thread to complete abnormally - in addition that requires the passed Throwable type object to be thrown. Even worse situation to handle in advance, what do you say?

What's ThreadDeath? Why is ThreadDeath a subclass of Error and not of Exception?

public class ThreadDeath extends Error - an object of this class is thrown when the Thread.stop() method is called without any argument. If a method catches this thrown object then it should rethrow the error so that the thread actually dies. This is the reason why the ThreadDeath class has been made a subclass of the Error class and not of the Exception class. Many applications simply use Exception type to capture all the exceptions and handle them either by simply ignoring OR maybe by doing something in the handler. The ThareadDeath when thrown should not be handled that way. It's thrown only when Thread.stop() method is called and that simply expects the thread to die and not to be handled some other way.

The second part of the article answers the subsequent questions to complete the article. These questions are:-
  • What should we do instead of using stop() method?
  • How can we stop a long waiting (maybe due to I/O) thread?
  • What if a thread doesn't respond to Thread.interrupt() call?
  • Why are Thread.suspend & Thread.resume deprecated?
  • What should be done instead of using suspend & resume?
  • What's Thread.destroy()?
Read Next - part two of the article - alternatives of stop, suspend, resume in Java >>

Liked the article? You may like to Subscribe to this blog for regular updates. You may also like to follow the blog to manage the bookmark easily and to tell the world that you enjoy GeekExplains. You can find the 'Followers' widget in the rightmost sidebar.



Share/Save/Bookmark


Thursday, June 19, 2008

Thread problem - what'll 'threadObject = null' do for an active thread?


A thread problem - what will 'threadObject = null' do for an active thread?

package test;
public class Thread1 extends Thread{
public void run() {
int counter = 0;
while(true){counter++;
System.out.println("Inside Thread1 - " + counter);}
}
}


package test;
public class Class2 {
public static void main(String[] args) {
Thread1 thread1 = new Thread1();
thread1.start();
thread1 = null;
}
}

What will be the output when Class2 is run? 'thread1 = null' - what will this do?


Outout:

Inside Thread1 - 1
Inside Thread1 - 2
Inside Thread1 - 3
....
..... till the stack overflow occurs or till you forcibly terminate :-)

Did you anticipate anything else? Except the statement 'thread1 = null', everything else is pretty straightforward - the main() method will start the execution in the 'main' thread and during the execution, it'll create a new thread 'thread1', which will start its execution in a separate thread of execution. The 'main' thread being the parent thread will keep waiting for the child thread 'thread1' to finish its execution and only then the 'main' thread will exit. The child thread 'thread1' is running an infinite loop in its run() method, so it'll keep executiing unless it's forcibly terminated either by user's intervention OR may be due to stack overflow.

Okay... so if we include the statement 'thread1 = null' then why do you expect something else to happen? Maybe because you think that assigning 'null' to an object will simply make that object eligible for garbage collection (as in this case thread1 will have no other active references) and hence the thread should stop execution. Well... threads don't get terminated that way.

In Java, the JVM continues executing a thread until either of the following three occurs:-

  • Runtime.exit() method (or its equivalent System.exit() method) is called and the underlying Security Manager has permitted the method to execute. This invokes the JVM Shutdown Sequence (Read More in this article - JVM Shutdown Sequence >>) which eventually halts the entire JVM process (the thread under execution will just be a part of this process).
  • Runtime.halt() method is called and the underlying Security Manager is okay with the call. This abruptly and immediately halts the entire JVM process.
  • The thread under execution has returned from its run() method either by completing the execution of this method OR by thowing an uncaught exception which propagates beyond the run() method. A parent thread can return only when all of its child threads have already returned.

Now we can easily understand that 'thread1 = null' statement will not terminate the thread and the main thread will keep executing and eventually keep waiting (as thread1 is in infinite loop) for any of the above three cases to occur for the thread1 to terminate and after that the 'main' thread will also get terminated. In our example, we're not explicitly calling Runtime.exit() or Runtime.halt(), so they may be called only if we log off the machine or shut it down. Otherwise, only third case will cause the thread to terminate. run() being in an infinite loop will never complete its execution, so only an uncaught exception can terminate this thread. This uncaught exception can be either due to stack overflow OR may be due to some user intervention. Thus, we can say that having 'thread1 = null' will not at all affect the execution of any of the threads. The output will remain the same with without having this statement as well.



Share/Save/Bookmark


Thursday, May 29, 2008

What's the Role of the Future interface in Java?


Future interface

public interface Future - this interface was added in Java 1.5 and it holds the result of an asynchronous computation. This interface contains methos to check if the asynchronous computataion is complete or still in progress, to wait for the completion of the computation and to block the call until the completion of the computation, and apparently to retrieve the result of the computation.

You can use Future in that case also where you simply want to either check if a task is complete or not or to simply cancel an ongoing task, but you don't want to return any significant result. Use Future to declare the type and return 'null' as the result in such a case.

Methods of the Future interface:-

  • boolean cancel(boolean mayInterruptIfRunning) - this method cancels the task if it's still under progress and returns 'true' in case it successfully cancels it. 'false' is returned if the task has alraedy completed or if the attempt of this method to cancel the task fails due to some other reasons. If the task has not started when the cancel method is called the the task should never run. The parameter mayInterruptIfRunning is used to determine if the thread executing this task should be interrupted or not. If it's true then the thread is interrupted otherwise the taks in progress are allowed to complete and the attempt to cancel the task fails.
  • boolean isCancelled() - it returns 'true' if the task got cancelled before its completion
  • boolean isDone() - it returns 'true' in case the task got completed either due to normal completion or due to exception or due to cancellation of the task using the cancel() method.
  • V get() - if the task has completed, it returns the result, otherwise waits for thr task to get completed first and then returns the result. This method may throw three exception:- One, CancellationException - in case the task was cancelled using cancel() method; Two, ExecutionException - if an exception occured during the execution of the task; Three, InterruptedException - if the thread executing the task was interrupted while it was in the waiting state.
  • V get(long timeout, TimeUnit timeUnit) - As the parameters suggest this variant of get will wait for the specified time only and if the task gets completed before the expiry of the timeout then it returns the result if the computation otherwise returns TimeoutException. It may throw the other three exceptions as well similar to the other variant of get() method.



Share/Save/Bookmark