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

WeakHashMap in Java

A WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference . By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. This makes the WeakHashMap an excellent implementation for a weakly referenced list, where entries that aren't used elsewhere may be dropped with no side effects. Also, just because a key may be dropped, doesn't mean it will immediately be dropped. If the system has sufficient resources, the weak key reference that isn't externally referenced could stay around for a long time. This class provides the easiest way to harness the power of weak references. It is useful for implementing "registry-like" data structures, where the utility of an entry vanishes when its key is no longer reachable by any thread. The WeakHashMap functions identically to the HashMap with one very important exception: if...

StringTokenizer

The processing of String often consists of parsing a formatted input string.  Parsing  is the division of text into a set of discrete parts, or  tokens,  which in a certain sequence can convey a semantic meaning. The  StringTokenizer  class provides the first step in this parsing process, often called the  lexer  (lexical analyzer) or  scanner .  StringTokenizer  implements the  Enumeration  interface. Therefore, given an input string, you can enumerate the individual tokens contained in it using  StringTokenizer . To use  StringTokenizer , you specify an input string and a string that contains delimiters.  Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example,  ",;:"  sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return. StringTokenizer Example import java.util.*; class StringTokenizerDemo...

hashcode and equals methods

Equals and hashcode methods are two primary but yet one of most important methods for java developers to be aware of. Java intends to provide equals and hashcode for every class to test the equality and to provide a hash or digest based on content of class. Importance of hashcode increases when we use the object in different collection classes which works on hashing principle e.g. hashtable and hashmap. A well written hashcode method can improve performance drastically by distributing objects uniformly and avoiding collision. General Contracts for hashCode() in Java  1) If two objects are  equal  by equals() method then there  hashcode  returned by hashCode() method must be same. 2) Whenever  hashCode() mehtod  is invoked on the same object more than once within single execution of application, hashCode() must return same integer provided no information or fields used in equals and hashcode is modified. This integer is not required to be same during multiple execution of application th...

Inheritance versus Composition

The two most common techniques for reusing functionality in object-oriented systems are class inheritance and object composition. Class inheritance lets you define the implementation of one class in terms of another's. Reuse by subclassing is often referred to as white-box reuse. The term "whitebox" refers to visibility: With inheritance, the internals of parent classes are often visible to subclasses. Object composition is an alternative to class inheritance. Here, new functionality is obtained by assembling or composing objects to get functionality that is more complex. Object composition requires that the objects being composed have well-defined interfaces. This style of reuse is called black-box reuse, because no internal details of objects are visible. Objects appear only as "black boxes." Inheritance and composition each have their advantages and disadvantages. Class inheritance is defined statically at compile-time and is straightforward to use, since it ...

calculate date time difference using Java

In this tutorial we will see how to calculate date time difference using Java library. Below is the program, package in.softcare; import java.text.SimpleDateFormat; import java.util.Date; public class DateTimeCalculation { public static void main(String[] args) { String dateStart = "03/14/2013 09:29:58"; String dateStop = "03/16/2013 11:31:48"; //HH converts hour in 24 hours format (0-23), day calculation SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); //in milliseconds long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000) % 24; long diffDays = diff / (24 * 60 * 60 * 1000); System.out.print(diffDays + " days, "); System.out.print(diffHours + " hours, "); System.out...

JDBC Batch Insert

Let’s see how we can perform JDBC Batch Insert in Java. Although you might already knew this, I will try to explain this with different scenarios. In this note, we will see how we can use JDBC APIs like Statement and PreparedStatement to insert data in any database in batches. Also we will try to explore scenarios where we can run out of memory and how to optimize the batch operation. So first, the basic API to Insert data in database in batches using Java JDBC. Simple Batch I am calling this a simple batch. The requirement is simple. Execute a list of inserts in batch. Instead of hitting database once for each insert statement, we will using JDBC batch operation and optimize the performance. Consider the following code: Bad Code String [] queries = {     "insert into employee (name, city, phone) values ('A', 'X', '123')",     "insert into employee (name, city, phone) values ('B', 'Y', '234')",     "insert into ...

JDBC Interview Question

Java Database Connectivity API contains commonly asked Java interview questions. A good understanding of JDBC API is required to understand and leverage many powerful features of Java technology. Here are few important practical questions and answers which can be asked in a Core Java JDBC interview. [expand title="What are available drivers in JDBC?"] JDBC technology drivers fit into one of four categories: A  JDBC-ODBC bridge  provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see  JDBC-ODBC Bridge Driver . A  native-API partly Java technology-enabled driver  converts JDBC calls into calls on the client API for...

Java Collection Interview Questions-2

Java Collections Framework are the fundamental aspect of java programming language. It’s one of the important topic for java interview questions. Here I am listing some important questions and answers for java collections framework. [expand title="What is an Iterator"] Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.[/expand]   [expand title="Difference between HashMap and HashTable? Compare Hashtable vs HashMap?"] Both Hashtable & HashMap provide key-value access to data. The Hashtable is one of the original collection classes in Java (also called as legacy classes). HashMap is part of the new Collectio...

Java Collection Interview Questions-1

Java Collections Framework are the fundamental aspect of java programming language. It’s one of the important topic for java interview questions. Here I am listing some important questions and answers for java collections framework. [expand title="What is Java Collections API?"] Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming. In nutshell, this API does 6 things at high level Reduces programming efforts. - Increases program speed and quality. Allows interoperability among unrelated APIs. Reduces effort to learn and to use new APIs. Reduces effort to design new APIs. Encourages & Fosters software reuse. To be specific, There are six collection java interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and Sorted...

Spring Interview Questions

Image
Spring interview questions  is in rise on J2EE and core Java interviews,  As Spring is the best framework available for Java application development and now  Spring IOC container  and Spring MVC framework are used as de-facto framework for all new Java development. We will be adding the more number of questions from readers request. If you are looking for any specific questions and doubts, please post your queries in the comments section of this article. We will update the questions and send you the remainder about the update.  Also don’t forget to leave the feedback about the questions in this article and provide suggestions. [expand title="(1)What is Spring Framework?"] Spring  is a lightweight inversion of control and aspect-oriented container framework. Spring Framework’s contribution towards java community is immense and spring community is the largest and most innovative community by size. They have numerous projects under their portfolio and have their own spring dmSer...

How to create Immutable Class in Java

Writing or creating immutable classes in Java is becoming popular day by day, because of concurrency and multithreading advantage provided by immutable objects. Immutable objects offers several benefits over conventional mutable object, especially while creating concurrent Java application. Immutable object not only guarantees safe publication of object’s state, but also can be shared among other threads without any external synchronization. In fact JDK itself contains several immutable classes like String, Integer and other wrapper classes. For those, who doesn’t know what is immutable class or object, Immutable objects are those, whose state can not be changed once created e.g. java.lang.String, once created can not be modified e.g. trim, uppercase, lowercase. All modification in String result in new object, see why String is immutable in Java for more details. In this Java programming tutorial, we will learn, how to write immutable class in Java or how to make a class immutable. By ...

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