CountDownLatch

This is used to synchronize one or more tasks by forcing them to wait for the completion of a set of operations being performed by other tasks. You give an initial count to a CountDownLatch object, and any task that calls await on that object will block until the count reaches zero. Other tasks may call countDown on the object to reduce the count, presumably when a task finishes its job. A CountDownLatch is designed to be used in a one-shot fashion the count cannot be reset. If you need a...

Radio buttons

The concept of radio buttons in GUI programming comes from pre-electronic car radios with mechanical buttons When you push one in, any other buttons pop out. Thus, it allows you to force a single choice among many. To set up an associated group of JRadioButtons, you add them to a ButtonGroup you can have any number of ButtonGroups on a form . One of the buttons can be optionally set to true using the second argument in the constructor . If you try to set more than one radio button to true, then...

Arrays and generics

In general, arrays and generics do not mix well. You cannot instantiate arrays of parameterized types Peel lt Banana gt peels new Peel lt Banana gt 10 Illegal Erasure removes the parameter type information, and arrays must know the exact type that they hold, in order to enforce type safety. However, you can parameterize the type of the array itself arrays ParameterizedArrayType.java public T f T arg return arg public static lt T gt T f T arg return arg public class ParameterizedArrayType public...

Dynamic type safety

Because you can pass generic containers to pre-Java SE5 code, there's still the possibility that old-style code can corrupt your containers. Java SE5 has a set of utilities in java.util.Collections to solve the type-checking problem in this situation the static methods checkedCollection , checkedList , checkedMap , checkedSet , checkedSortedMap and checkedSortedSet . Each of these takes the container you want to dynamically check as the first argument and the type that you want to enforce as...

State machines with enums

Enumerated types can be ideal for creating state machines. A state machine can be in a finite number of specific states. The machine normally moves from one state to the next based on an input, but there are also transient states the machine moves out of these as soon as their task is performed. 2 Projects are suggestions to be used for example as term projects. Solutions to projects are not included in the solution guide. There are certain allowable inputs for each state, and different inputs...

PriorityBlockingQueue

This is basically a priority queue that has blocking retrieval operations. Here's an example where the objects in the priority queue are tasks that emerge from the queue in priority order. A PrioritizedTask is given a priority number to provide this order import java.util.concurrent. import java.util. import static net.mindview.util.Print. class PrioritizedTask implements Runnable, Comparable lt PrioritizedTask gt private Random rand new Random 47 private static int counter 0 private final int...

DelayQueue

This is an unbounded BlockingQueue of objects that implement the Delayed interface. An object can only be taken from the queue when its delay has expired. The queue is sorted so that the object at the head has a delay that has expired for the longest time. If no delay has expired, then there is no head element and poll will return null because of this, you cannot place null elements in the queue . Here's an example where the Delayed objects are themselves tasks, and the DelayedTaskConsumer...

Lockfree containers

As emphasized in the Holding Your Objects chapter, containers are a fundamental tool in all programming, and this includes concurrent programming. For this reason, early containers like Vector and Hashtable had many synchronized methods, which caused unacceptable overhead when they were not being used in multithreaded applications. In Java 1.2, the new containers library was unsynchronized, and the Collections class was given various static synchronized decoration methods to synchronize the...

Collection vs Iterator

Collection is the root interface that describes what is common for all sequence containers. It might be thought of as an incidental interface, one that appeared because of commonality between other interfaces. In addition, the java.utiLAbstractCollection class provides a default implementation for a Collection, so that you can create a new subtype of AbstractCollection without unnecessary code duplication. One argument for having an interface is that it allows you to create more generic code....

Bounds

Bounds were briefly introduced earlier in the chapter see page 652 . Bounds allow you to place constraints on the parameter types that can be used with generics. Although this allows you to enforce rules about the types that your generics can be applied to, a potentially more important effect is that you can call methods that are in your bound types. Because erasure removes type information, the only methods you can call for an unbounded generic parameter are those available for Object. If,...

Deadlock

Now you understand an object can have synchronized methods or other forms of locking that prevent tasks from accessing that object until the mutex is released. You ve also learned that tasks can become blocked. Thus it s possible for one task to get stuck waiting for another task, which in turn waits for another task, and so on, until the chain leads back to a task waiting on the first one. You get a continuous loop of tasks waiting on each other, and no one can move. This is called deadlock.21...

Simplifying tuple use

Type argument inference, together with static imports, allows the tuples we saw earlier to be rewritten into a more general-purpose library. Here, tuples can be created using an overloaded static method Tuple library using type argument inference. public static lt A,B gt TwoTuple lt A,B gt tuple A a, B b return new TwoTuple lt A,B gt a, b public static lt A,B,C gt ThreeTuple lt A,B,C gt tuple A a, B b, C c return new ThreeTuple lt A,B,C gt a, b, c public static lt A,B,C,D gt FourTuple lt...

Buttons

Swing includes a number of different types of buttons. All buttons, check boxes, radio buttons, and even menu items are inherited from AbstractButton which, since menu items are included, would probably have been better named AbstractSelector or something equally general . You ll see the use of menu items shortly, but the following example shows the various types of buttons available gui Buttons.java Various Swing buttons, import javax.swing. import javax.swing.border. import...

Interfaces and factories

An interface is intended to be a gateway to multiple implementations, and a typical way to produce objects that fit the interface is the Factory Method design pattern. Instead of calling a constructor directly, you call a creation method on a factory object which produces an implementation of the interface this way, in theory, your code is completely isolated from the implementation of the interface, thus making it possible to transparently swap one implementation for another. Here s a...

Filling containers

Although the problem of printing containers is solved, filling containers suffers from the same deficiency as java.utiLArrays. Just as with Arrays, there is a companion class called Collections containing static utility methods, including one called fill . Like the Arrays version, this fill just duplicates a single object reference throughout the container. In addition, it only works for List objects, but the resulting list can be passed to a constructor or to an addAll method The...

A display framework

We can combine the ideas above and reduce redundant code by creating a display framework for use in the Swing examples in the rest of this chapter net mindview util SwingConsole.java Tool for running Swing demos from the console, both applets and JFrames. package net.mindview.util import javax.swing. public class SwingConsole public static void 5 This practice was added in Java SE5, so you will see lots of older programs that don t do it. That doesn t mean the authors were ignorant. The...

Immutable Strings

Objects of the String class are immutable. If you examine the JDK documentation for the String class, you ll see that every method in the class that appears to modify a String actually creates and returns a brand new String object containing the modification. The original String is left untouched. import static net.mindview.util.Print. public static String upcase String s return s.toUpperCase public static void main String args String q howdy print q howdy String qq upcase q print qq HOWDY...

Dynamic proxies

Proxy is one of the basic design patterns. It is an object that you insert in place of the real object in order to provide additional or different operations these usually involve communication with a real object, so a proxy typically acts as a go-between. Here s a trivial example to show the structure of a proxy typeinfo SimpleProxyDemo.java import static net.mindview.util.Print. interface Interface void doSomething void somethingElse String arg class RealObject implements Interface public...

Faster execution

The speed issue sounds simple at first If you want a program to run faster, break it into pieces and run each piece on a separate processor. Concurrency is a fundamental tool for multiprocessor programming. Now, with Moore s Law running out of steam at least for conventional chips , speed improvements are appearing in the form of multicore processors rather than faster chips. To make your programs run faster, you ll have to learn to take advantage of those extra processors, and that s one thing...

Daemon threads

A daemon thread is intended to provide a general service in the background as long as the program is running, but is not part of the essence of the program. Thus, when all of the non-daemon threads complete, the program is terminated, killing all daemon threads in the process. Conversely, if there are any non-daemon threads still running, the program doesn t terminate. There is, for instance, a non-daemon thread that runs main . Daemon threads don t prevent the program from ending. import...

Coding variations

In the examples that you ve seen so far, the task classes all implement Runnable. In very simple cases, you may want to use the alternative approach of inheriting directly from Thread, like this concurrency SimpleThread.java Inheriting directly from the Thread class. public class SimpleThread extends Thread private int countDown 5 private static int threadCount 0 public SimpleThread Store the thread name super Integer.toString threa start return getName System.out.print this if --countDown 0...

Complete decoupling

Whenever a method works with a class instead of an interface, you are limited to using that class or its subclasses. If you would like to apply the method to a class that isn t in that hierarchy, you re out of luck. An interface relaxes this constraint considerably. As a result, it allows you to write more reusable code. For example, suppose you have a Processor class that has a name and a process method that takes input, modifies it and produces output. The base class is extended to create...