Jaanus
Jaanus

Reputation: 16541

OSGi threads never stop running, defining fixed lifetime for threads

I havea threadpool of 5, which I keep in array:

private static final Collection<Thread> workerThreads = new ArrayList<Thread>();

But when I reupload my osgi plugin, the threads keep running, but the array will be empty, so it will be populated with new 5 threads. So eventually I have tons of threads running.

My thread pool is designed to run forever, they just stay idle and wait for jobs to come into queue.

while (!queue.isEmpty()) {
        try {
            Job takenJob = queue.poll(5000, TimeUnit.MILLISECONDS);
            if (takenJob != null) {
                takenJob.execute();
            }
        } catch (InterruptedException e) {
            log.error("ERROR", e);
        }
    }

So basically the problem is, that after I reupload my osgi project, I will lose reference to old threads.

Possible solution: I need to define a lifetime for threads, so I don't have a pool, but each thread will live ~15 minutes and then end. Meanwhile new threads a being created every 15 minutes so I will always have some thread looking at the queue.

Just using standard java.util.Date getTime() seems like not best way. Any suggestions how to implement this?

Upvotes: 0

Views: 726

Answers (2)

Peter Kriens
Peter Kriens

Reputation: 15372

The best solution is to use an ExecutorService and close it when the bundle ends. The https://github.com/bndtools/bndtools-rt project contains an bundle that registers such an executor as a service, ensuring all life cycles issues are properly addressed.

Upvotes: 2

Balazs Zsoldos
Balazs Zsoldos

Reputation: 6046

You must finish your threads and release every resources when the bundle is stopping. You can do it for example in the BundleActivator stop method.

In case you have new threads you should also be sure that the threads finish their job before the stop function returns. This means that if your jobs need to run for a long time before finish (e.g. due to an iteration) they should be designed in a way that they can be interrupted.

Upvotes: 2

Related Questions