Task Queue for Heavy Weight Tasks in JavaSE Applications

Modern hardware systems have a multi-core architecture. So in contemporary software development concurrency is an even more crucial ingredient than before. But as we will see it is of great importance for single core systems, too. If you have already created a Java Swing application you’ve propably made an acquaintance with the SwingWorker, in order to delegate long running tasks from within Swing events to another thread. But first things first. In Swing the whole painting and event handling of the graphical user interface is executed in one thread the so called event dispatching-thread from AWT the underlying former window toolkit from Java. Therefore most of Swing-based methods are not thread-safe, meaning that you have to prevent race conditions by yourself, but it offers the possibility to dispatch tasks to the event-dispatcher thread. It is highly recommended to do everything, that updates the GUI in the corresponding thread.

This works as follows. The event dispatcher maintains a queue in which all UI-Events and external runnables, submitted via SwingUtilities#invokeLater() or SwingUtilities#invokeAndWait(), are enqueued and executes them one by one:
The Event Dispatching Queue

If you have a long-running task, like searching a file on the hard drive, being invoked by an event, e.g., a button click, you should not do this in the event-handling code, since you would block the whole queue until the task is finished leading to an unresponsive GUI experience. This is also true for single-core machines. Lets take a look at this. Imagine you have a machine with one core and you are executing a task like mentioned before. If you are doing this in the queue, you won’t be able to cancel the task or to do anything on the GUI. It will freeze. But good GUIs don’t freeze, even on single-core machines. Why is that? If you dispatch this task to another thread and w.l.o.g it iterates through a big loop, then you may call Thread#yield() in every iteration, in order to give the Java VM a hint that it can suspend this thread and give some calculation capacity to the GUI thread. In addition if it waits for example for an I/O-operation, the GUI thread can process some GUI events. Since Java is preemptive (on most machine/operating system combinations), it can (even without ‘yield’-hints) interrupt the external thread at any time, in order to give the dispatcher thread some time and vice versa. So this is (on single-core machines) not real concurrency, but it allows both threads to work alternatingly, which appears to be concurrent. This especially applies for multi-core machines. Furthermore the external task can check for Thread#isInterrupted() or if it waits, e.g., for interruptable I/O operations it can react to cancel-events of the user and terminate the execution prematurely. Here is a code example:

while(!finished) {
  if(Thread.interrupted()) {
    cleanup();
    return;
  }
  doStuff();
  Thread.yield();
}

It is of fundamental significance, that you program long-running tasks this way. If you counteract, you provoke tasks that cannot be canceled, leading to annoying system behavior. The tenet reads: The longer the task, the more eager it should be to react to cancellation.

Analogous to dispatching external execution to the swing thread by enqueuing it, long-running tasks should be send to external threads. For this purpose the Swing Worker has been developed and since Java 5 it is an integral part of the JRE and evolved in Java 6. With the SwingWorker you can execute a task in another thread and relieve the event dispatcher. In the early versions of the Swing Worker it started new threads for every execution and had no support for getting intermediate progress from it conveniently and show it, e.g., in a progress bar. So I implemented a second queue for executing long-running tasks on an external thread for Java 1.4.2. Lateron I refined it by using the ExecutorService of Java 5. Now in Java 6, the Swing Worker uses an ExecutorService by itself with a fixed number of worker threads and offers very convenient features for updating the GUI with progress and canceling an execution.

Was it worth implementing my own heavy weight task executor? Yes! Since the SwingWorker starts a fixed number of worker threads, that cannot be configured there might arise race conditions between the data structures and resources accessed in the external tasks. If you are a fan of the one-thread-philosophy of Swing, because it naturally serializes/sequentializes the access to the resources you may use a second queue for these tasks and exchange tasks between the GUI thread and the external thread. In this sense, long-running tasks are sent to the heavy weight task executor and GUI updates — like progress updates — are sent back.

How this can be achieved will be the topic of another post (as usual with a running code example for a rudimentary heavy weight task executor).

Posted in Java, Knowledge. Tags: , , . No Comments »

Circular Injection of Util Classes in EJB 3.0

In my last post Circular Dependencies of Session Beans I presented a method to use interceptors in session beans in order to inject beans. This works great until you want to add circular dependencies. Then you have to look up the beans by name and inject them into the bean. But this is kind of cumbersome. So, if it is possible, have a bean structure, which is topologically sortable and inject util classes having circular dependencies between each other. This post shows how to achieve the latter.
(more…)

Ordering Collections with JPA

Often there is the need to sort an entity or a collection, e.g. If you have a list of line items in a bill and do not want that the order may change or is semantically wrong. Unfortunately, using a java.util.List will not suffice, since the DB has not to retain the order of the list. You might recognize this only after a long time, since some RDBMS will return the rows by insertion order. There are different ways to introduce an ordering with JPA (see Java Persistence: Ordering).
(more…)

Posted in Java, Knowledge. Tags: , , . No Comments »

Override fetch type in JPQL Queries

Executing a getter — representing a one-to-many or many-to-many association — on an entity causes one or n (with n entries in the collection) database calls, depending on the fetching strategy (see fetch strategies). This is a nasty little detail that may cause performance bottlenecks. Changing the fetch type (lazy/eager) may not be appropriate, since an association is generally used in more than one context, so there may be contradictory concerns. Generally spoken, an eager fetching is only in rare occasions a good idea on one-to-many or many-to-many associations, since this leads to the cartesian product problem (simply put, you have to read [nearly] the hole db in order to get one entity). Fortunately there is another solution that enables overriding a lazy fetch type in a dedicated JPQL-Query. This may entail a hole bunch of JPQL queries you will have to write (not more queries to execute on the db!!!), since you want to eagerly fetch an association in one situation but not in another.
(more…)

Posted in Java, Knowledge. Tags: , , , , . No Comments »

Unnecessary Code Detector

Recently I found a nice eclipse plugin for finding dead code. The standard eclipse check finds unused private fields and methods, only. You may use STRG+SHIFT+G for finding references to a public class or method in advance. But this approach is limited to search for methods/classes without references one by one, which is very time consuming. The UCDetector starts a search for methods and classses without any references to it in all projects in the current workspace respecting inheritance and presents the results in the ‘Problems’ view. (more…)

Posted in Java, Knowledge. Tags: , , . No Comments »

instanceof on Class objects

If you need to access the metadata of a class or be a bit less type safe than Java is by itself, you will have to get involved with the Java Reflection API.  At that the question may arise, how to check whether one class object is the super class of another. If you are working with objects, you may use the java keyword instanceof. But this won’t work as expected for class objects, since all class objects are instances of Class<?> . So Class<?> owns the method cls1.isAssignableFrom(cls2), checking whether cls1 is a super class/interface or the same as cls2. So it works just like instanceof on objects, but the order of the parameters is switched.

Bug in JDK Javadoc for class java.util.regex.Pattern

The Javadoc for class java.util.regex.Pattern contains a bug. It says that a back reference (Pattern (Java Platform SE 6)) to a capturing group is depicted by \n whereas n denotes the number of the capturing group. Unfortunately this won’t work. Use $n instead.
(more…)

Remote debugging with Java Virtual Machine

In order to remote debug a JVM export the following java options:

export JAVA_OPTS="-Xdebug -Xrunjdwp:transport=dt_socket,address=8888,server=y,suspend=n -XX:MaxPermSize=1024m"

I got this information from this site http://ztiromoritz.wordpress.com/2009/08/03/java-remote-debugging/.

After exporting these java options in the shell where you start the jvm you like to debug, you can use your favorite IDE to connect to port 8888 at localhost in order to start debugging.

Posted in Tutorials. Tags: , , . 2 Comments »

Standalone Tomcat with jBoss plus authentication against LDAP

There is a 2nd edition of this post: Standalone Tomcat with jBoss (2nd Edition)!
This tutorial desribes, how to install and configure a standalone Tomcat, so that a deployed webapp can authenticate against LDAP and connect to a jBoss passing the credentials in every call of an EJB via remote interface , so that the business application can authenticate against the same LDAP, too. The configuration of the jBoss seems to be a more common and better documented task and will be covered in another tutorial, which I will link here later, as soon as I have written it.

WARNING: Please don’t use this solution in a productive system, but for testing purpose only. The custom LdapExtLoginModule presented here exposes the credentials of all online users to all classes using the same class loader! I will add a blog post, as I find a solution for production systems.
(more…)

Switch to our mobile site