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 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 Collections Framework, added with Java 2, v1.2. There are several differences between HashMap and Hashtable in Java as listed below

  • The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).

  • HashMap does not guarantee that the order of the map will remain constant over time. But one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.

  • HashMap is non synchronized whereas Hashtable is synchronized.

  • Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn't. So this could be a design consideration.[/expand]


 

[expand title="What does synchronized means in Hashtable context?"]
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.[/expand]

 

[expand title="What is fail-fast property?"]

At high level - Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production. In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. [/expand]

 

[expand title="Why doesn't Collection extend Cloneable and Serializable?"]

From Sun FAQ Page: Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable. If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one. Note on Some Important Terms
Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
Fail-fast is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown. [/expand]

 

[expand title="How can we make Hashmap synchronized?"]

HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap); [/expand]

 

[expand title="Where will you use Hashtable and where will you use HashMap?"]

There are multiple aspects to this decision: 1. The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one. 2. If there is a possibility in future that - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes. [/expand]

 

[expand title="Can we use any class as Map key?"]

We can use any class as Map Key, however following points should be considered before using them.

  • If the class overrides equals() method, it should also override hashCode() method.

  • The class should follow the rules associated with equals() and hashCode() for all instances. Please refer earlier question for these rules.

  • If a class field is not used in equals(), you should not use it in hashCode() method.

  • Best practice for user defined key class is to make it immutable, so that hashCode() value can be cached for fast performance. Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issue with mutability.
    For example, let’s say I have a class MyKeythat I am using for HashMap key. 
    	//MyKey name argument passed is used for equals() and hashCode()
    MyKey key = new MyKey('Amit'); //assume hashCode=1234
    myHashMap.put(key, 'Value');

    // Below code will change the key hashCode() and equals()
    // but it's location is not changed.
    key.setName('Amit1'); //assume new hashCode=7890

    //below will return null, because HashMap will try to look for key
    //in the same index as it was stored but since key is mutated,
    //there will be no match and it will return null.
    myHashMap.get(new MyKey('Amit'));

    This is the reason why String and Integer are mostly used as HashMap keys.


[/expand]
[expand title="What are concurrent Collection Classes?"]
Java 1.5 Concurrent package (java.util.concurrent) contains thread-safe collection classes that allow collections to be modified while iterating. By design iterator is fail-fast and throws ConcurrentModificationException. Some of these classes areCopyOnWriteArrayListConcurrentHashMapCopyOnWriteArraySet. [/expand]

 

[expand title="Can a null element added to a Treeset or HashSet?"]
A null element can be added only if the set contains one element because when a second element is added then as per set defination a check is made to check duplicate value and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element. [/expand]

 

[expand title="What is difference between Comparable and Comparator interface?"]

Comparable and Comparator interfaces are used to sort collection or array of objects.Comparable interface is used to provide the natural sorting of objects and we can use it to provide sorting based on single logic.
Comparator interface is used to provide different algorithms for sorting and we can chose the comparator we want to use to sort the given collection of objects. [/expand]

Popular posts from this blog

Chain of responsibility using Spring @Autowired List

Iterate Through a HashMap

Under the Hood: Understanding the Gossip Protocol in Apache Cassandra