Answer the question
In order to leave comments, you need to log in
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)
{...
Answer the question
In order to leave comments, you need to log in
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(); // предлагаем потоку прервать выполнение
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);
}
...
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 questionAsk a Question
731 491 924 answers to any question