M
M
Marat2016-01-05 14:37:52
Java
Marat, 2016-01-05 14:37:52

How to limit a function (by time and memory)?

Good afternoon!
If it is possible at all (for example, to calculate the minima of functions by different methods)...

public class C1
{
...
    public void f1(ArrayList<Integer> al1)
    {...

1. Is it possible to call f1 in such a way as to forcibly interrupt its call after 10 seconds, while it returned the values ​​​​calculated up to that moment in al1?
2. Limit consumed memory resources when calling f1
I know what can be passed in the parameters of a function call, but consider the case of "abuse" and the need for forced restriction.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
E
Evhen, 2016-01-05
@Joysi75

I can help you with the first point.
Run the function as a separate thread and check for each operation

Thread t = new Thread.... {

if (Thread.interrupted()) {
// сохранить текущий результат и выйти из метода
}
});;

t.start();

t.join(10000); // ждем поток 10 сек

t.interrupt(); // предлагаем потоку прервать выполнение

C
cthulhudx, 2016-01-06
@cthulhudx

1) As Sirikid said - "it's better to rewrite the function so that it would return a sorted list"

class SomeClass {
public List<Integer> calculate() {
List<Integer> results = new ArrayList<>();
//Выполняем вычисления, заполняем коллекцию
return Collections.sort(results);
} 
...

2) You can limit the memory consumed by the virtual machine using the Xms and Xmx keys (it does not work on all jvms). It is not possible to limit the resources consumed by one method .

D
Deerenaros, 2016-01-06
@Deerenaros

1) You can bike on streams , ala Eugene , you can use ready- made ala Sirikid .
2) We make our own resource manager, which limits the number of created arrays. Of the minuses - you have to use this manager, which is never convenient (the code swells), and even without the native it will be quite difficult to control the memory. But theoretically it is possible.
3) Why this is necessary - remains open. If you are not sure that the task will be completed on time, then you are a bad programmer. If you are sure that the task will not be completed on time, then you need to look for another solution. Including the potential rejection of Java, which itself eats up extra resources.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question