Multithreading - Naming threads and handling exceptions - java

In java, what are the suggested ways to implement the two thread requirements
I would like the name a thread
I would like the parent (or main) thread know if there are any exceptions by this child thread.
For 2, I understand that having a future object would be a better approach. So to implement the above two requirements below is a code I came up with
class MyRunnable implements Runnable {
....
}
MyRunnable myRunnable = new MyRunnable ();
FutureTask futureTask = new FutureTask(myRunnable, null);
Thread myThread = new MyThread(futureTask, "processing-thread");
myThread.start();
try {
futureTask.get();
} catch (Exception e) {
throw new RuntimeException(e)
}
This seems to be a lot of code for simple stuff. Any better ways?
Note - Using executorService is not an option since I have threads which are not doing similar tasks. Also executorService accepts a thread name prefix instead of a thread name. I want to give each thread a unique name.

Using executorService is not an option since I have threads which are not doing similar tasks.
I don't see how this would matter.
Also executorService accepts a thread name prefix instead of a thread name. I want to give each thread a unique name.
So give each thread a name with a ThreadFactory. I have a class which I call a NamedThreadFactory.
I suspect what you would like the thread to do is reflect what the task is doing.
You can do this
ExecutorService es = Executors.newSingleThreadExecutor();
es.submit(new Runnable() {
public void run() {
Thread.currentThread().setName("Working on task A");
try {
System.out.println("Running: "+Thread.currentThread());
} finally {
Thread.currentThread().setName("parked worker thread");
}
}
});
es.shutdown();
prints
Running: Thread[Working on task A,5,main]
BTW There is no point starting a thread and immediately waiting for it to finish. You may as well use the current thread.

For the naming:
ThreadFactory myFactory = new ThreadFactory(){
#Override public Thread newThread( Runnable r ) {
return new Thread( r, getName() )
}
private int number = 0;
private String getName(){
return "MyThread_" + (number++);
}
}
There are other ways, too. This is the I like best, personnally.
---EDIT---
To give the thread completely different names, I would go another way:
One possibility would be to set the name inside the Runnable: See Peter's answer with one addition: instead of the fixed String, you could initialize a member variable of your Runnable implementation before starting the Thread.

Related

Java - are there different ways of starting threads?

Ok, guys so my teacher uses this code to start a thread if a thread is not already active. But i have been taught that to run threads no matter if its runnable or extending thread, you start it by the start method and not run. But in this case he starts it with run, why is that?
public void start2(Runnable r) {
if (thread == null) {
thread = new Thread(new Runnable() {
public void run() {
r.run();
thread = null;
}
});
thread.start();
}
}
Your teacher starts thread with thread.start() . He just implemented the runnable interface inside the Thread object initialization which is the absolutely correct approach.
A more modern approach would be to use an Executor to run the thread:
ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(() -> {
String threadName = Thread.currentThread().getName();
System.out.println("Hello " + threadName);
});
You have a better control of the thread:
Can retrieve some result (with futures)
Know if your thread is over (executor.isTerminated())
Request/force a shutdown (executor.awaitTermination()/executor.shutdownNow()).
These functionalities are not natively supported by the thread.start() that your teacher shows you (which is, by the way, a good way to launch a thread).
For more about Executors, I advice this excellent tutorial.
The r.run(); part in your code is just a method call to your Runnable r input parameter, which will be an implementation of the Runnable interface.
This does not start a thread
It's just a method call that is executes the input's implementation of Run method.
It will execute just like any other method.
Then, the actual thread will start at thread.start();
Long answer:
What is happening here is, first checking the thread variable.
If its null then initialize a new Thread with an anonymus class thread = new Thread(/*here --> */new Runnable() {.... and implementing the run() method.
Inside the run() there is a call, made to the outer method's input param, called Runnable r with r.run(); then set the thread variable to null.
Just outside of the if statement, the teacher starts the thread with thread.start();.

How do I run a thread in java that lets me know when another thread has died?

Assume that I have a thread A in java. This thread continues to perform some task A.
I have another thread B that must perform a task B only after Task A is finished. How do I implement this in Java?
You can use Thread.join() to basically block one thread until another thread terminates:
// In thread B
threadA.join();
doStuff();
Note that this won't work properly if you use a thread pool e.g. via an executor service. If you need to do that (and I'd generally recommend using executors instead of "raw" threads) you'd need to make the executor task notify any listeners that it has completed (e.g. via a CountDownLatch).
If you use Guava, you should look at ListenableFuture, too, which simplifies things.
You can use Thread Exceutor to acieve this. Executor keep the value in thread pool. Refer this link, It may help you
http://www.journaldev.com/1069/java-thread-pool-example-using-executors-and-threadpoolexecutor
see also
How to run thread after completing some specific worker thread
In Java SE 7 you could use CountDownLatch. Here is an example. Good thing that comes with using of CountDownLatch is that you can initialize it with certain number of required countdowns, so you can wait for a set of threads. Also it doesn't require thread to be completed (like in join()), thread can call countDown() in any place you want and continue execution.
Also, another approach is CyclicBarrier.
class Starter {
public static void main(String[] args) {
CountDownLatch signal = new CountDownLatch();
Thread a = new Worker(signal);
Thread b = new AnotherWorker(signal);
a.start();
b.start();
//doSomethingElse
}
}
class Worker extends Thread {
CountDownLatch signal;
Worker(CountDownLatch signal) {
this.signal = signal;
}
public void run(){
//doSomething
signal.await(); //wait until thread b dies
//doSomethingElse
}
}
class AnotherWorker extends Thread {
CountDownLatch signal;
AnotherWorker(CountDownLatch signal) {
this.signal = signal;
}
public void run(){
//doSomething
signal.countDown(); //notify a about finish
}
}

Could I join threads in a better way?

Suppose I have multiple Runnable instances in a program, all dispatched by an Executor instance. Further, suppose I at some point need to wait for a subset of these runnables to finish before moving on.
One way I could do this is the following:
public abstract class Joinable implements Runnable {
private final Semaphore finishedLock = new Semaphore(1);
#Override
public final void run() {
try {
finishedLock.acquireUninterruptibly();
doWork();
} finally {
finishedLock.release();
}
}
public abstract void doWork();
public void join() {
finishedLock.acquireUninterruptibly();
}
}
Implementing classes can then simply override doWork(), rather than run(), in order to define what should be done during execution.
The joining process will then simply look like this:
void doStuff() {
Executor executor = Executors.newCachedThreadPool();
List<Joinable> joinables = new LinkedList<Joinable>();
// Fill joinables with implementors of Joinable...
List<Runnable> others = new LinkedList<Runnable>();
// Fill others with implementors of Runnable...
for(Joinable joinable : joinables)
executor.execute(joinable);
for(Runnable runnable : others)
executor.execute(runnable);
for(Joinable joinable : joinables)
joinable.join();
// Continue, no matter what the threads in others are up to.
}
Is this a good way to solve this problem (is it even safe?), or is there a better one?
Your current solution is not thread safe. There are no guarantees that the executor will call run on your Joinable before you call join. Thus, in certain cases, your main thread will acquire the lock before your Joinable does.
On possible solution would be instead to use a CountDownLatch if you know the total number of joinables N, you create a CountDownLatch(N) and pass it to each instance. When each joinable is finished, have it call countDown(). Your main thread calls await() on the latch. await() doesn't return until the latch count is 0.
Is this a good way to solve this problem (is it even safe?)
This is not quite right. You can't join on a Runnable that you are executing by the ExecutorService. If you want to use a list then do something like this:
List<Future<?>> futures = new ArrayList<Future<?>>();
for(Joinable joinable : joinables) {
// this submit returns a `Future`.
futures.add(executor.submit(joinable));
}
// submit others to the executor _without_ adding to the futures list
for (Future<?> future : futures) {
// this can throw ExecutionException which wraps exception thrown by task
future.get();
}
or is there a better one?
If you were waiting for all tasks to complete then you could use the ExecutorService.awaitTermination(long timeout, TimeUnit unit) method. For example:
executor.awaitTerminate(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
But I don't see any better way to do this if you are waiting for a subset of tasks.

Get all threads that run with a specified Runnable

I have one Runnable that is used by more than one thread:
Runnable myRunnable = new MyWorker();
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
How can I get all threads that are created with myRunnable?
(Of course the example is simplified. I create new threads with myRunnable on several places in different classes.)
Use case (as requested): MyWorkerOfMyPage is a delayed worker that is bound to a page. If the user leaves this page (e.g. by navigating to another page) all threads that belong to MyWorkerOfMyPage should be killed ungracefully as their result is not needed anymore.
As already said best way is to track this yourself. This forces you to get a clear understanding of what you are doing. A good thing if you work with threads ... hmmm ... a good thing in every case ;).
But if you realy want to detect the threads you can use reflection with the Thread class to get the required information. First make the method "getThreads" accessible to get all running Threads, then make the field "target" accessible to get the runnables of the Threads.
Heres an example program (but I would advise against the usage in a real application. You should now what threads you are starting, it might harm compability with future JDKs, might harm portability ...):
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Runnable myRunnable = new Runnable() {
#Override
public void run() {
try {
System.out.println("Start: " + Thread.currentThread().getName());
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
};
Thread one = new Thread(myRunnable);
Thread two = new Thread(myRunnable);
one.start();
two.start();
List<Thread> threads = getThreadsFor(myRunnable);
for (Thread thread : threads)
System.out.println("Found: " + thread.getName());
}
private static List<Thread> getThreadsFor(Runnable myRunnable) throws Exception {
Method getThreads = Thread.class.getDeclaredMethod("getThreads");
Field target = Thread.class.getDeclaredField("target");
target.setAccessible(true);
getThreads.setAccessible(true);
Thread[] threads = (Thread[]) getThreads.invoke(null);
List<Thread> result = new ArrayList<Thread>();
for (Thread thread : threads) {
Object runnable = target.get(thread);
if (runnable == myRunnable)
result.add(thread);
}
return result;
}
}
The best way to do this is to track this yourself. Use a global singleton for instance that launches the threads and track which ones you started.
Although my first thoughts are along #Bengt's lines, perhaps you could use Class.isAssignableFrom if you had a list of runnables and you just want to know which ones use your interface.
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html
In Java there is no simple way to find all the places a object is referenced, its something you have to maintain a collection of yourself.
If you want to know this staticly you can Find Usages in your ide.
If you want to know this dynamically you can have the Runnable add the Thread to a collection (and remove it when finished)
Generally speaking, the developer should only create Threads deliberately. i.e. the Developer should know when he/she is creating thread and what those threads will be doing. Its not something you should be trying to track at runtime if you have a good design.

java thread reusage via executor

I am confused on the following:
To use threads in a Java program, the simplest way is to extend Thread class and implement the runnable interface (or simply implement runnable).
To start the thread's execution. we must call the Thread's method start(), which in turn calls method run() of the thread. And so the thread starts.
The method start() (unless I am wrong) must be called exactly and only once for each thread. As a result, thread instances can not be reused unless somehow the run method itself runs in some-short of infinite loop that facilitates a custom implementation of the thread's reusage.
Now the javadoc
link text
says
Calls to execute will reuse previously constructed threads if available
I do not understand how this is implemented.
I provide in the execute method of the executor method my custom thread e.g.
ExecutorService myCachedPool = Executors.newCachedThreadPool();
myCachedPool.execute(new Runnable(){public void run(){
//do something time consuming
}});
How can this custom thread I delegeate to the executor framework be reused?
Is Executor is allowed to call method start() more than 1 time, while we can not in our programs?
Am I misunderstanding something?
Thank you.
Note that it's not Executor that calls start() - it's ExecutorService. And no, it's not calling start() twice. It doesn't start the task that you give it directly using Thread.start()... instead, it starts a thread which knows about that thread pool's queue of work. The thread will basically wait until there's some work to do, then pick it up and execute it, before going back to waiting. So although the thread performs several tasks, Thread.start() is only called once.
EDIT: Judging by the comments, you're a bit confused about the difference between a Runnable (which is a task to be executed) and a Thread (which is what executes tasks).
The same thread can execute multiple tasks. For a very simple example not using a thread pool, consider this:
public class MultiRunnable implements Runnable
{
private final List<Runnable> runnables;
public MultiRunnable(List<Runnable> runnables)
{
this.runnables = runnables;
}
public void run()
{
for (Runnable runnable : runnables)
{
runnable.run();
}
}
}
(Ignore the potential thread safety issues of using a List<T> from multiple threads.)
You could create a whole bunch of Runnable tasks capable of doing different things, then create a single MultiRunnable to run them in turn. Pass that instance of MultiRunnable into the Thread constructor, and then when you start the thread, it will execute each of the original runnable tasks. Does that help?
It is not calling start() more than once; instead the Thread in the pool never completes, but just stays alive---waiting. The source code is available for download if you want to look at it.
Each Thread in the thread pool can simply wait() for the Executor to hand it a new Runnable, but the Thread's own run() method has not completed. It simply waits for a new Runnable to be given to the Executor.
To "start" a thread more than once, create a runnable. For example:
//NO
private class T extends Thread { //not necessary to implement runnable
public void run(){
//...
}
}
void someMethod(){
T a = new T();
a.start();
a.start(); //NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO NO
}
Instead,
//Yes
private class T implements Runnable {
public void run(){
//...
}
}
void someMethod(){
T a = new T();
new Thread(a).start();
new Thread(a).start(); //YES YES YES
}
It is also possible to do this:
void someMethod(){
final Runnable r = new Runnable(){
public void run(){
//...
}
};
new Thread(r).start();
new Thread(r).start();
}
// r could also be a field of you class.

Categories