Showing posts with label debug. Show all posts
Showing posts with label debug. Show all posts

Friday, 24 June 2011

Naming threads created with the ExecutorService

When profiling applications it sometimes becomes a pain to understand where so many threads come from and what the hell they are doing.






If you’re like me and have a dependency on java.util.concurrent‘s API’s for anything concurrency-related, then you’ve certainly noticed that default thread names aren’t particularly helpful with the aforementioned problem.
Here’s a quick & dirty implementation of a ThreadFactory (based on Executors.DefaultThreadFactory) but with support for your own thread name prefixes.

public class NamedThreadFactory implements ThreadFactory {

// constants -----------------------------------------------------------------

private static final AtomicInteger POOL_NUMBER = new AtomicInteger(1);

// internal vars -------------------------------------------------------------

private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;

// constructors --------------------------------------------------------------

public NamedThreadFactory() {
this("ThreadPool(" + POOL_NUMBER.getAndIncrement() + "-thread-");
}

public NamedThreadFactory(String namePrefix) {
SecurityManager s = System.getSecurityManager();
this.group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
this.namePrefix = namePrefix + "(pool" +
POOL_NUMBER.getAndIncrement() + "-thread-";
}

// ThreadFactory -------------------------------------------------------------

public Thread newThread(Runnable r) {
Thread t = new Thread(this.group, r, this.namePrefix +
this.threadNumber.getAndIncrement() + ")", 0L);
if (t.isDaemon()) {
t.setDaemon(false);
}
if (t.getPriority() != Thread.NORM_PRIORITY) {
t.setPriority(Thread.NORM_PRIORITY);
}
return t;
}
}
Tip: If you’re using Spring, you can just use CustomizableThreadFactory and save yourself the trouble.

Monday, 6 June 2011

Debug with Step Filters in Eclipse

Eclipse tip: Add a short cut key to Skip All Breakpoints

Eclipse doesn’t have a short cut key bound by default to the ‘Skip all breakpoints’ functionality. So again and again I had to manually skip the breakpoints.
Here is how you can set the short key. While you are at it, you probably want to define a few more shortcuts to functionality you use frequently.
In Eclipse, go to Window > Preferences > Type in ‘Keys’ in the search box > Select ‘Keys‘ to get the screen to edit the command bindings.
Search for the ‘Skip All Breakpoints’ command. Add your preferred shortcut at the Binding field, and in When use debugging.
 I use Ctrl+Alt+B. So when I press Ctrl+Alt+B all break points are skipped. If I again press it all breakpoints are restored.
If you toggle that bit of functionality as often as I do, you know this is gonna save you a bunch of time.