Posts

Optimistic Vs Pessimistic Locking

 Optimistic locking The optimistic locking model, also referred to as optimistic concurrency control, is a concurrency control method used in relational databases that does not use record locking. Optimistic locking allows multiple users to attempt to update the same record without informing the users that others are also attempting to update the record. The record changes are validated only when the record is committed. If one user successfully updates the record, the other users attempting to commit their concurrent updates are informed that a conflict exists. An advantage of the optimistic locking model is that it avoids the overhead of locking a record for the duration of the action. If there are no simultaneous updates, then this model provides fast updates. Optimistic locking is a useful approach when concurrent record updates are expected to be infrequent or the locking overhead is high. In the Rational ClearQuest implementation of optimistic locking, when multiple users edi...

Java Exception Hirarchy

Image
 

Spring Boot - Configure Multiple DBs (In Progress)

  First you have to set application.properties like this #Database database1.datasource.url=jdbc:mysql: //localhost/testdb database1.datasource.username=root database1.datasource.password=root database1.datasource.driver- class -name=com.mysql.jdbc.Driver database2.datasource.url=jdbc:mysql: //localhost/testdb2 database2.datasource.username=root database2.datasource.password=root database2.datasource.driver- class -name=com.mysql.jdbc.Driver Then define them as providers (@Bean) like this : @Bean(name = "datasource1" ) @ConfigurationProperties( "database1.datasource" ) @Primary public DataSource dataSource(){ return DataSourceBuilder.create().build(); } @Bean(name = "datasource2" ) @ConfigurationProperties( "database2.datasource" ) public DataSource dataSource2(){ return DataSourceBuilder.create().build(); } Note that I have @Bean(name= "datasource1" ) and @Bean(name= "datasource2...

Config Server (In Progress)

Image
 In micro-service world, managing configurations of each service separately is a tedious and time-consuming task. In other words, if there are many number of modules, and managing properties for each module with the traditional approach is very difficult. Central configuration server provides configurations (properties) to each micro service connected. As mentioned in the above diagram, Spring Cloud Config Server can be used as a central cloud config server by integrating to several environments.

Java 8 Supplier

Supplier A Supplier is a simple interface which indicates that this implementation is a supplier of results. This interface, however, does not enforce any restrictions that supplier implementation needs to return a different result on each invocation. The supplier has only one method get() and does not have any other default and static methods.  @Test public void supplier(){ Supplier<Double> doubleSupplier1 = () -> Math. random (); DoubleSupplier doubleSupplier2 = Math:: random ; System. out .println(doubleSupplier1.get()); System. out .println(doubleSupplier2.getAsDouble()); The supplier interface has its primitive variants such as IntSupplier, DoubleSupplier and  so on as shown below. Note that the method name is get() for the generic supplier  interface. However, for the primitive variants, it is as per the primitive type. IntSupplier int getAsInt(); DoubleSupplier double getAsDouble(); LongSupplier long getAsLong(); BooleanSupplier boolean getAsBoolean(); One...

Java 8 Consumer

 Consumer A Consumer is a functional interface that accepts a single input and returns no output. In layman’s language, as the name suggests the implementation of this interface consumes the input supplied to it. Consumer interface has two methods: void accept(T t); default Consumer<T> andThen(Consumer<? super T> after); The accept method is the Single Abstract Method (SAM) which accepts a single argument of type T. Whereas, the other one andThen is a default method used for composition. Following is an example of a consumer interface. We have created a consumer implementation that consumes a String and then prints it. The forEach method accepts consumer interface implementation. @Test public void whenNamesPresentConsumeAll(){ Consumer<String> printConsumer = t -> System. out .println(t); Stream<String> cities = Stream.of( "Sydney" , "Dhaka" , "New York" , "London" ); cities.forEach(printConsumer); In the following exam...

Java 8 Function

  Function A Function interface is more of a generic one that takes one argument and produces a result. This has a Single Abstract Method (SAM) apply which accepts an argument of a type T and produces a result of type R. One of the common use cases of this interface is Stream.map method. This is shown as below: @Test public void testFunctions(){ List<String> names = Arrays.asList( "Smith" , "Gourav" , "Heather" , "John" , "Catania" ); Function<String, Integer> nameMappingFunction = String::length; List<Integer> nameLength = names.stream().map(nameMappingFunction).collect(Collectors.toList()); System. out .println(nameLength);

Java 8 Predicate

  Predicate A Predicate interface represents a boolean-valued-function of an argument. This is mainly used to filter data from a Java Stream. The filter method of a stream accepts a predicate to filter the data and return a new stream satisfying the predicate. A predicate has a test() method which accepts an argument and returns a boolean value. @Test public void testPredicate(){ List<String> names = Arrays.asList( "John" , "Smith" , "Samueal" , "Catley" , "Sie" ); Predicate<String> nameStartsWithS = str -> str.startsWith( "S" ); names.stream().filter(nameStartsWithS).forEach(System. out ::println); In the above example, we have created a predicate which tests the names that start with S. This predicate is supplied to a stream. Predicate also provides a few default and static method for composition and other purposes: default Predicate<T> and(Predicate<? super T> other); default Predicate<T> or...

Java 8 Find Max Value

  public class Test { public static void main(String args[]) { List<Student> list = new ArrayList<>(); Student student1 = new Student( 1 , 20 , "A" ); Student student2 = new Student( 2 , 35 , "A" ); Student student3 = new Student( 3 , 25 , "A" ); list.add(student1); list.add(student2); list.add(student3); OptionalInt maxValue = list.stream().mapToInt(student->student.getAge()).max(); System. out .print( "Max Value-->" +maxValue.getAsInt());           List<Integer> list = List. of ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 );           OptionalInt maxValue = list.stream().mapToInt(x->x).max();           System. out .print( "Max Value-->" +maxValue.getAsInt()); } }

Java 8 Covert a list to Map

public class Hosting { private int Id ; private String name ; private long websites ; public Hosting( int id, String name, long websites) { Id = id; this . name = name; this . websites = websites; } public int getId() { return Id ; } public void setId( int id) { Id = id; } public String getName() { return name ; } public void setName(String name) { this . name = name; } public long getWebsites() { return websites ; } public void setWebsites( long websites) { this . websites = websites; } }   public class TestListMap { public static void main(String[] args) { List<Hosting> list = new ArrayList<>(); list.add( new Hosting( 1 , "liquidweb.com" , 80000 )); list.add( new Hosting( 2 , "linode.com" , 90000 )); list.add( new Hosting( 3 , "digitalocean.com" , 120000 )); lis...

Map Vs FlatMap

Image
 In Java, the Stream interface has a map() and flatmap() methods and both have intermediate stream operation and return another stream as method output. Both of the functions map() and flatMap are used for transformation and mapping operations. map() function produces one output for one input value, whereas flatMap() function produces an arbitrary no of values as output (ie zero or more than zero) for each input value. // Java program using map() function import java.io.*; import java.util.*; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; class Test{          public static void main(String[] args)     {         // making the array list object         ArrayList<String> fruit = new ArrayList<>();         fruit.add("Apple");         fruit.add("mango");         fruit.add("pineapple");     ...

Internal Working of Hashset

Image
Hashset internally use HashMap. Key -> Input Value Value -> Default PRESENT object public class HashSet< E > extends AbstractSet< E > implements Set< E >, Cloneable, java.io.Serializable { private transient HashMap< E ,Object> map ; // Dummy value to associate with an Object in the backing Map private static final Object PRESENT = new Object(); /** * Constructs a new, empty set; the backing { @code HashMap} instance has * default initial capacity (16) and load factor (0.75). */ public HashSet() { map = new HashMap<>(); } public boolean add( E e) { return map .put(e, PRESENT )== null ; } public boolean remove(Object o) { return map .remove(o)== PRESENT ; } import java.util.HashSet;    class Test {         public static void main(String args[])      {         // creating a HashSet         HashSet hs = new HashSet();       ...

Resiliency | Latency | Reliability

 Resiliency 1) Reliability 2) Error Handling 3) Graceful Failure Ability to handle and recover from failures gracefully. Resilient Solution 1) Detect Failure 2) Recover quickly and efficiently (within seconds or minutes) Resiliency Patterns 1) Circuit Breaker  2) Compensating Transaction 3) Bulkhead  4) Leader Election Latency It is a measure of delay. In a network, latency measure the time it takes for some data to get to its destination across the network. Low latency - Good, High Latency - Bad Reliability The probability of failure-free operation of a computer program in a specified environment for a specified time. Availability The percentage of time that the infrastructure, system or solution is operational under normal circumstances. The mathematical formula for Availability is : Percentage of availability = (total elapsed time – sum of downtime)/total elapsed time

Youtube Design

Image
 File upload flow

Binary Tree Traversal

  public class TreeNode { Integer value ; TreeNode left ; TreeNode right ; public TreeNode(Integer value) { this . value = value; } public Integer getValue() { return value ; } public void setValue(Integer value) { this . value = value; } public TreeNode getLeft() { return left ; } public void setLeft(TreeNode left) { this . left = left; } public TreeNode getRight() { return right ; } public void setRight(TreeNode right) { this . right = right; } } public class TreeTraversal { public static TreeNode createTree() { TreeNode rootNode = new TreeNode( 9 ); TreeNode node1 = new TreeNode( 7 ); TreeNode node2 = new TreeNode( 10 ); TreeNode node3 = new TreeNode( 3 ); TreeNode node4 = new TreeNode( 8 ); rootNode.setLeft(node1); rootNode.setRight(node2); node1.setLeft(node3); node1.setRight(...

Sliding Window Algorithm

Image
The main idea behind the sliding window technique is to convert two nested loops into a single loop. Usually, the technique helps us to reduce the time complexity from O(n^2) to O(n). The condition to use the sliding window technique is that the problem asks to find the maximum (or minimum) value for a function that calculates the answer repeatedly for a set of ranges from the array. Namely, if these ranges can be sorted based on their start, and their end becomes sorted as well, then we can use the sliding window technique. Let’s start with a problem for illustration where we can apply this technique –  Given an array of integers of size ‘n’. Our aim is to calculate the maximum sum of ‘k’  consecutive elements in the array. Input  : arr[] = {100, 200, 300, 400}          k = 2  Output : 700 Input  : arr[] = {1, 4, 2, 10, 23, 3, 1, 0, 20}          k = 4 Output : 39 We get maximum sum by adding subarray {4, 2, 10, ...

System Design URL Shortening Service

Image
URL shortening services like  bit.ly  or  TinyURL  are very popular to generate shorter aliases for long URLs. You need to design this kind of web service where if a user gives a long URL then the service returns a short URL and if the user gives a short URL then it returns the original long URL.  For example, shortening the given URL through TinyURL:  https://www.interviewready.org/get-your-dream-job-with /?ref=leftbar-rightbar We get the result given -  https://tinyurl.com/y7vg2xjl Requirement Before you jump into the solution always clarify all the assumptions you’re making at the beginning of the interview. Ask questions to identify the scope of the system. This will clear the initial doubt, and you will get to know what are the specific detail interviewer wants to consider in this service.  Given a long URL, the service should generate a shorter and unique alias of it. When the user hits a short link, the service should redirect to the origin...