Elettracompany.com

Компьютерный справочник
24 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Java util concurrent executionexception

Застрял с ошибкой исключения: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException 😕

Когда я строю проект, он показывает мне Exception, что «app: mergeDebugResources» я проверил весь свой код и build.gradle, а также файл манифеста; Я не мог понять, в чем главная проблема:

Ошибка: выполнение выполнено для задачи: app: mergeDebugResources Ошибка: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:

Вот мой самый мрачный файл:

И вот мой файл build.gradle: `

Я не использую jar-файл в lib в этом проекте. Заглядывая за некоторым полезным ответом. Заранее спасибо .

Я просто столкнулся с той же проблемой. Я удалил свой файл с возможностью рисования и попытался получить его один за другим и проверил. Я проверил XML-файл, где я его использовал, он показал мне ошибку:

Msgstr «Невозможно загрузить изображение».

Итак, проблема в изображении, я просто заменил старый на новый образ, и он работает!

Я просто столкнулся с той же проблемой. Я случайно удалил свой файл с возможностью рисования и попытался получить его, выполнив Ctrl + z. Я проверил файл xml, где я его использовал, он показал мне ошибку «Не удалось загрузить изображение». Итак, это проблема с изображением, я просто удалил старый и загрузил новый. Это сработало !

У меня была эта проблема.

После некоторого расследования я обнаружил, что это 9 патч-изображений, которые были добавлены в папку ресурсов. Проблема заключалась в том, что на этом 9 патче я добавил прозрачность, по ошибке, на контрольную границу (эти черные границы).

Итак, после исправления 9 патчей, что означает удаление прозрачности, проблема была решена.

В проект добавлено 9 патч-изображений или проблемы с именами файлов в папке с возможностью переноса, попробуйте изменить скомпилированную версию и целевую версию и перестроить проект.

Я столкнулся с такой же проблемой вчера, это проблема с IDE, вероятно, потому, что Android Studio заставляет Gradle Support в проекте. Мне удалось работать с тем же проектом со свежими источниками для Eclipse . Вот журнал ошибок: https://s27.postimg.org/n6nlos2sz/Screenshot_64.png Надеюсь, это поможет.

Импорт в eclipse guide

Просто извлеките загруженный пакет и используйте опцию для импорта существующего проекта Android. Если он не настроен для Android SDK , перейдите к настройке и добавьте путь к SDK (это можно найти в опции Android Studio SDK Manager). Также проверьте, какая версия API ему нужна и установите ее из диспетчера SDK.
Если вы получили сообщение об ошибке: не удалось устранить целевую «Google Inc.: API Google: XX» , установите эту версию из SDK.
Не забудьте добавить пакет API Google в список пакетов, поскольку пакет платформы SDK отличается от пакета API Google API. ссылка -> [HTTPS] s24 [точка] postimg [точка] орг / jq3bgwv39 / Screenshot_66.png
После этого удалите папку Workspace и попробуйте импортировать проект.

Ошибка: выполнение выполнено для задачи ‘: app: mergeDebugResources’.

Ошибка: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException:

Чтобы устранить описанные выше типы ошибок, перейдите в директорию «res» и проверьте доступные для загрузки файлы, drawable-XXXX и т. Д. Для возможных изображений .png. Удалите «.9» из изображений .png. Выполните «Build / Clean Project», за которым следует проект «Build / Rebuild».

Ну, я получил эту проблему, потому что мой проект был импортирован из Eclipse в Android Studio, и в gradle отсутствовали зависимости.

Я избавился от него после добавления

После этого мне пришлось установить

Кроме того, я добавил следующие строки

Надеюсь, это когда-нибудь поможет кому-нибудь. ура

Пожалуйста, проверьте, что в вашей папке с рисунком, если есть девять изображений патча, удалите их, а затем попробуйте. Это работает для меня одинаково.

Интерфейсы Callable и Future в Java

Интерфейс Java Callable(java.util.concurrent.Callable) представляет асинхронную задачу, которая может быть выполнена отдельным потоком. Например, можно передать объект Callable в Java ExecutorService, который затем выполнит его асинхронно. Метод call() вызывается для выполнения асинхронной задачи.

Интерфейс Callable довольно прост. Он содержит единственный метод с именем call().

Если задача выполняется асинхронно, результат обычно передается обратно через Java Future. Это тот случай, когда Callable передается в ExecutorService для одновременного выполнения.

Callable использует Generic для определения типа возвращаемого объекта. Класс Executors предоставляет полезные методы для выполнения Java Callable в пуле потоков. Поскольку вызываемые задачи выполняются параллельно, нам нужно дождаться возвращенного объекта.

Callable задачи возвращают объект java.util.concurrent.Future. Используя объект Java Future, мы можем узнать состояние задачи Callable и получить возвращенный объект. Он предоставляет метод get(), который может ожидать завершения Callable и затем возвращать результат.

Future предоставляет метод cancel() для отмены связанной задачи Callable. Существует версия метода get(), в которой мы можем указать время ожидания результата, поэтому полезно избегать блокировки текущего потока на более длительное время.

Существуют методы isDone() и isCancelled() для определения текущего состояния связанной вызываемой задачи.

Вот простой пример задачи с Callable, которая возвращает имя потока, выполняющего задачу через одну секунду. Мы используем платформу Executor для параллельного выполнения 100 задач и используем Java Future для получения результата представленных задач.

После того, как мы выполним вышеуказанную программу, вы заметите задержку вывода, потому что метод get() ожидает завершения задачи, вызываемой Java. Также обратите внимание, что есть только 10 потоков, выполняющих эти задачи.

Читать еще:  Javascript date parse

Вот фрагмент вывода вышеуказанной программы.

Mon Dec 31 20:40:15 PST 2012::pool-1-thread-1
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-3
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-4
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-5
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-6
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-7
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-8
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-9
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-10
Mon Dec 31 20:40:16 PST 2012::pool-1-thread-2
.

Что делать, если мы хотим переопределить некоторые методы, например, переопределить метод get() для тайм-аута через некоторое время по умолчанию, а не ждать бесконечно?

В этом случае пригодится класс Java FutureTask, который является базовой реализацией Future.

Callable против Runnable

Callable похож на Runnable в том, что оба они представляют задачу, которая предназначена для одновременного выполнения отдельным потоком.

Callable отличается от Runnable тем, что метод run() не возвращает значение и не может генерировать исключения (только RuntimeExceptions).

Runnable изначально был разработан для длительного параллельного выполнения, например, одновременный запуск сетевого сервера или просмотр каталога на наличие новых файлов. Интерфейс Callable больше предназначен для одноразовых задач, которые возвращают один результат.

Средняя оценка / 5. Количество голосов:

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

Пример использования ExecutorService

ExecutorService появился в Java 1.5 и предназначен для управления пулом потоков.

Есть несколько стандартных реализаций, которые можно получить из простой фабрики Executors:

  1. newFixedThreadPool
  2. newWorkStealingPool
  3. newSingleThreadExecutor
  4. newCachedThreadPool
  5. newSingleThreadScheduledExecutor
  6. newScheduledThreadPool

Догадаться об особенностях реализаций сервиса можно исходя из названий методов. В статье рассмотрен пример использования FixedThreadPool.

Для запуска приложения будем использовать Spring Boot:

Предположим, что клиентскому классу необходимо выполнить много работы, которую можно разделить на несколько независимых подзадач. Например, необходимо получить html-страницы по списку URL-адресов или обработать большой список строк:

Работа будет заключаться в приведении строк к верхнему регистру

Сохраним список работ, который необходимо провести, в виде List

Каждый элемент списка – это элементарная работа, реализация функционального интерфейса, которую необходимо выполнить запустив метод call. Но вместо ручного вызова мы создадим сервис, который будет управлять пулом потоков:

В параметре метода newFixedThreadPool мы указали значение 4, что задает размер будущему пулу потоков.

workService – это сервис Spring, который делает работу и выводит некоторую информацию для отладки:

Для наглядности добавим паузу при выполнении задачи в 1 секунду. Если задача будет выполняться слишком быстро, то executorService может не выделять дополнительные потоки для обработки и выполнит все задачи в одном потоке.

Запускаем выполнение списка задач методом executorService.invokeAll(), который возвращает список Future объектов. Сразу смапим все Future в интересующие нас String и выведем на экран:

Получившийся код класса клиента:

Запустим пример и посмотрим на вывод:

Из логов можно сделать следующие заключения:

  1. Сначала одновременно запустилось 4 потока на выполнение работ work1, work2, work3, work4
  2. Через секунду все 4 потока доделали работу и принялись выполнять work5, work6, work7, work8
  3. Еще через секунду потоки закончили выполнение второй четверки работ и два потока принялись выполнять последние две работы work9 и work10
  4. Получившийся список строк, как и список Future, является отсортированным, хотя это нигде не регламентировалось. Полагаю, не стоит надеяться, что список всегда будет отсортирован.
  5. На выполнение всех задач в 4 потока потрачено 3 секунды. 1 секунда – на первую четверку задач, 2 секунда – на вторую четверку задач, 3 секунда – на оставшиеся две задачи.

Архив с исходниками можно посмотреть на GitHub.

Добавить комментарий Отменить ответ

Для отправки комментария вам необходимо авторизоваться.

java.util.concurrent.RejectedExecutionException – How to solve RejectedExecutionException

In this example we are going to talk about java.util.concurrent.RejectedExecutionException . When using an Executor to run your threads, it might reach a state where it cannot run the task you asked him to. This can happen for a number of reason, as we will demonstrate in this example. It is worth noting that this is a java.lang.RuntimeException

1. A simple Executor Example

To demonstrate this exception we are going to create a simple Java application that uses a ThreadPoolExecutor to execute a number of worker threads. Let’s see how you can do that.

Here a simple worker thread:

An here is how you can use an ThreadPoolExecutor to create a number of threads to execute your tasks

If you run the program, this is the output:

Everything went normal at this point. We create a ThreadPoolExecutor with pool size of 3. This means that it will create 3 threads that will be charged with the execution of our tasks-workers. As we submit new tasks to the ThreadPoolExecutor , he will place them in a BlockingQueue, as some of its 3 threads might be currently occupied with other tasks and thus the new tasks will have to wait until one of these 3 threads becomes available. In this particular case we use an ArrayBlockingQueue of size 15, to do this job (for reason that should become clear later on). After that, we create 10 tasks and we submit them to out ThreadPoolExecutor .

Читать еще:  Java project structure

2. A simple case of RejectedExecutionException

One of the causes of RejectedExecutionException is when we try to execute a new task after we’ve shutdown the executor. When shutdown() is called upon an executor, older tasks might still progress, but it allows no more tasks to be submitted.

Let’s see what happens in the case where we violate this rule :

If you run the program, this is the output:

So when shutdown() is called, no more tasks are allowed to be executed. If that is not so, RejectedExecutionException is raised.

3. A second case of RejectedExecutionException

Another case of RejectedExecutionException , appears when an Executor cannot take any more tasks under its responsibility. This happens when the limit of its local “memory” is reached. In our case that “local” memory is an ArrayBlockingQueue of size 15. If we try to submit more tasks than the ArrayBlockingQueue can hold, then RejectedExecutionException arises.

Let’s see an example :

Now as you can, see our ArrayBlockingQueue can hold no more than 15 threads. But we submit to it 20 threads. And because we’ve introduced a bit of delay in the threads (with Thread.sleep() ), our 3 workers are occupied for sometime. So, our ThreadPoolExecutor has to put newly submitted tasks to the ArrayBlockingQueue , because they cannot be executed instantly. Consequently, when the submitted tasks are more than he can handle (more than 15), then RejectedExecutionException is thrown.

4. How to solve RejectedExecutionException

The first things you want to check are the two cases :

  1. Be careful not to submit new tasks after having called shutdown() on the Executor .
  2. Do not give the Executor more tasks than he can handle.

Not surprisingly, the second case can be easily resolved. You could just use a data structure that does not impose a size limit. For example a LinkedBlockingQueue . So if you still face this problem after using LinkedBlockingQueue , you should focus on the first case. If the first case is not the cause of your problem, then you should probably look for more complex problem. For example, your memory is filling up because some of your threads have deadlocked and the LinkedBlockingQueue keeps filling up, and don’t forget is still the limit of the available memory that the JVM has.

I want to focus a bit more o that second case, as it might be hidden often. Do not forget that it is possible to submit more that 15 tasks in the ThreadPoolExecutor even in the case where he uses the ArrayBlockingQueue , as long as you give it some time to complete some of the tasks before submitting new ones, so that the 3 workers smoothly consume the ArrayBlockingQueue and does not get clogged up.

Let’s see this example :

From the output, you can see that the program is executed normally.

You should be careful, because you might thing that your ThreadPoolExecutor can successfully take more than 15 tasks, but that is only because the are being progressively consumed by the 2 workers.

ExecutorService in Java

By Lokesh Gupta | Filed Under: Java Concurrency

Learn to use Java ExecutorService to execute a Runnable or Callable class in an asynchronous way. Also learn the various best practices to utilize it in most efficient manner in any Java application.

1. What is Executor Framework?

In simple Java applications, we do not face much challenge while working with a small number of threads. If you have to develop a program that runs a lot of concurrent tasks, this approach will present many disadvantages such as lots of boiler plate code (create and manage threads), executing thread manually and keeping track of thread execution results.

Executor framework (since Java 1.5) solved this problem. The framework consist of three main interfaces (and lots of child interfaces) i.e. Executor, ExecutorService and ThreadPoolExecutor.

1.1. Benefits of Executor framework

  • The framework mainly separates task creation and execution. Task creation is mainly boiler plate code and is easily replaceable.
  • With an executor, we have to create tasks which implement either Runnable or Callable interface and send them to the executor.
  • Executor internally maintain a (configurable) thread pool to improve application performance by avoiding the continuous spawning of threads.
  • Executor is responsible for executing the tasks, running them with the necessary threads from the pool.

1.2. Callable and Future

Another important advantage of the Executor framework was the Callable interface. It’s similar to the Runnable interface with two benefits:

  1. It’s call() method returns a result after the thread execution is complete.
  2. When we send a Callable object to an executor, we get a Future object’s reference. We can use this object to query the status of thread and the result of the Callable object.
Читать еще:  Сортировка arraylist java по убыванию

2. Creating ExecutorService instances

ExecutorService is an interface and it’s implementations can execute a Runnable or Callable class in an asynchronous way. Note that invoking the run() method of a Runnable interface in a synchronous way is simply calling a method.

We can create an instance of ExecutorService in following ways:

2.1. Executors class

Executors is a utility class that provides factory methods for creating the implementations of the interface.

2.2. Constructors

We can choose an implementation class of ExecutorService interface and create it’s instance directly. Below statement creates a thread pool executor with minimum thread count 10, maximum threads count 100, 5 milliseconds keep alive time and a blocking queue to watch for tasks in future.

3. Submitting tasks to ExecutorService

Generally, tasks are created by implementing either Runnable or Callable interface. Let’s see the example of both cases.

3.1. Execute Runnable tasks

We can execute runnables using the following methods :

  • void execute(Runnable task) – executes the given command at some time in the future.
  • Future submit(Runnable task) – submits a runnable task for execution and returns a Future representing that task. The Future’s get() method will return null upon successful completion.
  • Future submit(Runnable task, T result) – Submits a runnable task for execution and returns a Future representing that task. The Future’s get() method will return the given result upon successful completion.

In given example, we are executing a task of type Runnable using both methods.

3.2. Execute Callable tasks

We can execute callable tasks using the following methods :

  • Future submit(callableTask) – submits a value-returning task for execution and returns a Future representing the pending results of the task.
  • List invokeAll(Collection tasks) – executes the given tasks, returning a list of Futures holding their status and results when all complete. Notice that result is available only when all tasks are completed.
    Note that a completed task could have terminated either normally or by throwing an exception.
  • List invokeAll(Collection tasks, timeOut, timeUnit) – executes the given tasks, returning a list of Futures holding their status and results when all complete or the timeout expires.

In given example, we are executing a task of type Callable using both methods.

Notice that tasks have been completed with a delay of 1 second because there is only one task in the thread pool. But when you run the program, all first 3 print statements appear at same time because even if the tasks are complete, they wait for other tasks to complete in the list.

4. How to shutdown ExecutorService

The final and most important thing that many developers miss is shutting down the ExecutorService . The ExecutorService is created and it has Thread elements.

Remember that the JVM stops only when all non-daemon threads are stopped. Here not shutting down the executor service simply prevents the JVM from stopping.

In above examples, if we comment out the executor.shutdownNow() method call, then even after all tasks are executed, main thread remains active and JVM does not stop.

To tell the executor service that there is no need for the threads it has, we will have to shutdown the service.

There are three methods to invoke shutdown:

  • void shutdown() – Initiates an orderly shutdown in which previously submitted tasks are executed, but no new tasks will be accepted.
  • List shutdownNow() – Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
  • void awaitTermination() – It blocks until all tasks have completed execution after a shutdown request, or the timeout occurs, or the current thread is interrupted, whichever happens first.

Use any of above 3 methods wisely as per requirements of the application.

5. Conclusion

As discussed above, ExecutorService helps in minimizing the boiler plate code which is a good thing. It also helps in better resource management by internally utilizing a thread pool.

Still, programmers should be careful to avoid some common mistakes. E.g. always shutdown the executor service after tasks are completed and service is no longer needed. Otherwise JVM will never terminate, normally.

Similarly, while creating it’s instance, be mindful of the configured thread pool capacity. Here or any other implementation, a careless threads pool size can halt the system and bring performance down.

And finally, make a practice of using timeout parameters in blocking method calls. These methods can block the whole application execution if not returned in small time.

6. More Examples

Drop me your questions in comments section.

0 0 голоса
Рейтинг статьи
Ссылка на основную публикацию
ВсеИнструменты 220 Вольт