Queueing Runnable objects for execution in one thread - java

Is this possible to queue multiple Runnable objects to wait for execution in one thread? How it can be done without using ExecutorService? What's gonna happen if one of those Runnable objects threw unchecked exception, does it stop executing thread?

Is this possible to queue multiple Runnable objects to wait for execution in one thread?
Use an ExecutorService.
How it can be done without using ExecutorService?
Use a BlockingQUeue and Thread.
What's gonna happen if one of those Runnable objects threw unchecked exception, does it stop executing thread?
That's up to you since you have to writ this yourself.
For an ExecutorService, the Throwable thrown is added to the Future object for you to check. Its very easy to forget to do this, in which case you need to add a try/catch block to you Runnable.

Is there a specific reason for not using an ExecutorService? It provides an implementation working in one Thread: Executors.newSingleThreadExecutor()

It is possible.
Open a thread the listens to a queue, each time it sees a item, it deques and runs it.
You can wrap the execution of the task in a try catch block, thus allowing the worker thread to continue working even if one of the tasks threw an exception.
Having said that- the above is exactly what a ThreadPoolExecuter does, so why wouldn't you want to use it? (Homework?)

Related

How to schedule tasks in a specific thread without using a looper and a handler?

Timer creates its own thread and ScheduledThreadPoolExecutor uses a pool. Is their a way to specify the thread where the task will be executed directly without having to marshal any code? And if this is a bad idea, please explain why (beside the thread being busy).
I have no problem with the looper-handler approach, I'm just curious.
You can create a ScheduledThreadPoolExecutor with one single thread using Executors.newSingleThreadScheduledExecutor().
Optionally, you can pass a ThreadFactory as parameter if you want to have more control about this single thread. The thread factory's newThread(Runnable) method is called every time the executor wants to have a new Thread instance that should run the given Runnable (which is not identical to the Runnable you pass to the executor's execute(...), submit(...) or schedule(...) methods).
Note that you are not able to reuse an existing thread, as there is no way to 'inject' code into an already running thread in general, as it is possible in Qt. There, every thread has its own event queue and timing facility, so you can freely decide which (already existing) thread should process your timed task (see Timers in Qt).
There is no such feature in Java out of the box.

What order do threads run (execute) after being submitted to ExecutorService?

Is there a better way to make writing to files thread safe (for cases where the file may not be all the same in every thread) than synchronizing the method or the file writer? I read a few threads similar to this topic, but they seem to focus on one file as opposed to multiple files.
Ex. There are 20 threads that writes (meaning it uses a method that creates a a file writer to the file and then writes to it with a try-catch, etc) to file; 10 of the threads write to fileA, 5 threads write to fileB, 4 threads write to fileC, and 1 thread writes to fileD.
Synchronizing the method would not be efficient since threads that want to write to different files will have to wait for the previous thread to finish before it can proceed. I think synchronizing the file writer does pretty much the same or am I wrong?
If I were to have a separate thread thread (from the main application) that writes to a file, would they execute (run) in the order they were submitted to the ExecutorService with 1 thread?
In the main application, I would submit new threads to the ExecutorService (uses 1 thread). The threads would write to a file (using a write method that has the FileWriter synchronized from a Logger class). The threads would write to the file one by one because the FileWriter is syncrhonized and there is only 1 threads for the ExecutorService, which will prevent multiple writes to the same file at once. The question is will the threads write to the file in the order they were submitted to the ExecutorService? I know they start in the order they were submitted, but I am not too sure on the execution order.
You are mixing some things up which creates the confusion: First, ExecutorService is an interface that does not mandate a particular way how the submitted tasks (not threads) are executed. So it doesn’t make sense to ask how an ExecutorService will do a particular thing as it is not specified. It might even drop all tasks without executing anything.
Second, as already mentioned above, you are submitting tasks, not threads, to an ExecutorService whereas the tasks may implement Runnable or Callable.
Unfortunately there’s a design flaw in Java that Thread implements Runnable so you actually can pass a Thread instance to submit() which you should never do as it creates a lot of confusion for no benefit. When you do so, the common ExecutorService implementations will treat it as an ordinary Runnable invoking its run() method ignoring the fact completely that it is a Thread instance. The thread resource associated with that Thread instance will have no relationship with the thread actually executing the run() method (if the implementation ever calls run()).
So if you submit tasks implemented as Runnable or Callable to an ExecutorService you have to study the documentation of the particular implementation to learn about how they will be executed.
E.g. if you use Executors.newSingleThreadExecutor() to get an implementation, its documentation says:
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. Unlike the otherwise equivalent newFixedThreadPool(1) the returned executor is guaranteed not to be reconfigurable to use additional threads.
(emphasis by me)
So that would answer your question completely. Note that in this case you don’t even need synchronized within your task’s implementation as this ExecutorService already provides the mutual exclusion guaranty required for your tasks.
Consider the alternative of having a specialized file writer thread that is the only thread to write to the files. The other threads can safely add messages to a java.util.concurrent.BlockingQueue. As soon as a thread has placed a message on the queue, it can get back to work.

Cleanly Stopping a Thread

I've finally managed to implement Thread.interrupt() into my program instead of Thread.stop(). I am however not sure that I've done this well.
I have a class which extends Thread and declares several methods. EVERY method has been made to throw InterruptedException (Each method performs I/O intensive operations, some of which take several minutes to complete, I have therefore not used a thread-safe flag as the flag would not get checked until after the operation completed). I have also added the following code at several places within these methods to throw the exceptions:
if (this.isInterrupted()) throw new InterruptedException();
Within the run() method I execute all methods within a try/catch for InterruptedException. If caught, I execute Process.destroy() and BufferedReader.close() for my class variables.
This all works, and seems to work very well, however I have a couple of questions:
Is it correct to have more than 10 methods, all of which throw InterruptedException? Is there a better way to do this?
Is it correct to bloat the methods with checks for isInterrupted()?
At the end of the catch InterruptedException block, must I execute a 'return', or 'null' certain values to make the Thread available for GC? If I re-create the Thread it takes longer than usual to initialize.
Finally, are there any issues/enhancements related to what I've done?
Thanks in advance for your help!
Thread interruption in Java doesn't mean stopping the execution of that thread. It is not stop, it is interrupt. A thread can be interrupted when something fundamental and crucial changes, telling the thread that its execution context, its task or its enviroment changed in some significant way. A thread reaction to this message is implementation specific. It can be stop, it can be restart or any other action. A thread that doesn't handle interruptions cannot be interrupted, but its behaviour can still be altered, for example, by using a shared variable.
For example, imagine you have a number of threads, all searching through a part of a problem space for a solution. When one thread finds a solution, it can interrupt other threads, because their search for a solution is no longer relevant. A solution has already been found.
Or imagine one continuously working main thread and one network communication thread. Each time the network thread receives a messsage, it interrupts the working thread with the message. Based on what the message and the context is, the worker thread may decide what to do next. For example, if the message was "STOP", then it could stop all execution immediately. If the message was "RESET", it could start again from scratch or maybe not from scratch and reuse some previous work, based on the execution context.
Is it correct to have more than 10 methods, all of which throw
InterruptedException? Is there a better way to do this?
No, this is perfectly fine, as long as you know what you are doing. If you implement interruptions to just stop the threads, there is no need to throw InterruptedExceptions. A Thread's run() method is it's first, and the exception will not go any further the stack.
Is it correct to bloat the methods with checks for isInterrupted()?
Depending on the context. The checks would be usually added before some crucial code. Usually it is added as a first item in the loop block.
At the end of the catch InterruptedException block, must I execute a
'return', or 'null' certain values to make the Thread available for
GC? If I re-create the Thread it takes longer than usual to
initialize.
No. Once the Thread exists from the run() method, it's left at GC's mercy. Shared variables will not be GC'ed, as long as they are still referenced by other objects.

Java interrupts

I'm trying to implement a sort of interrupt process into my java program so that if an operation takes longer than 5 minutes, i can kill it.
Is there any sort of generic way I can do this? I'm using an external API to carry out very processor intensive calculations and it already multithreads the process so can I still use the executor class to do this?
-edit-
Ended up solving it by using a bash script wrapper function. It kills the PID after a timeout.
It's considered unsafe to kill or forcefully stop a Thread because it may leave the program in an undetermined state, which will later cause a crash or other more serious problem. Instead, you should design your worker thread to periodically check the interrupt flag via Thread#isInterrupted or Thread#interrupted and exit if it is set. Then, using another thread, you can signal to the worker thread that it should stop by calling interrupt() on the worker thread, which will result in the worker thread detecting the interrupt or possibly receiving an InterruptedException if it is blocking inside your code or the third party code.
Depending on how your thread is coded (ie. whether it would properly terminate when interrupted), you could use the provided Thread.join(millis) or Thread.join(mills, nanos) method calls.
Something like this:
Thread myThread
// ... start myThread
myThread.join(300000); // 5mins in millis
if (myThread.isAlive()) {
myThread.interrupt();
}
Inside the thread itself, you would want to ensure that you .yield() at relevant points and properly handle an InterruptedException to allow this kind of logic to work.
Of course this is an "ideal" kinda situation - if the thread is blocked due to some outside process, and cannot handle the .interrupt(), then it will not work very well.
HTH

what is the relationship of thread and task?

I know that Thread and Task are in different abstraction-level.But anyway,I'm still confused that what's the relationship of them.And,by the way,I think that the Task tells how to do a job and the Thread actually excute the job according to a Task instance.Is my understanding correct?thank u^
I assume by Task you mean Runnable and Callable. The relationship is simple:
Thread might be used to execute multiple tasks
might - because you don't need a separate thread to execute tasks (well, technically, everything runs inside a thread - you don't need a separate one)
multiple - thread can be reused; it can run multiple tasks from a collection like queue
Typically one thread executes one Runnable passed to Thread constructor or multiple Callables passed to ExecutorService (wrapping thread pool in most cases).
If by Task you mean something like this, then the difference is that the task is used to run some thread-like code execution, but has additional properties, such as when to run it, how many times, and the option to cancel its execution, whereas a thread will just go ahead and run once immediately.
A task is rather abstract it can be implemented as a process or a thread.
Your understanding is correct.
We can do the analogy with workflow patterns where tasks are something that needs to be done in a process and threads are resources used to process or execute them.

Categories