On Java Threads: A fairytale of a tutorial
I always thought that the Java Thread API is something… strange. If you work in a frontend application, things like running long-running tasks in the back without having the GUI ugly frozen and not responding should be somewhat simpler.
SwingWorker has been around for quite a time but made it just recently into the core API (Java6). Furthermore i don’t think that it’s the right thing for performing enduring tasks like checking for mail and pushing a result with a second thread into a database, for example.
Don’t get me wrong, i use SwingWorker quite often, but it didn’t fit my needs and furthermore, i wanted to learn more about Java Threads.
My goal / task was a little daemon that regularly checks an email account and a samba share for some files, load them into an Oracle Database and executes a longer running db procedure. The checking should be suspendable and stoppable independently, the configuration should be reloadable.
I throw some interfaces and abstract classes at the vm and boom, it was that simple 😉
Things i’ve learned:
- Always start the GUI in it’s own thread, never use the main thread. Sure, most programs will work fine, but it can get confusing. Use SwingUtilities to do so.
- A thread once terminated is not reusable. Never ever. So don’t interrupt them if you plan on resume them later.
- Know the primitives, i.e. build in locks (synchronized and wait())
- Know the task scheduling frameworks (Executors and ExecutorServices)
- Read the tutorials here, here and maybe here
The following demo can start 7 producers and one consumer, both are synchronized via a BlockingQueue (i actually used a SynchronousQueue at work, as the files must only be removed if they were taken by the db). Both the producers and consumers can be suspended, resumed and stopped. I never ever will start a thread by hand again if not necessary. The threads are managed by an ExecutorService.
For the tasked mentioned above this thing works fine. If anyone comes up with a better idea, let me know.
I had fun to write it, maybe you have fun to read. Be aware, the program is not a good example of organizing classes, i put everything in one file just for the sake of being a demo.
But apart from that, the demo could serve as an example of what came to Java with Java 5 and 6 as i use a lot of generics, enums and enhanced for loops, in case you haven’t seen this.
To compile and run the stuff you need at least a Java5 JDK (get it here, download this file JThreadDemo.zip, unzip it and type
javac snow/white/JThreadDemo.java java snow.white.JThreadDemo
If you read this, i’ll guess you’re familiar with the JDK, java packages and the whole crap.
Get the whole fun after the click: