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

Java Serialization

Image
I will explain you what is java serialization, then provide you with a sample for serialization. Finally most importantly, lets explore what is inside a serialized object and what it means. That is internals of java serialization and how does it works. If you want to have your own implementation of java serialization, this article will provide you with a good platform to launch. What is Java Serialization? Primary purpose of java serialization is to write an object into a stream, so that it can be transported through a network and that object can be rebuilt again. When there are two different parties involved, you need a protocol to rebuild the exact same object again. Java serialization API just provides you that. Other ways you can leverage the feature of serialization is, you can use it to perform a deep copy. Why I used ‘primary purpose’ in the above definition is, sometimes people use java serialization as a replacement for database. Just a placeholder where you can persist an...

Iterate Through a HashMap

The  HashMap  is one of the most useful data structures in the Java programming language. Once you have a HashMap filled with data, you may want to iterate through its keys and values. Below are three different ways to iterate through a Java HashMap. Sample HashMap Here is our sample HashMap. The key is an Integer and the value is a String: HashMap <Integer, String> hm = new HashMap<Integer, String>(); hm.put(0, "zero"); hm.put(1, "one"); hm.put(2, "two"); In the above Java code, we first declare the HashMap. Then we add the values "zero", "one" and "two" with the keys 0, 1 and 2 respectively. Now that the HashMap has data, we can try to iterate over the keys and values. Iteration Example 1 for (int i=0; i < hm.size(); i++) { Integer key = hm.keySet().toArray()[i]; String val = hm.values().toArray()[i]; System.out.println("key,val: " + key + "," + val); } In this example, we use a  for  loop ...

Difference between left and right outer join

There are two kinds of OUTER joins in SQL, LEFT OUTER join and RIGHT OUTER join. Main difference between RIGHT OUTER join and LEFT OUTER join, as there name suggest, is inclusion of non matched rows. Sine INNER join only include matching rows, where value of joining column is same, in final result set, but OUTER join extends that functionality and also include unmatched rows in final result. LEFT outer join includes unmatched rows from table written on left of join predicate. On the other hand RIGHT OUTER join, along with all matching rows, includes unmatched rows from right side of table. In short result of LEFT outer join is INNER JOIN + unmatched rows from LEFT table and RIGHT OUTER join is INNER JOIN + unmatched rows from right hand side table. Similar to difference between INNER join and OUTER join, difference between LEFT andRIGHT OUTER JOIN can be better understand by a simple example, which we will see in next section. LEFT and RIGHT OUTER Join Example in SQL In order to unders...

Failfast Vs Failsafe in Java

Difference between fail-safe and fail-fast Iterator is becoming favorite core java interview questions day by day, reason it touches concurrency a bit and interviewee can go deep on it to ask how fail-safe or fail-fast behavior is implemented .  How does a system react when there is a failure characterizes it as a fail fast or a fail safe system. This article is to discuss whether fail safe or fail fast is better. Then what it has to do with java. Concept of fail-safe iterator are relatively new in Java and first introduced with Concurrent Collections in Java 5 like ConcurrentHashMap and CopyOnWriteArrayList. fail-fast Iterators in Java As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun . Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. fail-fast behavior is implemented by keepinga modification count and if iterat...

Atomic Variables in Java

Atomic is a toolkit of variable java.util.concurrent.atomic package classes, which assist in writing lock and wait-free algorithms with the Java language. When a data (typically a variable) can be accessed by several threads, you must synchronize the access to the data to ensure visibility and correctness. By example, if you have a simple counter: public class Counter { private int value; public int getValue(){ return value; } public int getNextValue(){ return value++; } public int getPreviousValue(){ return value--; } } This class works really well in single-threaded environment, but don’t work at all when several threads access the same Counter instance. You can solve the problem using synchronized method as below public class SynchronizedCounter { private int value; public synchronized int getValue(){ return value; } public synchronized int getNextValue(){ return value++; } public synchronize...

Race Condition in Java

Race condition in Java  is a type of concurrency bug or issue which is introduced in your program because  parallel execution of your program by multiple threads at same time, Since Java is a multi-threaded programming language hence risk of Race condition is higher in Java which demands clear understanding of what causes a race condition and how to avoid that. Anyway Race conditions are just one of hazards or riskpresented by  use of multi-threading in Java just like deadlock in Java.  Race conditions  occurs when two thread operate on same object without proper synchronization and there operation interleaves on each other. Classical  example  of Race condition  is incrementing a counter since increment is not an atomic operation and can be further divided into three steps like read, update and write. if two threads tries to increment count at same time and if they read same value because of interleaving of read operation of one thread to update operation of another thread, one count ...

Comparable Vs Comparator interface

1) Comparator in Java is defined in  java.util  package while Comparable interface in Java is defined in  java.lang  package. 2) Comparator interface in Java has method  public int  compare (Object o1, Object o2)  which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method  public int compareTo(Object o)  which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. 3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified. 4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface. 5) If any class implement Comparable interface in Java then collection of that object e...

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