Week 9 - Exceptions, Threads, Applet Parameters

Threads

Recommended Reading

Doing Two or More Tasks At Once: Threads

I like the way threads are done in Java.

Thread Concepts

Simply put, threads allow you to put an independent stream of execution onto its own, lightweight process. This allows for two or more tasks to seemingly be accomplished simultaneously.

Here is how this is accomplished, and some terms you should know:

For further enlightenment, see the What Are Threads? section of the tutorial.

The Life Cycle of a Thread

You will want to look first at the Clock Applet Example, and then look at The Life Cycle of a Thread section in the tutorial. It explains Java Threads rather well.

Basically, the life cycle of a thread goes like this:

Two Approaches to Threading

If you decide to use threads in your programs, there are two approaches you can take: See Customizing a Thread's run Method for an explanation of these two approaches.

Subclass Thread and override run

With this approach, you make your own thread as a subclass of the stock Thread object and override the run method, filling the body with what you need.

The following is an example of a custom thread suitable for a console program that sums up an array of floats and prints the result on the standard output.


class SumThread extends Thread
{
	private float numbers;

	public SumThread(float[] nums) {
		numbers = nums;
	}

	public void run() {
		float sum = 0.0;

		// Add up all the numbers
		for (int i = 0; i < numbers.length; i++) {
			sum += numbers[i];
		}

		// Display the result
		System.out.println("Sum: " + sum);
	}
}

See the Thread Class API reference for all of the info on threads.

Implement the Runnable interface

With this approach, you simply put implements Runnable as part of a class declaration and override the run method. If you choose this approach you will need to keep the following things in mind:

The following snippet of code shows a skeleton of what a class might look like that implements a Runnable interface.


class DisplaySum extends Label implements Runnable
{
	private Thread ownThread = null;
	private float[] numbers;
	
	public DisplaySum(String text) { 
		// Call parent constructor
		super(text);

		// Create a new thread
		if (ownThread == null) {
			ownThread = new Thread(this, "Sum");
		}
	}

	// Call doSum with an array of numbers that you want to sum up and display
	public doSum(float[] nums) {
		numbers = nums;
		ownThread.start(); // this will call the run() method
	}

	public void run() {
		float sum = 0.0;

		// Add up all the numbers
		for (int i = 0; i < numbers.length; i++) {
			sum += numbers[i];
		}

		// Display the result
		setText("Sum: " + sum);

		// This function exits and the thread dies
	}
}

Synchronizing Threads

Please see the section entitled Synchronizing Threads .

Synchronization is basically this: If you have two threads that are using a shared resource, you don't want them to both try accessing the shared resource simultaneously or else Bad Things will happen. The two threads could very likely stomp all over the shared resource creating errors, memory violations, security holes, or even crashing your program. When two threads try to access a shared resource and end up stomping on each other, this is known as a race condition.

If you want to synchronize the activities of two methods that use a shared resource so they do not create a race condition, you use the synchronized keyword. You declare it as part of the functions decl-specifiers. See the Locking an Object section for details. In the most humble opinion of your instructor, this is one of the most elegant synchronization implementations that I have ever seen.

One of the keys to good synchronization is Avoiding Starvation and Deadlock , which the tutorial also addresses. Basically, you don't want to have two threads asleep, each one waiting for the other to wake up. Such an event is known as a deadlock Over-synchronizing your methods will do this.

Thread in Applets

It is likely that you would want to use threads in your Applets. For info on how to do this, please see the section entitled Threads in Applets

Exceptions

Recommended Reading

Please read the section in the turorial entitled Handling Errors with Exceptions.

Exception Concepts

Different programming languages handle errors in different ways. Some languages will return error codes, other languages will have you register callbacks to handle particular errors. The approach taken in Java is to use Exceptions.

For a good review of how exceptions work and what their advantages are, please read the What's an Exception and Why Do I Care section of the tutorial.

Handling Exceptions

Please look at the Catching and Handling Exceptions section of the tutorial for the straight dope on Exceptions.

Each package listed in the API will contain exceptions that are pertinant to the other classes in that package. Some of the most common, basic exceptions can be found in the java.lang package.

If you want a fairly comprehensive listing in the API of the various kinds of exceptions that might be thrown look at the page from the API entitled Uses of Class java.lang.Exception

Here's the skinny on dealing with exceptions:

For a comprehensive example of how all these blocks would be used in a hunk of code, please see Putting It All Together.

Throwing Your Own Exceptions

If you want to specify exceptions thrown by any of your own methods, you do so by putting the word throws after the method signature, followed by the various exceptions that it throws. Then, somewhere in your method body, you can call another method that would throw an exception and rather than having to handle it yourself, you can pass the exception right along. Think of it as "passing the buck".

See Specifying the Exceptions Thrown by a Method for a code example.

Alternatively, you can make your own exceptions, very likely as a derivitive of an existing exception class, and throw them. To do that, you type throw CustomExceptionName at the point where an error would occur.

When you are reading the API documentation, the exceptions thrown by various methods will be listed with the signature so you know when you need to add catch blocks.

Applet Parameters

For the skinny on applet parameters, see the Using the <APPLET> Tag section of the tutorial.

Similar to command-line parameters, you can pass values to an applet via the <PARAM NAME=parmname VALUE=parmvalue> tag that goes inside the opening and closing APPLET tags.

To retrieve the values of various parameters in your Applet, you use the getParameter(String name) method. Please look at the Writing the Code to Support Parameters section of the tutorial for info on how to do this. There is also a getParameterInfo() method that your Applet should override to return a list of the parameters it will accept. There is no method in an applet for returning the total number of parameters. Kind of a bummer, huh?

Applet Parameter Example

If you're interested in seeing an example of a very configurable "linkbar" Applet which does pop-up menus, look at UserFriendly on the left-hand side of the home page.


Changelog

3/8/99 - Initial Revision