Short answer: None . Sorry
There is no such mechanism in the standard API, and you cannot use WeakReference to create such a thing, because links refer only to the reachability of objects, and not to processor activity.
But this does not mean that the analogy is not neat, and this does not mean that this is a bad idea! I like it.
Hope you need to assign a low priority to the thread - but as noted elsewhere, this is subtle and quick anger. A low priority thread should give way to higher priorities and would be suitable for a while-loop thread. The dangers are that different OS scheduling systems can cause your low-priority thread to starve, especially if you are not too careful that higher priority threads are allocated from time to time. You can find wild variable behavior on multiprocessor processors and on individual processors.
Given that you want the task to actually stop when the processor loads ... you could use System.nanoTime() to execute each loop pass, and if it exceeds a threshold, then exit the while loop. I donβt like it very much: it is susceptible to GC pauses and natural changes leading to termination.
Alternatively, you can use JMX to measure the actual processor load, see How to get the percentage of OS processor utilization from java - and break the while loop if it exceeds the threshold value. You may have a monitoring thread that calls Thread.interrupt () for your worker to abort any blocking actions. I can imagine that you would spend your whole life setting it up - too impatient in some circumstances, too lethargic in others; wildly varying on different host sizes.
And if you want to kill threads while they actually work ... it starts very hard. I'm starting to think that there may be other approaches, but it's hard to say without knowing more about the wider problem you are trying to solve.
Still neat.
source share