Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7053987
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 28, 20262026-05-28T03:34:17+00:00 2026-05-28T03:34:17+00:00

In my application I have a wrapper over some native code, which is called

  • 0

In my application I have a wrapper over some native code, which is called via JNI bridge. This native code needs to be executed in separate thread (parallel processing). However the problem is that the code sometimes “hangs” so the thread needs to be terminated “by force”. Unfortunately I haven’t found any “delicate” method to do so: general advise is to tell the code in a thread to exit gracefully, but I can’t do it with this native code (which is 3rd party code all above).

I use Java Concurrent API for task submission:

Future<Integer> processFuture = taskExecutor.submit(callable);

try {
    result = processFuture.get(this.executionTimeout, TimeUnit.SECONDS).intValue();
}
catch (TimeoutException e) {
    // How to kill the thread here?
    throw new ExecutionTimeoutException("Execution timed out (max " + this.executionTimeout / 60 + "min)");
}
catch (...) {
    ... exception handling for other cases
}

Future#cancel() will only interrupt the thread, but it will not terminate it. So I used the following trick:

class DestroyableCallable implements Callable<Integer> {

    private Thread  workerThread;

    @Override
    public Integer call() {
        workerThread = Thread.currentThread();

        return Integer.valueOf(JniBridge.process(...));
    }

    public void stopWorkerThread() {
        if (workerThread != null) {
            workerThread.stop();
        }
    }
}

DestroyableCallable callable = new DestroyableCallable();

Future<Integer> processFuture = taskExecutor.submit(callable);

try {
    result = processFuture.get(this.executionTimeout, TimeUnit.SECONDS).intValue();
}
catch (TimeoutException e) {
    processFuture.cancel(true);
    // Dirty:
    callable.stopWorkerThread();

    ThreadPoolTaskExecutor threadPoolTaskExecutor = (ThreadPoolTaskExecutor) taskExecutor;

    logger.debug("poolSize: " + threadPoolTaskExecutor.getPoolSize() + ", maxPoolSize:"
                    + threadPoolTaskExecutor.getMaxPoolSize() + ", activeCount:"
                    + threadPoolTaskExecutor.getActiveCount());
    }

    throw new ...;
}
catch (...) {
    ... exception handling for other cases
}

The questions/problems with this code:

  • Is it in general the right way to do so? Any other more elegant alternatives?
  • activeCount on task executor is not decreased, so task executor still “thinks” that thread is running
  • I had to add workerThread != null check to stopWorkerThread() method, as this variable turned out to be null on some case. I can’t understand what are these cases…

Notes:

  • Native code does not consume file descriptors (sockets). Everything is passed to it as block of data and returned the same way.
  • Native code is CPU-intensive. Even though it guarantees to terminate, it may take a long time.

Bounty edit: The approach/suggestion to revisit the native code is clear, please do not offer it in your reply. I need pure-Java solution / workaround.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-28T03:34:17+00:00Added an answer on May 28, 2026 at 3:34 am

    Java has pure options for force thread termination. It is ancient and deprecated Thread.stop() only (AFAIK). And no option for safe thread termination (what is why .stop() was deprecated, and allowed to be even not implemented by JVM implementors).

    The reason is what all threads inside app shares memory and resources — so, if you force termination of thread in some arbitrary point, you can’t prove for sure what terminated thread does not left some shared memory/resources in inconsistent state. And you even can’t (in general) suppose which resources are (possibly) dirty (‘cos you dont know exactly at which point thread was stopped).

    So, if you want some threads of your app to be able to interrupt, the only solution is to provide — at design phase — some notation of “savepoints” — locations in target thread’s code, which are guaranteed to not mutate shared state, so it is safe for thread to exit here. And it is exactly what Thread.stop() javadocs are telling you: the only way to interrupt thread safely is to design thread’s code so it can by itself response to some kind of interrupt request. Some kind of flag, which is checked by thread from time to time.

    I’ve trying to tell you: you can’t do the thing you’re asked about using java threading/concurrency. The way I may suggest you (it was given early here) is to do your job in separate process. Forcibly kill process is much more safe then thread since 1) processes are much more separated from each other and 2) OS takes care about many cleanups after process termination. Killing process is not completely safe, since there exists some kind of resources (files, for example) which is not cleared by OS by default, but in your case it seems to be safe.

    So you design small separate application (may be even in java — if your third-party lib does not provide other bindings, or even in shell-script) which only job is to make you computation. You start such process from main app, give it the job, and start watchdog. It watchdog detects timeout — it kills process forcibly.

    This is the only draft of solution. You can implement some kind of processes pool, if you want to improve performance (starting process may takes time), and so on…

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

In my console application have an abstract Factory class Listener which contains code for
I have application which needs to use a dll (also written by me) which
I have a wrapper managed application(.net) over a COM Component(created using vb6) where Com
I have some wrapper code that runs a set of NUnit tests that scan
I have a small command-line application written in C that acts as a wrapper/launcher
I see an application have used Log.info = some info where are these logs
I have a Delphi application that I have written a fairly simple wrapper .exe
we have a customer that's been experiencing some blocking issues with our database application.
We have an application where a log message without the context in which it
I'm writing some Scala code which uses the Apache POI API. I would like

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.