CodesJava

Easy learning with example program codes

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 codesjava
 */
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.

Please follow and like us:


Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki