Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - can we have a weak thread?

Can we have a weak reference to a running thread to be terminated in low performance of CPU?

I mean, does something like this work?

WeakReference<Thread> ref = new WeakReference<Thread>(new Thread(){
    public void run(){
        while(true){ /* your code */ }
    }
});

In that way, I want a thread to have low priority to be executed, I mean when the CPU performance is LOW and CPU is engaged completely, the thread's execution be terminated automatically.

There are some threads which are NOT in high priority and should be interrupted and terminated in low CPU performance.

like image 694
user3840019 Avatar asked Aug 23 '16 09:08

user3840019


1 Answers

This is not achievable via weak references in the way you describe. This article defines weak references nicely so you may be interested in this: weak reference

There are two problems you need to solve for this, easy and not so easy one. I don't think there is anything within standard Java API for this.

Easy one - terminate "low" priority threads:

Simple way to achieve desired behavior would be to register Runnable instances of a low priority, according to your application rules, to some kind of state manager. These instances would implement some kind of stop(), and optionaly pause() and resume() behavior and expose it to the state manager that could stop all the instances on some kind of signal. You could simply check some volatile boolean in run() loop for this.

Not so easy one - determine CPU usage

Either use JNI or some kind of third party library such as one of these: How to monitor the computer's cpu, memory, and disk usage in Java?

You could periodically check for resource consumption via step 2, and if you determine there is something fishy going on notify state manager to shutdown low priority tasks.

like image 148
John Avatar answered Oct 06 '22 01:10

John