Category Archives: java

Setting log4j log level programmatically

Sometimes you don’t want to ship a log4j.properties file — you want to spin up logging in code. Useful inside unit tests, one-off debug runs, or anywhere you want to flip log levels at runtime. Here’s a self-contained setupLog4j() that … Continue reading

Posted in java | Leave a comment

Print java stack trace from anywhere

Need to know which code calls a specific location? Dump the stack trace: 1234import org.apache.commons.lang3.exception.ExceptionUtils; // …somewhere in your method: LOG.trace(ExceptionUtils.getStackTrace(new Throwable())); You’re constructing a Throwable just to capture the current stack — you’re not throwing it. ExceptionUtils.getStackTrace turns the … Continue reading

Posted in java | Leave a comment

Knowing your exception class name

You’re staring at a generic catch (Exception e) and you don’t know which actual exception is being thrown. The trick is to log the runtime class so you can replace the generic catch with a specific one: 12345} catch (Exception … Continue reading

Posted in java | Tagged | Leave a comment

Ant Junit debugging

Sometime we want to debug why ant build failed when executing a certain JUnit Make sure your ant junit task look like the following 1234<junit printsummary="withOutAndErr" haltonfailure="yes"> : : </junit> and not like 1234<junit printsummary="yes" haltonfailure="yes"> : : </junit>

Posted in java | Leave a comment

Java Flight Recorder: a profiler that’s already in your JVM

If you’re running anything on the JVM (Java Virtual Machine) in production and you’ve never opened a Flight Recorder file, you’re leaving a free profiler on the table. Java Flight Recorder (JFR) is a low-overhead event recorder built into the … Continue reading

Posted in java | Leave a comment

Multithreading in Java using ThreadPoolExecutor

ThreadWorker is your custom class. 123456789try { ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(MAX_THREAD_SIZE); for (int i = 1; i Random randomGenerator = new Random(); executor.submit(new ThreadWorker("worker" + i, randomGenerator.nextInt(10))); LOG.info(i); } } catch (Exception e) { LOG.error("Hmm something is not right.", … Continue reading

Posted in java | Leave a comment

Getting the caller method details using Java

12345678910 public static String getCallerClassName() {         StackTraceElement[] stElements = Thread.currentThread().getStackTrace();         for (int i=1; i<stElements.length; i++) {             StackTraceElement ste = stElements[i];             if … Continue reading

Posted in java | Leave a comment