[jdom-interest] Code to reproduce threading bug

Eric Burke burke.eric at gmail.com
Tue Dec 16 14:21:39 PST 2008


This quick and dirty hack demonstrates the threading bug in Namespace.java
that I posted earlier today. If I run this several times, it eventually
hangs forever.

By adding the synchronized keyword to the Namespace.getNamespace(...)
method, the program seems to always work.



import org.jdom.Namespace;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class JdomThreadBug {

    public static void main(String[] args) throws InterruptedException {
        ExecutorService es = Executors.newCachedThreadPool();

        int numThreads = 100;
        CountDownLatch startLatch = new CountDownLatch(1);
        for (int i = 0; i < numThreads; i++) {
            es.submit(new Namespacer(i * 10, i * 10 + 10, startLatch));
        }

        startLatch.countDown();
        System.out.println("*** DONE ***");
        es.shutdown();
    }

    private static class Namespacer implements Runnable {
        private final int min;
        private final int max;
        private final CountDownLatch startLatch;

        private Namespacer(int min, int max, CountDownLatch startLatch) {
            this.min = min;
            this.max = max;
            this.startLatch = startLatch;
        }

        public void run() {
            try {
                startLatch.await();
                for (int i = min; i < max; i++) {
                    String prefix = "p" + i;
                    String uri = "u" + i;
                    System.out.println("Getting namespace " + prefix + ":" +
uri);
                    Namespace.getNamespace(prefix, uri);
                    System.out.println("Got namespace " + prefix + ":" +
uri);
                }
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}


-- 
Eric M. Burke
http://www.linkedin.com/in/ericburke
314-494-3185 (mobile)
636-272-3298 (home)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.jdom.org/pipermail/jdom-interest/attachments/20081216/831e12fc/attachment.htm


More information about the jdom-interest mailing list