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...

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...

Java Thread Life Cycle

Image
When you are programming with threads, understanding the life cycle of thread is very valuable. While a thread is alive, it is in one of several states. New state:  After the creations of Thread instance the thread is in this state but before the start() method invocation. At this point, the thread is considered not alive. Runnable (Ready-to-run) state :  A thread start its life from Runnable state. A thread first enters runnable state after the invoking of start() method but a thread can return to this state after either running, waiting, sleeping or coming back from blocked state also. On this state a thread is waiting for a turn on the processor. Running state :  A thread is in running state that means the thread is currently executing. There are several ways to enter in Runnable state but there is only one way to enter in Running state: the scheduler select a thread from runnable pool. Dead state:  A thread can be considered dead when its run() method completes. If any thre...

How HashMap works in Java

How HashMap works in Java or sometime how get method work in HashMap is common questions on Java interviews now days. Almost everybody who worked in Java knows about HashMap, where to use HashMap or difference between Hashtable and HashMap then why this interview question becomes so special? Because of the depth it offers. It has become very popular java interview question in almost any senior or mid-senior level Java interviews. Investment banks mostly prefer to ask this question and some time even ask to implement your own HashMap based upon your coding aptitude. Introduction of ConcurrentHashMap and other concurrent collections has also made this questions as starting point to delve into more advanced feature. let's start the journey. Questions start with simple statement "Have you used HashMap before" or "What is HashMap? Why do we use it “ Almost everybody answers this with yes and then interviewee keep talking about common facts about HashMap like HashMap accep...

URI v/s URL

Before going into URL and URI, you need to know some background. Do you ever thought about, who decides what is URL? and what is URI? or who is the authority for URL, URI and such naming conventions? W3C and IETF There are two separate bodies W3C and IETF. The World Wide Web Consortium (W3C) is the main international standards organization for the World Wide Web. The specifications for URI and URL are defined by W3C. It was founded and headed by Sir Tim Berners-Lee. He is one of the greatest scientist living now. He created this www model of server and client architecture, a web server serving web pages through network and client browsers reading it. He did it first when he was with CERN. He created the world’s first web page http://info.cern.ch/ . He was also in HTML 2.0 working group of IETF. So it is very appropriate for W3C to define URI and URL. Internet Engineering Task Force (IETF) is an open international community working on Internet related standards. In general it addresses ...

Exception Handling -1

Image
Java has many wonderful things and exception handling is one among them. Exception handling is a framework provided by Java to ensure program execution continues in an unfavorable problem condition by handling it gracefully. Exception handling is not new to Java guys and I need not give a heroic introduction to it. This is my attempt at writing a detailed tutorial like a chapter in a Java book, by giving comprehensive coverage to this topic accompanied by code examples, images, bells and whistles. I will give a simple and easy to understand narrative to java exception handling and try to uncover intricate detail as much as possible in my own style. As exception handling is a large topic, this will be a multi-part series. I chose to use the word problem instead of error in the above definition. Error is a java class and given a specific meaning in Java exception handling and I didn’t want that to be mixed with the general English word which denotes an unfavorable condition. Google says,...

Implementing Producer / Consumer using SynchronousQueue

Among plenty of useful classes which Java provides for concurrency support, there is one I would like to talk about: SynchronousQueue . In particular, I would like to walk through Producer / Consumer implementation using handy SynchronousQueue as an exchange mechanism. It might not sound clear why to use this type of queue for producer / consumer communication unless we look under the hood of SynchronousQueue implementation. It turns out that it's not really a queue as we used to think about queues. The analogy would be just a collection containing at most one element. Why it's useful? Well, there are several reasons. From producer's point of view, only one element (or message) could be stored into the queue. In order to proceed with the next element (or message), the producer should wait till consumer consumes the one currently in the queue. From consumer's point of view, it just polls the queue for next element (or message) available. Quite simple, but the great ben...