JAVA: Possible to add a runnable thread into a queue? - java

I recently began working with Threads and I am trying to complete a Java implementation of the Looper class in Android. Basically I am making a Java class that puts threads into a queue that will then be executed by the Looper class. I have the code completed for the most part but have an issue with the enqueuing of tasks.
In the Looper class I have the queue declared and my enqueue method:
List<Runnable> queue;
public synchronized void enqueue(Runnable runnable) {
queue.add(runnable);
notify(); // signal a waiting thread
}
I then created another class called TaskManager to add Tasks into the queue. I receive the error when I call:
loop.enqueue(new Task());
Where Task() implements runnable and just adds two integers together in its run() method...this is just a test.
The error I receive is:
Exception in thread "Thread-0" java.lang.NullPointerException
at Looper.enqueue(Looper.java:20) (this is the queue.add(runnable))
at TaskMaker.run(TaskMaker.java:16) (this is the loop.enqueue(new Task())
I'm obviously doing something wrong and not implementing this right...how should I go about this? Is the way I am enqueuing the task right? Thanks for any help it is much appreciated!

Are you initializing the queue variable? like:
List<Runnable> queue = new ArrayList<Runnable>();

Related

executor Service interupt handling

I have an application in which there are multiple threads. I want them to execute in order.so i choose executorService for multi-threading. if any one of thread(run method) is in error , I want to move on to net thread so that by the end i can come to know how many thread are completed successfully (count needed).My sample code:
The Main class:
public class MySampleClass{
ExecutorService executor = Executors.newSingleThreadExecutor();
for(int i=0; i<=100;i++){
executor.submit(new ThreadClass());
}
//After all threads executed now to shutdown executor
executor.shutdown()
executor.awaitForTermination(1,Time.MILLISECONDS);
My Sample Thread Class :
public class ThreadClass implements Runnable{
#override
public void run(){
boolean isCompleted= doAction();
if(!isCompleted){
// I want here to stop this thread only..what to do ?
//executor.shutdown will stop all other threads
}
}
}
Any Suggestion what to do ?? Am i doing it wrong way ?
Thread.currentThread().interrupt();
You shouldn't stop a thread. There is a reason Thread.stop is deprecated. Instead you can interrupt the current thread.
You can use Callable instead of Runnable. If you do that, submit method returns a Future (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Future.html) instance on which you can verify if the callable do it´s work in the right way. The documentation explains it:
http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ExecutorService.html#submit(java.util.concurrent.Callable)
Hope i explained in the right way.

Stopping a Timer Task from within a Runnable thread when shutdown

I have a TimerTask that gets started as the first thing in my run() method of my Runnable class. I want to make sure that it gets stopped when the runnable is shutdown.
The runnable is started via an ExecutorService. I don't see a way to get a hook back to the runnable from the ExecutorService when shutdown() is called.
How can I make sure that the TimerTask is stopped?
Thanks
use ExecuterService.submit() to get back Future object once the task is completed.
ExecutorService.Submit()
The method call TimerTask.cancel() should do the desired.
Your Runnable.run method could be designed like this:
public void run() {
pingTask = new PingTimerTask(...);
try {
...
} finally {
/* this code even gets executed when an exception
* (for example an *InterruptedException*) was thrown:
*/
pingTask.cancel();
}
}

Is there a way to put tasks back in the executor queue

I have a series of tasks (i.e. Runnables) to be executed by an Executor.
Each task requires a certain condition to be valid in order to proceed. I would be interested to know if there is a way to somehow configure Executor to move tasks in the end of the queue and try to execute them later when the condition would be valid and the task be able to execute and finish.
So the behavior be something like:
Thread-1 take tasks from queue and run is called
Inside run the condition is not yet valid
Task stops and Thread-1 places task in the end of the queue and
gets next task to execute
Later on Thread-X (from thread pool) picks task again from queue condition is valid
and task is being executed
In Java 6, the ThreadPoolExecutor constructor takes a BlockingQueue<Runnable>, which is used to store the queued tasks. You can implement such a blocking queue which overrides the poll() so that if an attempt is made to remove and execute a "ready" job, then poll proceeds as normal. Otherwise the runnable is place at the back of the queue and you attempt to poll again, possibly after a short timeout.
Unless you have to have busy waiting, you can add a repeating task to a ScheduledExecutorService with an appropriate polling interval which you cancel or kill after it is "valid" to run.
ScheduleExecutorService ses = ...
ses.scheduleAtFixedRate(new Runnable() {
public void run() {
if (!isValid()) return;
preformTask();
throw new RuntimeException("Last run");
}
}, PERIOD, PERIOD, TimeUnit.MILLI_SECONDS);
Create the executor first.
You have several possibilites.
If I suppose that your tasks implement a simple interface to query their status (something like an enum with 'NeedReschedule' or 'Completed'), then implement a wrapper (implementing Runnable) for your tasks which will take the task and the executor as instanciation parameters. This wrapper will run the task it is bound to, check its status afterwards, and if necessary reschedule a copy of itself in the executor before terminating.
Alternatively, you could use an execption mechanism to signal the wrapper that the task must be rescheduled.
This solution is simpler, in the sense that it doesn't require a particular interface for you task, so that simple Runnable could be thrown in the system without trouble. However, exceptions incur more computation time (object construction, stack trace etc.).
Here's a possible implementation of the wrapper using the exception signaling mechanism.
You need to implement the RescheduleException class extending Throwable, which may be fired by the wrapped runnable (no need for a more specific interface for the task in this setup). You could also use a simple RuntimeException as proposed in another answer, but you will have to test the message string to know if this is the exception you are waiting for.
public class TaskWrapper implements Runnable {
private final ExecutorService executor;
private final Runnable task;
public TaskWrapper(ExecutorService e, Runnable t){
executor = e;
task = t;
}
#Override
public void run() {
try {
task.run();
}
catch (RescheduleException e) {
executor.execute(this);
}
}
Here's a very simple application firing up 200 wrapped tasks randomly asking a reschedule.
class Task implements Runnable {
#Override
public void run(){
if (Maths.random() > 0.5)
throw new RescheduleException();
}
}
public class Main {
public static void main(String[] args){
ExecutorService executor = Executors.newFixedThreadPool(10);
int i = 200;
while(i--)
executor.execute(new TaskWrapper(executor, new Task());
}
}
You could also have a dedicated thread to monitor the other threads results (using a message queue) and reschedule if necessary, but you lose one thread, compared to the other solution.

Why is my multi-threaded application being paused?

My multi-threaded application has a main class that creates multiple threads. The main class will wait after it has started some threads. The runnable class I created will get a file list, get a file, and remove a file by calling a web service. After the thread is done it will notify the main class to run again. My problem is it works for a while but possibly after an hour or so it will get to the bottom of the run method from the output I see in the log and that is it. The Java process is still running but it does not do anything based on what I am looking at in the log.
Main class methods:
Main method
while (true) {
// Removed the code here, it was just calling a web service to get a list of companies
// Removed code here was creating the threads and calling the start method for threads
mainClassInstance.waitMainClass();
}
public final synchronized void waitMainClass() throws Exception {
// synchronized (this) {
this.wait();
// }
}
public final synchronized void notifyMainClass() throws Exception {
// synchronized (this) {
this.notify();
// }
}
I originally did the synchronization on the instance but changed it to the method. Also no errors are being recorded in the web service log or client log. My assumption is I did the wait and notify wrong or I am missing some piece of information.
Runnable Thread Code:
At the end of the run method
// This is a class member variable in the runnable thread class
mainClassInstance.notifyMainClass();
The reason I did a wait and notify process because I do not want the main class to run unless there is a need to create another thread.
The purpose of the main class is to spawn threads. The class has an infinite loop to run forever creating and finishing threads.
Purpose of the infinite loop is for continually updating the company list.
I'd suggest moving from the tricky wait/notify to one of the higher-level concurrency facilities in the Java platform. The ExecutorService probably offers the functionality you require out of the box. (CountDownLatch could also be used, but it's more plumbing)
Let's try to sketch an example using your code as template:
ExecutorService execSvc = Executors.newFixedThreadPool(THREAD_COUNT);
while (true) {
// Removed the code here, it was just calling a web service to get a list of companies
List<FileProcessingTask> tasks = new ArrayList<FileProcessingTask>();
for (Company comp:companyList) {
tasks.add(new FileProcessingTask(comp));
}
List<Future<FileProcessingTask>> results = execSvc.invokeAll(tasks); // This call will block until all tasks are executed.
//foreach Future<FileProcessingTask> in results: check result
}
class FileProcessingTask implements Callable<FileResult> { // just like runnable but you can return a value -> very useful to gather results after the multi-threaded execution
FileResult call() {...}
}
------- edit after comments ------
If your getCompanies() call can give you all companies at once, and there's no requirement to check that list continuously while processing, you could simplify the process by creating all work items first and submit them to the executor service all at once.
List<FileProcessingTask> tasks = new ArrayList<FileProcessingTask>();
for (Company comp:companyList) {
tasks.add(new FileProcessingTask(comp));
}
The important thing to understand is that the executorService will use the provided collection as an internal queue of tasks to execute. It takes the first task, gives it to a thread of the pool, gathers the result, places the result in the result collection and then takes the next task in the queue.
If you don't have a producer/consumer scenario (cfr comments), where new work is produced at the same time that task are executed (consumed), then, this approach should be sufficient to parallelize the processing work among a number of threads in a simple way.
If you have additional requirements why the lookup of new work should happen interleaved from the processing of the work, you should make it clear in the question.

sequential event processing via executorservice

I have an event queue to process. A thread adds events to the queue.
I have created a runnable Task that in the run method does all which is necessary to process the event.
I have declared an Executors.newCachedThreadPool(); and I execute each Task.
public class EventHandler {
private static final ExecutorService handlers = Executors.newCachedThreadPool();
public void handleNextEvent(AnEvent event){
handlers.execute(new Task(evt));
}
public class Task implements Runnable{
#Override
public void run() {
//Event processing
}
}
public AnotherClass{
public void passEvent(AnEvent evt)//This is called by another thread
{
EventHandler.handleNextEvent(evt);
}
}
My problem is that if I call execute of the executor, my code will get the next event and run next runnable via the executor.
My purpose is to process next event from queue only after previous task has ended.
How would I know that the previous task has finished or not so that I know I can call handleNextEvent again?
Is having some status field updated by the Task a good idea?
Thanks
Executors.newCachedThreadPool() will create new threads on demand, so it's not what you want. You want something like Executors.newSingleThreadExecutor(), which will process the events one at a time, and queue up the rest.
See javadoc:
Creates an Executor that uses a single worker thread operating off an unbounded queue. (Note however that if this single thread terminates due to a failure during execution prior to shutdown, a new one will take its place if needed to execute subsequent tasks.) Tasks are guaranteed to execute sequentially, and no more than one task will be active at any given time.
I think Executors.newSingleThreadExecutor() and the submit() Method are the solution to your problem: http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/ExecutorService.html

Categories

Resources