Tracking thread initialization in source with large applications - java

If an application starts many threads ( using new Thread() as well as using ExecutorService ) at various places in its code ( including from within the referenced jars ) , then what is the best way to identify the source code that started any specific thread ( as seen in an executing instance of the application )
This is helpful , for example , in case a thread causes an Exception - and we need to start at the source code where the thread was initialized ( so that the context is clear ).The thread dump I get from VisualVM shows many running/waiting threads but the stack root always seem to be at java.lang.Thread.run(Thread.java:722) - not very helpful.
`

Are you able to insert code at the points that the threads are being created? If so, then create a static HashMap in your main class along with a public static put method. Then whenever you create a thread t1, call Main.putThreadId(t1.getId(), "some text that identifies the method that's creating the thread"), and when you catch an exception look up the value in the HashMap.

What you can do is that, set Thread.uncaughtExceptionhandler to every thread you start.
It has a method called:
uncaughtException(Thread t,Throwable e)
Inside this you can put a log or something with which you can later identify from where this code is called for. But of-course for every thread, you will have to specify individually as the origin.
You can set a global one by Thread.setDefaultUncaughtExceptionHandler(myHandler);. But to make it distinct, probably have a ThreadGroup or something.
Though all this isn't helpful if the thread is started by referenced Jar.

You can use the map approach given before, but instead of some text, you generate a new Exception at the point where you create the thread. Put this exception as value in the map. You can later get the stack trace if you need. For Executors, you can hide this in the ThreadFactory creating the worker threads.
This problem occurs in similar fashion when using Runnables. Sometimes you want to know where the Runnable has been created and queued, on top of any stack trace starting at the run method.
Of course the whole legacy code and referenced jar problem is: you want to solve a problem that needs coding, but without coding. Not easy :)

Related

Monitor file to find which thread is modifying file

I want to find which java thread is modifying file.
If anybody know tool or know how we can monitor and get thread name please share.
Thanks.
I am not sure why exactly you need this information but i beleive there are two ways.
First way is in your java code when you create a thread , create it with a name. There are constructors & method available in Thread class to do the same. If you have a good logging in your project then you can log the thread name who enters the code to modify the file.
Second way is again dependent on having a thread with the name. You can use a java profiler to find out what threads are doing at a point in time. Although it will be too tough if threads are modifying the file too quickly. But if you are trying to find a problem of slow modification of file by a thread then profiler may give you the hint.
Hope it helps!
if the file modification is a code that you wrote, you can use before the modification:
Thread.currentThread().getName();
Thread.currentThread().getId();
and youl get the name and id of the thread

How can I get the thread id of the threads of the servlet?

Just as the title. Google didn't give me any clue.
Edit: What I mean is to get the threads that executing the code of the servlet. Thanks.
Edit: Why I want this information, this is because when there are many threads executing, their log aggregate in a single log, and the order of log is disrupt. I want a thread id inserted at the front of each line of the log so that I can trace the activity of each thread.
It is not actually a meaningful thing to ask for.
Threads don't belong to a servlet. Rather, they belong to the web container and are used to run requests ... which at certain points involves running servlet methods. A servlet method can of course find out what the current thread is ... but then so can any method.
It is also possible that the web container might use thread groups in a way that allows you to determine that certain threads are used for certain things. But that would be highly implementation specific.
If that's not what you mean, then please refine your question.
What I mean is to get the threads that executing the code of the servlet.
Do you mean currently executing the code of the servlet?
Then I think that the answer is simply - "This is not possible".
It is not possible within a running program for one application thread to find out what code another thread is executing. This kind of thing can only be found using a debug agent ... while all application threads are stopped.
I want a thread id inserted at the front of each line of the log so that I can trace the activity of each thread.
(Well why didn't you simply ask that in the first place??)
A log4j LoggingEvent contains the name of the thread that created the event. You can use a %t in a pattern layout to include the thread name in a log file. You could also write your own custom Appender to filter the events into different "streams" based on the event's thread name.
The thread id is not available for logging ... unless you explicitly insert it into (for example) the log message string.
How about:
long threadId = Thread.currentThread().getId();
in the servlet code? That will give you the ID of the thread running the servlet's service() method. Obviously many of those can be going on simultaneously. Or do you mean something else by "id of the threads of the servlet"?
You can get all the threads in the current thread group with this code:
int active = Thread.activeCount();
Thread allThreads[] = new Thread[active];
active = Thread.enumerate(allThreads);
You can then call getId() for each element of the returned array. You can get fancier by first climbing to the root ThreadGroup of the current thread.
What would you want this information for?
You can get only the currrent thread id using Thread.currentThread().getId(). If you want to track all the threads executing your servlet, keep a list in the request called executedThreads and add the current thread id to the list.

Events or Handlers? Invoking methods from a thread

Consider a simple Android application: there are two TabActivities and a thread in the background getting integer values from a server. If the number is even, it must be displayed in the first tab otherwise in the second. Obviously I will be doing something more complicated, but this is the basic pattern. How do I go about doing this? I have been scratching my head for about a day now and here are things I have come across:
Use of EventHandlers. The two TabActivities register for listening for my_events and when a value is received by the thread, it 'throws my_event' and then specific methods in both these activites are called and the value is passed.
The use of Handlers.
I have not used both of these concepts before and I would like to know which might be the better/correct route to take. Further, any more tips along the chosen route will be appreciated. Also, should this thread be run from a service class?
When you create your thread just pass the objects of your tabs into it, then in your execution you can easily put the text you want into tabs.
Possibly you want to look at using an AysncTask. If you do this you want to insert the values into the appropriate tab in the onProgressUpdate() method. Since the arguments passed to this method may not actually be able to represent the incoming data sufficiently you'll just want to put the new data somewhere that it can be accessed from the onProgressUpdate() method, probably in a member variable. Keep in mind that access to this member variable probably needs to be synchronized because code in onProgressUpdate is running on the application's main thread, while code in doInBackground is running on a background thread so code in these methods will be running concurrently.
AsyncTask uses Handlers transparently for you, but you could use raw Handlers if you wanted. The basic things you need to keep in mind are
You can/should only update the UI from the main application thread
Code in a Handler will always run on the Thread that created the Handler
Handlers must be created on a Thread that has a Looper (the main Thread has a Looper)
Be careful if creating the Handler as an anonymous inner class or handing it a reference to a Context since this creates the potential for a memory leak
Possibly the Thread should be invoked by a Service, but if the Thread only needs to exist when there is a UI for it to update there may be little point to this.

How to Identify threads in Eclipse Debug Perspective?

I am developing a Java application which has some threads. I print in the console the threadId, for instance 17, 18, 19, and so on.
But when I have the debug perspective open, I have this "Debug" window (most up-left window), which shows me the current threads, but they use [Thread-2], [thread-3]. The numbers not necessarly match the ThreadIds.
Is there any way so I can correlate the ThreadId I get in my console to the thread shown in the "Debug" window?
I don't know of a way to do that.
However, there is another approach. Those thread names are generated automatically by the Thread constructor you are using. However, there is a method called Thread.setName() that allows you to change the thread's name. You could possibly tweak your application to change the names of the threads that it creates to match the thread's ids.
There is nothing as such in Eclipse, but if you want to find which thread, then add debugging point on the code and call the
Thread.currentThread();
to find out the thread, which is currently executing.
Watch this thread for more information on the same.
http://dev.eclipse.org/mhonarc/lists/platform-debug-dev/msg00845.html
Instead of printing the Thread ID, you could print the thread name. Thread.currentThread().getName(). That is the name shown in the debugger.

What is the proper way to keep track of the original stack trace in a newly created Thread?

In the client program on which I work, we dispatch server calls to different Threads, to not lock the UI (equivalent of a SwingWorker).
This is made with a model class inheriting an abstract class containing the "update" method, which is preparing the new thread, and executing the code from an abstract method in this newly created Thread (plus other tweaks)
It works correctly, but my issue is that when debugging (or logging), it is hard to keep track of which method exactly called the "update" method, since the stack trace ends with the creation of the new Thread.
What would be the proper way to keep track of the stack trace which led to call this new Thread? Ideally, in a way which would show in the debugger's stack navigator (from Eclipse in this case; the idea is to navigate easily in the initial context).
Typically stack traces don't cross threads so this is going to be tricky. However, in the constructor of your Worker class you could access the current thread with...
Thread current = Thread.currentThread
You can then get the current stack trace of that thread by calling...
StackTraceElement[] currentStack = current.getStackTrace();
You can then store that in an instance variable for your worker and view that from your debugger. This has to be done before the control passes into the new thread, that's why I suggested doing it in the constructor. However, any method that gets called before the start() method of the new thread will be fine.
A good way to store a stacktrace away efficiently is to simply construct an exception. Later, if you want to inspect the stacktrace call exception.getStackTrace() which will do the slow work of resolving the stack frames to methods.
So, you could create a new Exception on the construction of your worker thread, or pass it to the worker thread. Note, you'll have to get eclipse to evaluate exception.getStackTrace(), because the exception object won't have the details before you do.
public abstract class Worker {
protected abstract Object doTheWork();
public Future<Object> update() {
Exception stack = new Exception();
Callable<Object> job = new WhateverYourCallableIs(stack);
return submitJob(job);
}
}
Incidentally, you should probably use an ExecutorService to manage the lifecycle of your threads.
Edit
I'm suggesting this way because it will have a minimal impact on performance in the usual case where you don't want to see the stack trace.
You say you do "like SwingWorker". In this case, why not using an ExecutorService ? Java concurrent framework is pretty well made, and would allow you to avoid the classic pitfalls of threading, amongst them your question.
I just had the same problem - multiple points in the system were sending a mail through the same logic wrapped in an ExecutorService.
Just like #daveb I create an empty Exception and pass it into the Runnable:
Executors.newSingleThreadExecutor().submit(new Mailer(..., new Exception()));
Now inside of Mailer I have the Exception instance to use in logging expressions:
public Mailer(..., final Exception originalStackKeeper) {
...
this.originalStackKeeper = originalStackKeeper;
}
...
LOG.error("There was an error while sending mail, originating here: ",
originalStackKeeper);
But even better: whenever I catch an exception in Mailer, I can do this:
} catch (final SomeException e) {
LOG.error("There was an error while sending mail.",
originalStackKeeper.initCause(e));
}
So I tell the original Exception: let's use your stack: here is the cause why we are using you, and here we are logging you. It seems to me that this is not really a hack, but rather a clean way to use the "cause" mechanism in Java exceptions.

Categories

Resources