• August 29, 2014
  • Core Java
  • Comments Off on Starvation in java

Starvation in java

Starvation:

Starvation is a situation when a thread is in waiting state from long period because it not getting access of shared resources or because higher priority threads are coming.

Example:

StarvationExample.java

/**
 * This program is used to show the starvation problem. 
 * @author javawithease
 */
public class StarvationExample implements Runnable{
	private final Object resource;
	private final String message;
	private final boolean fair;
 
 
	public static void main(String[] args)
	{
		boolean fair = false;
		if (args != null && args.length >= 1 && args[0].equals("fair")) {
			fair = true;
		}
 
		// get the number of available CPUs, do twice as much threads.
		final int cpus = Runtime.getRuntime().availableProcessors();
		System.out.println("" + cpus + " available CPUs found");
		final int runners = cpus * 2;
		System.out.println("starting " + runners + " runners");
 
		final Object resource = new Object();
 
		// create sample runners and start them
		for (int i = 1; i <= runners; i++) {
			(new Thread(new StarvationExample(resource, String.valueOf(i), fair))).start();
		}
 
		// suspend main thread
		synchronized (StarvationExample.class) {
			try {
				StarvationExample.class.wait();
			} catch (InterruptedException ignored) {
			}
		}
	}
 
	public StarvationExample(Object resource, String message, boolean fair)
	{
		this.resource = resource;
		this.message = message;
		this.fair = fair;
	}
 
	public void run()
	{
		synchronized (this) {
			for (;;) {
				synchronized (resource) {
					print(message);
					try {
						(fair ? resource : this).wait(100);
					} catch (InterruptedException ignored) {
					}
				}
			}
		}
	}
 
	private static void print(String str)
	{
		synchronized (System.out) {
			System.out.print(str);
			System.out.flush();
		}
	}
}

Output:

4 available CPUs found
starting 8 runners
1222222222222222222222222222222222222222222222222222222222222222...

Download this example.
 
Next Topic: Inter-thread communication in java with example.
Previous Topic: Deadlock in java with example.

Related Topics:

Multithreading in java.
Thread life cycle in java.
Way of creating thread in java.
Commonly used methods of Thread class.
Thread scheduling in java with example.
Thread priority in java with example.
Naming a thread in java with example.
Joining a thread in java with example.
Daemon thread in java with example.
Can we start a thread twice?
Can we call run method directly?
Difference between Thread.yield() and Thread.sleep() methods.
Deadlock in java with example.
Starvation in java with example.
Inter-thread communication in java with example.
Synchronization in java with example.
Synchronized method in java with example.
Static synchronization in java with example.
Synchronized block in java with example.

 


Comments are closed.