Posts

Observability Done Right: Best Practices and Anti-Patterns for Effective System Monitoring

Image
  WHAT Observability is a concept that refers to the ability to gain insights into the behavior and performance of complex systems. In the context of software engineering, observability involves the collection, analysis, and visualization of data from software applications, infrastructure, and other components of a system. In the animal kingdom, observability plays a critical role in survival, allowing animals to monitor their surroundings, detect threats, and find food. Dolphins use echolocation to observe their surroundings. They emit high-frequency sounds that bounce off objects, allowing them to create a 3D map of their environment. Thanks for reading Knowledge Cafe! Subscribe for free to receive new posts and support my work. Subscribed WHY In today's era, architectures are becoming increasingly large, complex, and fast-paced due to the faster development and deployment of software by distributed teams with the help of DevOps, continuous delivery, and agile development methodo...

Spring Interceptor for logging

Spring Interceptors has the ability to pre-handle and post-handle the web requests. Each interceptor class should extend the  HandlerInterceptorAdapter  class. Here we will create a Logger Interceptor by extending the  HandlerInterceptorAdapter  class. You can override any of the three callback methods preHandle() ,  postHandle()  and  afterCompletion() . As the names indicate the  preHandle()  method will be called before handling the request, the  postHandle()  method will be called after handling the request and the  afterCompletion()  method will be called after rendering the view. In each method we will log information using log4j. First instantiate the logger in the static context, then set up the basic configuration so that the log messages will be logged on the console. The  LoggerInterceptor  class is shown below. package sct.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.BasicConfigurator; impo...

Spring JDBC

In this example you will learn how the Spring JDBCTemplate simplifies the code you need to write to perform the database-related operations. The insertForum() method below shows the amount of code you need to write to insert data using JDBC. package com.sct.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.sql.DataSource; import com.sct.domain.Forum; public class JDBCForumDAOImpl implements ForumDAO { private DataSource dataSource; public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void insertForum(Forum forum) { /** * Specify the statement */ String query = "INSERT INTO FORUMS (FORUM_ID, FORUM_NAME, FORUM_DESC) VALUES (?,?,?)"; /** * Define the connection and preparedStatement parameters */ Connection connection = null; PreparedStatement preparedStatement = null; try { /** * Open the connection */ connect...

Java 7-Precise Rethrow Exception

Previously, rethrowing an exception was treated as throwing the type of the catch parameter. For example, let's say that your try block could throw a ParseException or an IOException . To intercept all exceptions and rethrow them, you would have to catch Exception and declare your method as throwing an Exception . This is "imprecise rethrow", because you are throwing a general Exception type (instead of specific ones) and statements calling your method need to catch this general Exception . This is illustrated below: //imprecise rethrow. //must use "throws Exception" public static void imprecise() throws Exception{ try { new SimpleDateFormat("yyyyMMdd").parse("foo"); new FileReader("file.txt").read(); } catch (Exception e) { System.out.println("Caught exception: " + e.getMessage()); throw e; } } However, in Java 7, you can be more precise about the exception types being rethr...

New Java 7 Features: The Try-with-resources Language Enhancement

This article examines the use of the  try-with-resources  statement. This is a try statement that declares one or more resources. A resource is as an object that must be closed after the program is finished with it.   The  try-with-resources  statement ensures that each resource is closed at the end of the statement. Any object that implements the java.lang.AutoCloseable or java.io.Closeable interface can be used as a resource. Prior to  try-with-resources  (before Java 7) while dealing with SQL Statement or ResultSet or Connection objects or other IO objects one had to explicitly close the resource. So one would write something like: try{ //Create a resource- R } catch(SomeException e){ //Handle the exception } finally{ //if resource R is not null then try{ //close the resource } catch(SomeOtherException ex){ } } We have to explicitly close the resource and thereby add a few more lines of code. There are few cases where the developer will forget to cl...

Code Refactoring

Continuous Refactoring  by Michael Hunger Code bases that are not cared for tend to rot. When a line of code is written it captures the information, knowledge, and skill you had at that moment. As you continue to learn and improve, acquiring new knowledge, many lines of code become less and less appropriate with the passage of time. Although your initial solution solved the problem, you discover better ways to do so. It is clearly wrong to deny the code the chance to grow with knowledge and abilities. While reading, maintaining, and writing code you begin to spot pathologies, often referred to as  code smells . Do you notice any of the following? Duplication, near and far Inconsistent or uninformative names Long blocks of code Unintelligible boolean expressions Long sequences of conditionals Working in the intestines of other units (objects, modules) Objects exposing their internal state When you have the opportunity, try deodorizing the smelly code. Don’t rush. Just take...

Java Generics

Image
Generics is a Java feature that was introduced with Java SE 5.0 and, few years after its release, I swear that every Java programmer out there not only heard about it, but used it. There are plenty of both free and commercial resources about Java generics.  Despite the wealth of information out there, sometimes it seems to me that many developers still don’t understand the meaning and the implications of Java generics. That’s why I’m trying to summarize the basic information developers need about generics in the simplest possible way. The Motivation for Generics The simplest way to think about Java generics is thinking about a sort of a syntactic sugar that might spare you some casting operation: 1 List<Apple> box = ...; 2 Apple apple = box.get(0); The previous code is self-speaking: box is a reference to a List of objects of type Apple. The get method returns an Apple instance an no casting is required. Without generics, this code would have been: 1 List box = ...; 2 Apple apple...

Synchronized - Java Keyword

1.   Synchronized keyword in Java  is used to provide mutual exclusive access of a shared resource with multiple threads in Java. Synchronization in java guarantees that no two threads can execute a synchronized method which requires same lock simultaneously or concurrently. 2. You can use java synchronized keyword only on synchronized method or synchronized block. 3. When ever a thread enters into java synchronized method or block it  acquires a lock  and whenever it leaves java synchronized method or block it releases the lock. Lock is released even if thread leaves synchronized method after completion or due to any Error or Exception. 4. Java Thread acquires an  object level lock  when it enters into an instance synchronized java method and acquires a class level lock when it enters into static synchronized java method. 5. J ava synchronized keyword is re-entrant in nature  it means if a java synchronized method calls another synchronized method which requires same lock then cur...

Java Multithreading Interview

Multi-threading and concurrency questions are essential part of any Java interview. If you are going for any Java interview on any Investment bank for equities front office position expect lots of muti-threading interview questions on your way. Multi-threading and concurrency is a favorite topics on Investment banking specially on electronic trading development and they grill candidate on many confusing java thread interview questions. They just want to ensure that the guy has solid knowledge of multi-threading and concurrent programming in Java because most of them are in business of performance. High volume and low latency Electronic trading System which is used for Direct to Market (DMA) trading is usually concurrent in nature. These are my favorite thread interview questions on Java asked on different on different time. I am not providing answer of these thread interview questions but I will give you hint whenever possible, some time hint is enough to answer. I will update the post...

Java Singleton Design Pattern

1.1. Overview A singleton in Java is a class for which only one instance can be created provides a global point of access this instance. The singleton pattern describe how this can be archived. Singletons are useful to provide a unique source of data or functionality to other Java Objects. For example you may use a singleton to access your data model from within your application or to define logger which the rest of the application can use. 1.2. Code Example The possible implementation of Java depends on the version of Java you are using. As of Java 6 you can singletons with a single-element enum type. This way is currently the best way to implement a singleton in Java 1.6 or later according to tht book ""Effective Java from Joshua Bloch. package mypackage; public enum MyEnumSingleton { INSTANCE; // other useful methods here }   Before Java 1.6 a class which should be a singleton can be defined like the following. public class Singleton { private static Singleton uniqIn...

Java File I/O

Java I/O is very interesting and much discussed feature of JAVA. There are few open-source library as well to make programmer's life easy. Here I will discuss only file reading example. My favorite way to read a small file is to use a BufferedReader and a StringBuilder. It is very simple and to the point (though not particularly effective, but good enough for most cases): BufferedReader br = new BufferedReader(new FileReader("file.txt")); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append("n"); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } When I read strings like this, I usually want to do some string handling per line anyways, so then I go for this implementation. One more way is to use the Scanner class in Java and the FileReader object simple examep...

Chain of responsibility using Spring @Autowired List

Image
There is a way in Spring 3.1 to auto populate a typed List which is very handy when you want to push a bit the decoupling and the cleaning in your code. To show you how it works, I will implement a simple chain of responsibility that will take care of printing some greetings for a passed User. Let start from the (only) domain class we have, the User: package in.softcaretech.springchain; public class User { private final String name; private final char gender; public User(String name, char gender) { super(); this.name = name; this.gender = gender; } public String getName() { return name; } public char getGender() { return gender; } } Then we create an interface that defines the type for our command objects to be used in our chain: package in.softcaretech.springchain; public interface Printer { void print(User user); } This is the generic class (the template) for a Printer implementation. The  org.springframework.core.Ordered  is used to tell the AnnotationAwareOrderCo...

JSP include directive and JSP include action

UPDATE http://amit.softcaretech.in/blog/static-include-vs-dynamic-include-in-jsp/ <%@ include file=”filename” %> is the JSP include directive. At JSP page translation time, the content of the file given in the include directive is ‘pasted’ as it is, in the place where the JSP include directive is used. Then the source JSP page is converted into a java servlet class. The included file can be a static resource or a JSP page. Generally JSP include directive is used to include header banners and footers. The JSP compilation procedure is that, the source JSP page gets compiled only if that page has changed. If there is a change in the included JSP file, the source JSP file will not be compiled and therefore the modification will not get reflected in the output. <jsp:include page=”relativeURL” /> is the JSP include action element. The jsp:include action element is like a function call. At runtime, the included file will be ‘executed’ and the result content will be included with t...

Callable vs Runnable

Callable interface public interface Callable<V>, where V is the return type of the method call. This interface has a single method 'call', which needs to be defined by all the classes which implement this interface. This method takes no arguments and returns a result of type V. This method can throw checked exceptions as well. Runnable interface public interface Runnable - this interface is implemented by those classes whose instances are supposed to be executed in a different thread. This interface has only one method 'run', which takes no arguments and obviously all the classes implementing this interface need to define this method. This interface is implemented by the Thread class as well and it's a common protocol for all the objects who wish to execute in a different thread. It's one of the ways of creating threads in Java. The other way to create a thread is by sub-classing theThread class. A class implementing Runnable interface can simply pass itse...