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

How to check if String Starts with one of the several prefixes

Image
In my current project I had requirement to find if given string starts with any of provided prefixes or not. If yes then do special handling otherwise normal processing.  There are few ways to achieve this, mentioned below. Please comment if you know any better way or problem in below approaches.   (1) Iteration and use startsWith() method This has limitation if search string varies over period of time, we might need to recompile code. This will take longer if search string list is too large static void javaStdWay (String testString, List<String> searchStringList) { boolean flag = false ; for (String searchSt : searchStringList) { if (testString. toUpperCase (). startsWith (searchSt. toUpperCase ())) { System. out . println ( "TestString {" + testString + "} starts with " + searchSt); flag = true ; } } if (!flag) { ...

Printing Object Properties - RecursiveToStringStyle

Image
It would be sometime challenging to print/log object properties when toString method is not overriden in  class. We can use reflection to retrieve and print values but it would become tricky when object has other object refrences and so on. Apache provides very good implementation (http://commons.apache.org/proper/commons-lang/download_lang.cgi) to solve the problem. I will try to explain this with simple example. I have Employee Object having two properties employeeId(Numer) and department (Type Department), While Department object has two properties departmentName (String) and address (Type Address), while Address has three properties houseNumber, StreetName, and Pincode. public class Employee { private Number employeeId; private Department department; public Department getDepartment () { return department; } public void setDepartment (Department department) { this . department = department; } public Number getEmployId () {...

CaseInsensitiveMap

Image
How to ignore case sensitivity when searching a key in the java.util.Map? There are multiple ways to achieve this (1) We can  use a  TreeMap  instead of  HashMap , then specify a Comparator with a case insensitive order ( String.CASE_INSENSITIVE_ORDER ) package in. softcaretech ; import java.util.Map; import java.util.TreeMap; public class TreeMapDemo { public static void main (String args[]){ Map<String, String> studentMap = new TreeMap<String, String>(String. CASE_INSENSITIVE_ORDER ); studentMap. put ( "Amit" , "Audi" ); studentMap. put ( "Nilesh" , "BMW" ); System. out . println ( "Searchnig AMIT Key from map:" + studentMap. get ( "AMIT" )); System. out . println ( "Searchnig amit Key from map:" + studentMap. get ( "amit" )); } } (2)  You can write a wrapper map class with custom put and get methods (converting keys to lower case or...

Java Collections - hashCode() and equals() methods

Image
We will discuss about hashcode() and equals() methods of Object class and what role they play in an object life cycle. The methods  hashCode()  and  equals()  play a distinct role in the objects identity you insert into collections. The specific contract rules of these two methods are best described in the JavaDoc, here I will just describe what role they play, What they are used for, so you know why their implementation is important. Both equals() and hashcode()   are defined in  java.lang.Object  class and their default implementation is based upon Object information e.g. default  equals()  method return  true,  if two objects are exactly same i.e. they are pointing to same memory address, while default implementation of hashcode method return  int  and implemented as native method. Equals: This particular method is used to make equal comparison between two objects. There are two types of compari...

Hibernate-Object state transitions

Image
 Transient instances –instances of a persistent class instantiated with the new operator –transient, they have no persistent state –garbage collected if dereferenced by the application –have no database identity  Transient instances may be made persistent by –calling Session.save(object) –creating a reference from another instance that is already persistent  Persistent instances –include any instance retrieved with a query, lookup by identifier or navigation –are managed, changes are automatically flushed to the database –are transactional, changes can be rolled back in the database only –have database identity  Persistent instances may be made transient by –calling Session.delete(object) –“orphan delete” (later)  Detached instances –are instances with database identity that are not associated with any open Session –are no longer managed by Hibernate –represent database state, that is potentially stale  Persistent instances become detached by –calling Sessi...

Facts about HashMap in Java 6

Image
  Few points regarding HashMap DS in Java 6 as per the source code. HashMap extends AbstractMap implements Map Backed by array of Map.Entry where each element points to a list of Map.Entry  Default Initial Capacity – 16 i.e. Entry[16] Default load factor  - 0.75 i.e. when size reaches 75% of capacity – resizing of internal data structure is triggered. Capacity is always in power of 2 - if 5 is passed as initialCapacity in constructor, capacity will be set to 8 – it just does bitwise shift of 1 until it gets a number just greater than the passed capacity value. If 8 is passed – actual capacity will be 16 . (for detail check source code) provides a hook method init() which subclasses can use for addition functionality- it is invoked from constructor. modCount member variable to track the modifications in hashmap. same is used for Fail-fast detection modifications means adding new Entry and removing Entry  from hashmap provide supplemen...

ConcurrentHashMap

Image
J ava thread safety problems can bring down your Java EE application and the Java EE container fairly easily. One of most common problems I have observed when troubleshooting Java EE performance problems is infinite looping triggered from the non-thread safe HashMap get() and put() operations. There seem to be three different synchronized Map implementations in the Java API: Hashtable Collections.synchronizedMap(Map) ConcurrentHashMap ConcurrentHashMap in Java is introduced as an alternative of Hashtable in Java 1.5 as part of Java concurrency package. Prior to Java 1.5 if you need a Map implementation, which can be safely used in a concurrent and multi-threaded Java program, than, you only have Hashtable or synchronized Map because HashMap is not thread-safe. With ConcurrentHashMap, now you have better choice; because, not only it can be safely used in concurrent multi-threaded environment but also provides better performance...

Singleton Collection Classes

Image
Singletons are useful to provide a unique source of data or functionality to other Java Objects. Collection framework provides singleton classes for each collection class like SingletonList and SingletonMap.   In this article we will discuss about SingletonList which is equally applicable to other singleton collection classes. Collections Class provide method to convert normal list into singletonList like below syntax, List<String> mySingletonList = Collections. singletonList ( "AAA" ); Java documentation says "Returns an immutable list containing only the specified object. The returned list is serializable." Why we need this type single object Immutable list? Below is the code to remove all null values from list - in conventional style: package singleton; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class SingletonListTest { public static void main (String[] args) { List ...