Wednesday, May 5, 2010

Thread programming in Java

I spent a day in library refreshing stuffs I learned long back(not so long!) while I was in undergrad. Since my memory is fresh with these topics, I thought I should blog them so next time I can find it all in one place. On a different note, a day spent studying/reading in library is well spent! Okay back to Threads in Java.

Thread - class, Runnable - interface which has the thread implementations. For our application class to use thread we need to either implement or subclass or make the class a member class of our application. Thus three ways to create threads:
  1. Extend Thread class: For standalone applications that don't need to extend another class.
  2. Implement Runnable interface: For classes that need to extend other classes. Due to single inheritance, we can achieve threads by implementing the interface. Eg: Applets that extend JApplet and can't extend Thread too.
  3. Construct a thread passing an inner class that is Runnable: For threads with tiny run methods and little outside interaction.
Thread life cycle functions:
  • Thread() - When subclassing Thread class
  • Thread(name) - when subclassing + for debugging
  • start() - Begins process of assigning CPU time to a thread. Finally it results in calling run() method of the thread object.
  • suspend(), resume(),stop() - deprecated. Because these suspend and resume functions can cause deadlocks.
  • interrupt() - interrupt whatever the thread is doing
  • boolean isAlive() - returns true if thread is neither finished or terminated by call to its stop()
  • join() - to wait for a thread to finish
  • get/setPriority() - higher priority threads gets first chance of CPU
  • wait(), notify(), notifyAll() - semaphore and for thread synchronization.
  • synchronised - keyword - can be used for any object in Java. When used over an object or a method, threads will wait if one thread has already started running.
Thread synchronization:
The wait, notify and notifyAll methods allow any java.lang.Object to be used as a synchronization target.

wait():
This causes the current thread to block in given object until awakened by notify or notifyAll.

notify():
Randomly selected thread waiting on this object is awakened. Then that thread tries to regain the monitor lock. If wrong thread is awakened, will result in deadlock.

notifyAll():
All threads waiting on this object is awakened. Then all try for the monitor lock. Hopefully one of them succeed.

Best practices:
  • To avoid deadlock, use notifyAll to wake up waiting threads.
  • To avoid using deprecated method - stop, use the variable as a flag and use it to find if the thread is done executing.

No comments: