How to Identify threads in Eclipse Debug Perspective? - java

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.

Related

How can I prevent the command line from being interrupted by printing lines?

I've been tryna find an answer to this for a while but I'm a newbie with little hope left lol
In Java, I have two threads right now:
(main class) Thread A has a while loop listening to commands with Scanner.nextLine()
Thread B prints out "test" every second
When I start both threads, I can't properly type a command without it getting interrupted by Thread B's printing
Output:
test
test
commantest
dctest
ommandtest
test
test
How do I prevent this so I can type commands without any interruptions? I'm open to using ANSI Escape codes and JCurses (or any libraries reallyy) :)
Thanks!
There is no way of preventing this. The two threads are essentially using the same console, which for you looks messed up, but is in fact working exactly as it should. Note that both reading and writing should still work, despite the text on your console being garbled.
If you want to use the console for interacting with the user, you need to ensure that no other threads are using it at the same time. Depending on your use case you could for example send the other prints to a file, named pipe etc. Alternatively, if you are designing the console application with curses, you need to properly design it for multithreading (which, again, boils down to having a single thread dealing with the console, but in a way that keeps things on separate parts of the screen).

Stop at breakpoints only in certain thread

I have some multithreaded code and am trying to set up some breakpoints in Eclipse so I can do some debugging.
The breakpoint I want to set is in a class used by all of the threads. However, I only want the breakpoint to be hit when I am in the main thread. Is there a way to do this in Eclipse?
I have tried to use the 'conditional' breakpoint options but cannot get it to work.
Conditional breakpoint approach is good. The condition should looks like: Thread.currentThread().getName().equals("main").
If you want to set up a breakpoint for another thread you just have to change "main" to a thread-specific name, which can be provided via the Thread constructor.
You should be able to set up a conditional breakpoint by using a condition dependent on thread-local data. Two examples:
Thread.currentThread().getName(),
some value stored in a ThreadLocal.
There should be an item Filtering in the breakpoint properties dialog. There, you can limit the breakpoint to specific threads. But this only works when the program is already running since that dialog shows all threads from the running JVM.

Tracking thread initialization in source with large applications

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 :)

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.

Java program only works with Breakpoints in Netbeans

I'm working on a multithreaded program in Java that uses a shared array to pass data between threads. It's being developed in Netbeans 6.7.1.
One of the threads only seems to work when a breakpoint is placed in it, it doesnt matter where it is.
Running in debug mode with no breakpoints acts the same as running in release - the expected output never arrives.
I can't tell where the problem occurs, as the moment a breakpoint is added and I press continue, it works as expected.
How can I narrow down where/why this problem occurs?
Example code:
result = utils.isBufferFull(AudioDuplex.voiceArray);
if(result == true) {
System.out.println("Taking copy");
voiceArray = AudioDuplex.voiceArray;//.clone();
utils.clearBuffer(AudioDuplex.voiceArray);
}
If a breakpoint is placed on line 2, it is never hit.
A breakpoint on line 3 will be hit, and the expected output will arrive.
It's impossible to tell exactly what's wrong without a lengthier code sample, but in my experience, this kind of behavior is typical of unrecognized producer-consumer problems (see http://en.wikipedia.org/wiki/Producer-consumer_problem).
Basically, what's probably happening is that your producer thread does not have the data available when the consumer thread is requesting it. The basic solution is to keep a semaphore (there is a Sempahore class in java afaik). The producer would post when it has the data, the consumer would wait until the producer posts.
What you're seeing with the break point is you stopping the consumer thread for a long enough period that the producer can offer something. When you don't break, the consumer runs normally, and exits before the producer has anything.
Write the values of the involved variables to a log file, the console or add them to an array and print them as soon as you get the error.
Your problem is probably a runtime issue (a second thread updates an involved variable). Since breakpoints only stop the active thread, the second thread gets its work done so the code works.

Categories

Resources