Showing posts with label concurrency. Show all posts
Showing posts with label concurrency. Show all posts

Saturday, 24 January 2009

Getting Groovy with SwingWorker TV

javax.swing.SwingWorker is the generic type for SwingWorker, which came in Java 1.6. Various incarnations of the SwingWorker existed prior to 1.6 though. T is the result type returned by various methods, and V is the type used for carrying out various intermediate results. The class implements the RunnableFuture interface.

The primary purpose of a SwingWorker is to do lengthy GUI-interacting tasks in a dedicated thread. Subclasses of SwingWorker must implement the doInBackground() method to perform background computation.

The concept of a Future<V> is an asynchronous computation. Methods exist to check if the computation is complete, to wait for completion and retrieve the result of the computation.

A FutureTask<V> is a cancellable asynchronous computation. This class also implements the RunnableFuture interface.

Thursday, 8 January 2009

the joys of java.util.concurrent

Since java ONE-FIVE we have had the java.util.concurrent package, which introduced the remarkable BlockingQueue interface (which extends java.util.Queue). The "B&Q" interface has a wide range of implementations:
  • ArrayBlockingQueue
  • DelayQueue
  • LinkedBlockingQueue (a bq based on linked nodes)
  • PriorityBlockingQueue
  • SynchronousQueue

An ArrayBlockingQueue is a BOUNDED blocking queue backed by an array. It orders elements using FIFO discipline. This is the classic "bounded buffer" in which a fixed-size array holds elements inserted by producers and extracted by consumers. The head of the queue is the element that has been on the queue the longest time.

These data structures are all part of the wonderful Java Collections Framework. Enjoy the benefits of enhanced-for loop, generics and auto-boxing.

Here's a precanned example of enhanced-for-loop in action, utilising the colon operator:

void cancelAll(Collection c) { for (TimerTask t : c) t.cancel();}