Category Archives: Java

Setting the Classpath from the Command Line in Java

When you compile or run a Java program that depends on classes from other JAR files or locations, the Java runtime needs to know where to find those classes. The classpath is the list of paths that Java checks for classes and resources. In this guide we’ll explore how to set the classpath in a few different ways—via the java and javac commands, through the CLASSPATH environment variable and by using the -cp / -classpath switch.

What Is the Classpath?

The classpath is a logical list of directories, JAR archives, and other resources that the Java Virtual Machine (JVM) searches for class files. When the JVM loads a class, it looks through the entries in this list in order until it finds the class. If the class isn’t found, a ClassNotFoundException (compile time) or NoClassDefFoundError (runtime) is thrown.

Example of a classpath for a simple project might look like this:

/home/user/project/bin:/home/user/lib/commons-io-2.8.0.jar        
Continue reading Setting the Classpath from the Command Line in Java

Handling Exceptions in JAX-RS Jersey with ExceptionMapper

When building RESTful web services, proper exception handling is crucial. Unhandled exceptions can lead to ugly stack traces being sent to the client, exposing internal server details and providing a poor user experience. The JAX-RS specification provides an elegant solution for this: the ExceptionMapper.

In this tutorial, we’ll explore how to use Jersey’s implementation of ExceptionMapper to create centralized, custom, and consistent error responses for our API. We’ll build a simple Spring Boot application with Jersey to demonstrate the concepts.

What is an ExceptionMapper?

An ExceptionMapper is a JAX-RS component that “maps” a Java exception to a javax.ws.rs.core.Response object. When an exception is thrown from a JAX-RS resource method, the framework checks if there’s a registered ExceptionMapper for that specific exception type (or any of its superclasses).

If a mapper is found, its toResponse() method is called. This gives you complete control over the HTTP response sent back to the client, including:

  • The HTTP Status Code (e.g., 404 Not Found, 400 Bad Request, 500 Internal Server Error)
  • The Response Body (e.g., a structured JSON error object)
  • Custom HTTP Headers
Continue reading Handling Exceptions in JAX-RS Jersey with ExceptionMapper

Deep Dive into Java’s PriorityBlockingQueue

Let’s explore a powerful and often-underutilized concurrent collection in Java: the PriorityBlockingQueue. If you’re building multi-threaded applications where task prioritization and producer-consumer patterns are crucial, understanding this class is a game-changer.

The PriorityBlockingQueue is part of Java’s java.util.concurrent package. As its name suggests, it combines the features of a PriorityQueue and a BlockingQueue. Let’s break down what that means.

What is PriorityBlockingQueue?

At its core, PriorityBlockingQueue is an unbounded blocking queue (meaning it doesn’t have a fixed capacity, though memory limits apply) that orders its elements according to their natural ordering, or by a Comparator provided at queue construction time. Elements with higher priority (as defined by their comparison) are retrieved first.

Continue reading Deep Dive into Java’s PriorityBlockingQueue

Java 8 Default Methods: Evolving Interfaces Without Breaking Code

Before Java 8, interfaces were a rigid contract. If you had an interface implemented by dozens of classes across multiple projects, adding a new method to that interface was a developer’s nightmare. Why? Because every single implementing class would instantly break, requiring you to manually add an implementation for the new method. This made evolving APIs incredibly difficult and risky.

Enter Java 8 default methods. This powerful feature changed the game by allowing us to add new, fully-implemented methods directly to interfaces without breaking existing code. Let’s dive into how they work, why they’re essential, and how to handle the complexities they introduce.

What Are Default Methods? The “Why” and “How”

A default method is a method in an interface that has a body. It is declared using the default keyword. If a class implements the interface but does not override the default method, it automatically inherits the default implementation.

Think about the java.util.Collection interface. Imagine the chaos if adding the stream() or forEach() method in Java 8 had broken every single List and Set implementation in the world! Default methods were the elegant solution that allowed the Java API to evolve.

Continue reading Java 8 Default Methods: Evolving Interfaces Without Breaking Code

Integrating Gson with JAX-RS (Jersey) for Seamless JSON Handling

JSON has become the de-facto standard for data exchange in web services, and for Java developers, Gson is a highly popular library for converting Java objects to JSON and vice-versa. When building RESTful APIs with JAX-RS (specifically Jersey), integrating Gson can significantly streamline your development process. This post will guide you through setting up a Jersey project to leverage Gson for automatic JSON serialization and deserialization.

Why Gson with JAX-RS?

While JAX-RS implementations like Jersey often come with their own default JSON providers (like Jackson), Gson offers a lightweight and often more intuitive API for many developers. Its simple approach to serialization and deserialization, along with features like custom type adapters and versioning, makes it a compelling choice for many projects.

Continue reading Integrating Gson with JAX-RS (Jersey) for Seamless JSON Handling

HashMap vs. Hashtable in Java: A Practical Comparison

When you’re working with key-value pairs in Java, the Collections Framework offers several Map implementations. Two of the most frequently discussed are HashMap and Hashtable. While they seem to serve a similar purpose, they have crucial differences that every Java developer must understand. This is a classic Java interview question, but more importantly, choosing the right one has real-world implications for your application’s performance and stability.

Let’s cut to the chase: For almost all new development, you should use HashMap or ConcurrentHashMap. Hashtable is a legacy class that you should generally avoid. This guide will break down why.


Key Differences: HashMap vs. Hashtable

Here are the fundamental distinctions between HashMap and Hashtable, starting with the most important one.

1. Synchronization and Thread-Safety

This is the single most critical difference between the two.

  • Hashtable is synchronized. This means all of its public methods, like put() and get(), are marked with the synchronized keyword. Only one thread can access the Hashtable instance at a time. While this makes it thread-safe, it comes at a significant performance cost due to contention, as threads have to wait for the lock to be released.
  • HashMap is non-synchronized. It makes no guarantees about thread safety. If multiple threads access a HashMap concurrently and at least one of them modifies the map structurally, it can lead to data inconsistency and unexpected behavior. External synchronization is required if you need to use it in a multi-threaded context.
Continue reading HashMap vs. Hashtable in Java: A Practical Comparison

Understanding and Using Java’s CopyOnWriteArrayList

Dealing with concurrent modifications to collections in Java can be a source of tricky bugs. While Collections.synchronizedList() and ConcurrentHashMap offer solutions, sometimes you need a different approach, especially when read operations far outnumber write operations. This is where Java’s CopyOnWriteArrayList shines.

In this post, we’ll dive deep into CopyOnWriteArrayList, exploring its mechanics, use cases, and how it compares to other concurrent collection strategies.

What is CopyOnWriteArrayList?

CopyOnWriteArrayList is a thread-safe variant of ArrayList from the java.util.concurrent package. Its key characteristic, as the name suggests, is that all modifying operations (add, set, remove, etc.) create a fresh, new copy of the underlying array. The original array remains untouched during modification.

This “copy-on-write” strategy ensures that iterators traversing the list will always see a consistent, immutable snapshot of the list at the time the iterator was created. They are never exposed to concurrent modification exceptions (ConcurrentModificationException).

Continue reading Understanding and Using Java’s CopyOnWriteArrayList