Home > Multithreading > Java Multithreading

Java Multithreading


I, originally, wrote this article 4 years ago. And all the examples are based of Java 6. I don’t have any liability If any example fails due to change in java libraries.

There are 3 ways to create threads in java;

    • Extends Thread class
class ConcreteClass extends Thread {
	public void run() {
	:
	}
}

ConcreteClass cObj = new ConcreteClass();
cObj.start();
    • Implements Runnable Interface and pass it’s object to Thread class
    • Implements Callable interface and pass it’s object to Thread class
class ConcreteClass implements Runnable {
	public void run() {
	:
	}
}

ConcreteClass cObj = new ConcreteClass();
Thread T1 = new Thread(cObj,"my Thread");
T1.start();

Important Terms

Monitor
it ensures that only one thread can enter in its critical section. It is associated with every object in java. Synchronized acquires a monitor for a thread. It is also called intrinsic or monitor lock.

method(
	:
	synchronized(this){
		:
	}
}

method2(
	synchronized(this){

	}
	:
}

Starvation
When a thread waits too long.

  • If there are multiple threads waiting on same object, notify() can awake any thread randomly. It arises the condition that some threads never get awaken and some always get awaken.
  • Sometimes some greedy threads don’t release resources (call sleep() instead of wait() etc). It also force other threads to wait.
  • Some threads increase their priority to get served first to CPU, it also force low priority threads to wait for long.

Slipped condition 
from the time a thread has checked a certain condition until it acts upon it, the condition has been changed by another thread.

method(
	:
	while(amount < required){
		synchronized(filler){
			filler.notify();
		}
		wait();
	}
	amount -= required;
	:
}

Race condition
A race condition occurs when two or more threads can access shared data and they try to change it at the same time. Both threads are “racing” to access/change the data. We don’t know who will win.

It can be avoided by creating lock over the shared data.

DeadLock
When all threads waiting outside the door closed by another thread. And this chain is either circular or ending on resource which cant be assigned to any thread due to some reasons. (Might be because it is held by some devil thread).

Nested Monitor Lockout
Lock inside lock. wait() releases one of the lock but not all. It results deadlock.

method(
	synchronized(this){
		while(flag){
			synchronized(a){
				a.wait();
			}
		}
	}
}

method2(
	synchronized(this){
		flag = false;
		synchronized(a){
			a.notify();
		}
	}
}

Guarded/loop/spin lock
Loop & Wait until the condition becomes false.

while(condition){
	wait();
}

Reentrance Lock
When one thread calls a synchronized block inside from another synchronized block on the same object. (when a thread reenters in its monitor)

public synchronized outer(){
	inner();
}

public synchronized inner(){
	//do something
}

It is allowed for same thread. But if 2 separate threads access 2 separate synchronized blocks, then one of them will have to wait.

Daemon Thread
A thread that has no other role in life than to serve others. For example Timer thread, garbage collector. JVM stop executing a program if only daemon.

To make a thread daemon in java just call setDaemon(true) on a thread.

	private static class MyDaemonThread extends Thread {

		public MyDaemonThread() {
			setDaemon(true);
		}

		@Override
		public void run() {
			while (true) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
				}
			}
		}
	}

	public static void main(String[] args) throws InterruptedException {
		Thread thread = new MyDaemonThread();
		thread.start();
		:
	}

Livelock
A livelock is a situation in which two or more threads block each other by responding to an action that is caused by another thread. In contrast to a deadlock situation, where two or more threads wait in one specific state, the threads that participate in a livelock change their state in a way that prevents progress on their regular work.

If two threads detect a deadlock, and try to “step aside” for each other, without care they will end up being stuck in a loop always “stepping aside” and never managing to move forwards.

By “step aside” I mean that they would release the lock and attempt to let the other one acquire it.

Example:

  • Two persons passing each other in a narrow gallery.
  • A husband and wife are trying to eat soup, but only have one spoon between them. Each spouse is too polite, and will pass the spoon if the other has not yet eaten.

Reference

Advertisements
Categories: Multithreading
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: