Showing posts with label java interview in I.T. companies. Show all posts
Showing posts with label java interview in I.T. companies. Show all posts

Wednesday, August 19, 2020

How Kafka Consumer consumes messages from Kafka Topic

Hi friends,

This post is all about "How kafka consumer consumes messages from kafka topic"?


Kafka Consumers: Reading data from Kafka

Applications that need to read data from Kafka use a KafkaConsumer to subscribe to Kafka topics and receive messages from these topics.


Kafka Consumer Concepts

In order to understand how to read data from Kafka, you first need to understand its consumers and consumer groups. The following sections cover those concepts.

Consumers and Consumer Groups

Suppose you have an application that needs to read messages from a Kafka topic, run some validations against them, and write the results to another data store. In this case your application will create a consumer object, subscribe to the appropriate topic, and start receiving messages, validating them and writing the results. This may work well for a while, but what if the rate at which producers write messages to the topic exceeds the rate at which your application can validate them? If you are limited to a single consumer reading and processing the data, your application may fall farther and farther behind, unable to keep up with the rate of incoming messages. Obviously there is a need to scale consumption from topics. Just like multiple producers can write to the same topic, we need to allow multiple consumers to read from the same topic, splitting the data between them.

Kafka consumers are typically part of a consumer group. When multiple consumers are subscribed to a topic and belong to the same consumer group, each consumer in the group will receive messages from a different subset of the partitions in the topic.

Let’s take topic T1 with four partitions. Now suppose we created a new consumer, C1, which is the only consumer in group G1, and use it to subscribe to topic T1. Consumer C1 will get all messages from all four T1 partitions.




If we add another consumer, C2, to group G1, each consumer will only get messages from two partitions. Perhaps messages from partition 0 and 2 go to C1 and messages from partitions 1 and 3 go to consumer C2.


If G1 has four consumers, then each will read messages from a single partition.


If we add more consumers to a single group with a single topic than we have partitions, some of the consumers will be idle and get no messages at all.

In addition to adding consumers in order to scale a single application, it is very common to have multiple applications that need to read data from the same topic. In fact, one of the main design goals in Kafka was to make the data produced to Kafka topics available for many use cases throughout the organization. 

In those cases, we want each application to get all of the messages, rather than just a subset. To make sure an application gets all the messages in a topic, ensure the application has its own consumer group. Unlike many traditional messaging systems, Kafka scales to a large number of consumers and consumer groups without reducing performance.

In the previous example, if we add a new consumer group G2 with a single consumer, this consumer will get all the messages in topic T1 independent of what G1 is doing.

 

 

Consumer Groups and Partition Rebalance

As we saw in the previous section, consumers in a consumer group share ownership of the partitions in the topics they subscribe to. When we add a new consumer to the group, it starts consuming messages from partitions previously consumed by another consumer. The same thing happens when a consumer shuts down or crashes; it leaves the group, and the partitions it used to consume will be consumed by one of the remaining consumers. Reassignment of partitions to consumers also happen when the topics the consumer group is consuming are modified (e.g., if an administrator adds new partitions).

Moving partition ownership from one consumer to another is called a rebalance. Rebalances are important because they provide the consumer group with high availability and scalability (allowing us to easily and safely add and remove consumers), but in the normal course of events they are fairly undesirable. 

During a rebalance, consumers can’t consume messages, so a rebalance is basically a short window of unavailability of the entire consumer group. In addition, when partitions are moved from one consumer to another, the consumer loses its current state; if it was caching any data, it will need to refresh its caches—slowing down the application until the consumer sets up its state again. Throughout this chapter we will discuss how to safely handle rebalances and how to avoid unnecessary ones.

The way consumers maintain membership in a consumer group and ownership of the partitions assigned to them is by sending heartbeats to a Kafka broker designated as the group coordinator (this broker can be different for different consumer groups). As long as the consumer is sending heartbeats at regular intervals, it is assumed to be alive, well, and processing messages from its partitions. Heartbeats are sent when the consumer polls (i.e., retrieves records) and when it commits records it has consumed.

If the consumer stops sending heartbeats for long enough, its session will time out and the group coordinator will consider it dead and trigger a rebalance. If a consumer crashed and stopped processing messages, it will take the group coordinator a few seconds without heartbeats to decide it is dead and trigger the rebalance. 

During those seconds, no messages will be processed from the partitions owned by the dead consumer. When closing a consumer cleanly, the consumer will notify the group coordinator that it is leaving, and the group coordinator will trigger a rebalance immediately, reducing the gap in processing. Later in this chapter we will discuss configuration options that control heartbeat frequency and session timeouts and how to set those to match your requirements

How does the process of assigning partitions to brokers work?

When a consumer wants to join a group, it sends a JoinGroup request to the group coordinator. The first consumer to join the group becomes the group leader. The leader receives a list of all consumers in the group from the group coordinator (this will include all consumers that sent a heartbeat recently and which are therefore considered alive) and is responsible for assigning a subset of partitions to each consumer. It uses an implementation of PartitionAssignor to decide which partitions should be handled by which consumer.

 Creating a Kafka Consumer:

The first step to start consuming records is to create a KafkaConsumer instance. Creating a KafkaConsumer is very similar to creating a KafkaProducer—you create a Java Properties instance with the properties you want to pass to the consumer. We will discuss all the properties in depth later in the chapter. 

To start we just need to use the three mandatory properties: bootstrap.servers, key.deserializer, and value.deserializer.

The first property, bootstrap.servers, is the connection string to a Kafka cluster. The other two properties, key.deserializer and value.deserializer, are similar to the serializers defined for the producer, but rather than specifying classes that turn Java objects to byte arrays, you need to specify classes that can take a byte array and turn it into a Java object.

The following code snippet shows how to create a KafkaConsumer:

Properties props = new Properties();

props.put("bootstrap.servers", "broker1:9092,broker2:9092");

props.put("group.id", "CountryCounter");

props.put("key.deserializer",

    "org.apache.kafka.common.serialization.StringDeserializer");

props.put("value.deserializer",

    "org.apache.kafka.common.serialization.StringDeserializer");

 

KafkaConsumer<String, String> consumer =

    new KafkaConsumer<String, String>(props);

We assume that the records we consume will have String objects as both the key and the value of the record. The only new property here is group.id, which is the name of the consumer group this consumer belongs to.

 

Subscribing to Topics

Once we create a consumer, the next step is to subscribe to one or more topics. The subscribe() method takes a list of topics as a parameter, so it’s pretty simple to use:

consumer.subscribe(Collections.singletonList("customerCountries"));

The Poll Loop

At the heart of the consumer API is a simple loop for polling the server for more data. Once the consumer subscribes to topics, the poll loop handles all details of coordination, partition rebalances, heartbeats, and data fetching, leaving the developer with a clean API that simply returns available data from the assigned partitions. 

try {

    while (true) {

        ConsumerRecords<String, String> records = consumer.poll(100);

        for (ConsumerRecord<String, String> record : records)

        {

            log.debug("topic = %s, partition = %d, offset = %d,"

                customer = %s, country = %s\n",

                record.topic(), record.partition(), record.offset(),

                record.key(), record.value());

 

            int updatedCount = 1;

            if (custCountryMap.countainsKey(record.value())) {

                updatedCount = custCountryMap.get(record.value()) + 1;

            }

            custCountryMap.put(record.value(), updatedCount)

 

            JSONObject json = new JSONObject(custCountryMap);

            System.out.println(json.toString(4));

    }

}

}finally{

    consumer.close();

}

 

This is indeed an infinite loop. Consumers are usually long-running applications that continuously poll Kafka for more data. We will show later in the chapter how to cleanly exit the loop and close the consumer.

 

 

This is the most important line in the chapter. The same way that sharks must keep moving or they die, consumers must keep polling Kafka or they will be considered dead and the partitions they are consuming will be handed to another consumer in the group to continue consuming. The parameter we pass, poll(), is a timeout interval and controls how long poll() will block if data is not available in the consumer buffer. If this is set to 0, poll() will return immediately; otherwise, it will wait for the specified number of milliseconds for data to arrive from the broker.

 

poll() returns a list of records. Each record contains the topic and partition the record came from, the offset of the record within the partition, and of course the key and the value of the record. Typically we want to iterate over the list and process the records individually.

 

Processing usually ends in writing a result in a data store or updating a stored record. Here, the goal is to keep a running count of customers from each county, so we update a hashtable and print the result as JSON. A more realistic example would store the updates result in a data store.


That's all for this post.

Thanks for reading!!

Monday, August 10, 2020

Java Technical interview @ Thales Group: Round-3

 Hi friends,


In this post, I am sharing interview questions asked in Thales group: round-3. 


Question 1:

What are the differences between save() and persist() methods?

Answer:

  • persist() is defined in JPA. save() is defined in hibernate.
  • persist() return type is void. save() returns serializable object[generated id].
  • persist() doesn't execute insert statement outside transaction boundary. But save() can execute insert statement inside/outside transaction boundary.
  • We can persist detached object using save() and it will crate a new row in the table. We cannot persist  a detached object using persist() and it will throw PersistentObjectException.

Working of persist() method:


When it is called on transient instance, then that instance's state is changed to persistent. No record will be created in DB until until commit or flush is called on session object or session is closed.

When it is called on persistent object, then nothing happens.
When it is called on detached instance, then it throws PersistentException.

persist() method has void return type.

Note: An instance will go to detached state, when evict() is called on session instance, or session is closed.


Example:

Person p = new Person();
p.setName("abcd");
session.persist(p);

//Here when persist() is called, the person object has transitioned from transient to persistent state.

The object is in the persistent context now, but not yet saved to the db. The generation of INERT statement will occur only upon committing the transaction, flushing or closing the session.

Working of save() method:


The save() method is an original hibernate method that does not conform to the JPA specification.
It's purpose is basically the same as persist(), but it has different implementation details.
The documentation for this method strictly states that it persists the instance, "first assigning a generated identifier". The method is guaranteed to return the serializable value of this identifier.

Person p = new Person();
p.setName("abcd");
long id = (long) session.save(p);

The effect of saving an already persisted instance is the same as with persist(). Difference comes when we try to save a detached instance.

Person p = new Person();
p.setName("abcd");
long id = (long) session.save(p);

session.evict(p);
long id2 = (long)session.save(p);


The id2 variable will differ from id1. The call of save() on a detached instance creates a new persistence instance and assigns it a new identifier, which results in a duplicate record in a database upon committng or flushing.



Working of update() method:

As with persist and save, the update method is an “original” Hibernate method that was present long before the merge method was added. Its semantics differs in several key points:

  • it acts upon passed object (its return type is void); the update method transitions the passed object from detached to persistent state;
  • this method throws an exception if you pass it a transient entity.

 

import org.hibernate.*;

import org.hibernate.cfg.*;

 

public class ClientLogicProgram{

 

public static void main(String... args)

{

 

        Configuration cfg = newConfiguration();

cfg.configure("hibernate.cfg.xml");

 

SessionFactoryfactory = cfg.buildSessionFactory();

 

        Session session1 = factory.openSession();

         Product p=null;   //Transient state..

         Object o=session1.get(Product.class, new Integer(1001));

         p=(Product)o;   //now p is in Persistent state..

 

        session1.close();

 

 

p.setPrice(36000);            // p is in Detached state

 

        Session session2=factory.openSession();

         Transaction tx=session2.beginTransaction();

            session2.update(p);   // now p reached to Persistent state

tx.commit();

 

        session2.close();

factory.close();

}

}


 

Question 2:

What are spring transaction isolation levels?

Answer:


Isolation level defines how the changes made to some data repository by one transaction affect other simultaneous concurrent transactions. And also how and when that changed data becomes available to other  transactions.


When we define a transaction using the spring framework , we are also able to configure in which isolation level that same transaction will be executed.


Usage example:


Using the @Transactional annotation, we can define the isolation level of a spring managed bean transactional method. This means that the transaction in which this method is executed will run with that isolation level.


Isolation level in a transactional method:

@Autowired

private TestDAO testDAO;

@Transactional (isolation = Isolation.READ_COMMITTED)

public void someTransactionalMethod(User user){

    // interact with testDAO

}


READ_UNCOMMITTED:


READ_UNCOMMITTED isolation level states that a transaction may read data  that is still uncommitted by other transactions. This constraint is very relaxed in what matters to transactional concurrency , but it may led to some issues like dirty reads. 




Note: READ_UNCOMMITTED is also vulnerable to non-repeatable reads and phantom reads.


READ_COMMITTED:


This level states that  a transaction cannot read data that is not yet committed by other transactions.

This means that dirty read is no longer an issue , but even this way other issues may occur.






In this example Transaction A reads some record. Then Transaction B writes that same record and commits. Later Transaction A reads that same record again and may get different values because Transaction B made changes to that record and committed. This is a non-repeatable read.

Note: READ_COMMITTED is also vulnerable to phantom reads.

 

 

REPEATABLE_READ

REPEATABLE_READ isolation level states that if a transaction reads one record from the database multiple times the result of all those reading operations must always be the same. This eliminates both the dirty read and the non-repeatable read issues, but even this way other issues may occur. 




In this example Transaction A reads a range of records. Meanwhile Transaction B inserts a new record in the same range that Transaction A initially fetched and commits. Later Transaction A reads the same range again and will also get the record that Transaction B just inserted. This is a phantom read: a transaction fetched a range of records multiple times from the database and obtained different result sets (containing phantom records).



SERIALIZABLE:

This is the most restrictive of all isolation levels. Transactions are executed with locking at all levels (read, range and write locking) so they appear as if they were executed in a serialized way.

This leads to a scenario where none of the issues mentioned above may occur. But in the other way, we do not allow transaction concurrency and consequently introduce a performance penalty.



That's all for this post.

Thanks for reading!! 



Friday, July 10, 2020

Mongo DB Replication interview

Hi friends,

In this post, I'm sharing interview questions on Mongo DB replication and configuration.



Question 1:

Why we need replication in Mongo DB?

Answer:

Mongo DB replication has two benefits:

  • If one database node is down, we can get data from other nodes.
  • Replication can also be done for the purpose of load balancing.


Question 2:

How to setup replication in Mongo DB?

Answer:

In Mongo db , replication process can be setup by creating a replica set. In Mongo db, a replica set contains multiple Mongo db servers. In this group of Mongo db servers, one server is known as a primary server and others are known as secondary servers.

Every secondary server always keeps copies of the primary's data. So, if anytime the primary server goes down, then the new primary server is selected from the existing secondary servers and process goes on.
The replication process works as below with the help of a replica set:

Replica set is a group of one or more standalone mongo db servers [Normally, 3 Mongo db servers are required].

In a replica set, one server is marked as primary server and rest are marked as secondary server.

Data writes into the primary server from the application first. Then all the data replicates to the secondary servers from the primary server.

When the primary server is unavailable due to hardware failure or maintenance work, the election process starts to identify the new primary server and select a primary server from the secondary lists.

When the failed server recovered, it will again join the replica set as a secondary server.




  
 

Question 3:

How to configure replication in Mongo DB?

Answer:

I will tell here , how to convert a standalone Mongo db instance into a replica set. This process is not an ideal process for the production environment. Because in production environment, if we need to establish a replica set, then we need to provide three different Mongo db instances for the replica set.

Step 1:

Start a mongo shell with the --nodb options from the command prompt. It will start a shell without any connection with the existing mongodb instance.

Command is : mongo --nodb

Step 2:

Now, create a replica set with the below commands:

replicaSet = new ReplSetTest({name:'rsTest', nodes : 3})

This command instructs the shell to create a replica set with three node servers: one primary and two secondaries.

Step 3:

Now run the below commands one by one to start the mongo db server instances:

1. replicaSet.startSet() - This command starts the three mongo db processes.
2. replicaSet.initiate() - This command configures the replication.

Now, we have three mongo db processes locally on ports port1, port2, port3 [These will be integer values]. 

Step 4:

Now open another command prompt and connect the mongo db running on port port1.

1. conn1 = new Mongo("localhost:port1");
2. connection to localhost:port1
3. rsTest : PRIMARY>

Note that, when we connect a replica set member, the prompt changes to rsTest: PRIMARY. Here PRIMARY is the state of the member and rsTest is the identifier of the replica set.






Question 4:

How to change replication configuration?

Answer:

After defining a replica set, we can change the replica set at any time. We can add new members , remove any existing members.

There is a mongo shell helper method is available to add new replica set members or remove existing replica set members. 

To add a new member into the replica set, we need to run the below command:

rs.add("server-4: 20005")

Similarly, we can remove any members from the existing replica set using the below command:

rs.remove("server-2:20002")

If we need to check the existing configuration of the replication, then we need to run the below command in the shell:

rs.config()  




Question 5:

How does syncing work in Mongo DB?

Answer:

The main objective of the replication process is to keep the same or an identical set of data on multiple servers.  For performing this task, MongoDB always maintains a log of operations or oplog which contains every write information into the primary server. This log is a collection that exists in  the local database on the primary server.
The secondary  servers are queries of this collection for obtaining the operation details so that they can replicate that data.

Every secondary server maintains it's own oplog where Mongo db captures each operation related to the replication process from the primary server.These log files allow any replica set members to use as a sync source for other members.

The secondary server always first fetches the information related to the pending operations from the primary members, then apply that operation to their own data set and then writes down the logs about that operation into the oplog.




That's all for this post.
Thanks for reading!!



Saturday, June 20, 2020

Java Interview @ Polaris

Hi friends,

In this post, I'm sharing interview questions asked in Polaris.


Question 1:

public class Quiz23{

    public static void main(String[] args){

        int x = 0;
        int[] nums = {1,2,3,5};

        for(int i : nums){

            switch(i){

                case 1:
                    x += i;
                case 5:
                    x += i;
                default:
                    x += i;
                case 2:
                    x  += i;

            }
            System.out.println(x);
        }
    }
}

What will be the output of above code?

Answer:

27

Explanation:

For case i = 1:  All the cases will run.
For case i = 2: only case 2 will run.
For case i = 3: Default and case 2 will run.
For case i = 5: case , default and case 2 will run.



Question 2:

What is the difference between Map and FlatMap?

Answer:

Map: Transforms the elements into something else. It accepts a function to apply to each element and returns a new Stream of values returned by the passed function.

It takes function object as the parameter e.g.: Function, ToIntFunction, ToIntDoubleFunction, ToLongFunction.


FlatMap: Combination of Map and Flat operations.So, we first apply map operation on each element and then flattens the result.

So, if function used by Map is returning a single value, then map is ok. But, if function used by Map operation is returning a stream of list or stream of stream, then we need to use flatmap to get stream of values.

For example:

If we have a stream of String containing {"12", "34"} and a method getPermutations() which returns a list of permutations of given string.

When we apply getPermutation() into each string of Stream using map , we get something like [["12","21"], ["34","43"]], but if we use flatMap, we get a stream of strings e.g.: ["12","21","34","43"].

Another example:

List evens = Arrays.asList(2,4,6);
List odds = Arras.asList(3,5,7);
List primes = Arrays.asList(2,3,5,7,11);

List numbers = Stream.of(evens, odds, primes).flatMap(list -> list.stream()).collect(Collectors.toList());

System.out.println("flattened list : "+numbers);

Output: flattened list : [2,4,6,3,5,7,2,3,5,7,11]


 
Question 3:

What is the difference between passing int array and String array to Stream.of()?

Answer:

Stream.of(int[]) gives Stream<int[]>
Stream.of(String[]) gives Stream<String>

So, when using Stream.of() with int[] , we get Stream<int[]> and then for getting ints from Stream, we use flatMapToInt(i -> Arrays.Stream(i)) to get IntStream and then we can either use map() or forEach().

e.g.:

int[] arr = {1,2,3,4};
Stream<int[]> streamArr = Stream.of(arr);
IntStream intStream = streamArr.flatMapToInt(i -> Arrays.Stream(i));
intStream.forEach(System.out :: println);



Question 4:

What is a Boxed Stream?

Answer:

If we want to convert stream of objects to collection:

List<String> strings = Stream.of("how", "to", "do", "in", "java").collect(Collectors.toList());

The same process doesn't work on streams of primitives, however.

//Compilation Error:
IntStream.of(1,2,3,4,5).collect(Collectors.toList());

To convert a stream of primitives, we must first box the elements in their wrapper class and then collect them. This type of stream is called boxed stream.

Example of IntStream to List of Integers:

List<Integer> ints = IntStream.of(1,2,3,4,5).boxed().collect(Collectors.toList());

System.out.println(ints);

Output: [1,2,3,4,5]

 

Question 5:

List Spring Core and Stereotype annotations.

Answer:

Spring Core Annotations:
  • @Qualifier
  • @Autowired
  • @Configuration
  • @ComponentScan
  • @Required
  • @Bean
  • @Lazy
  • @Value

Spring framework Stereotype annotations:
  • @Component
  • @Controller
  • @Service
  • @Repository


Question 6:

What is difference  between @Controller and @RestController?

Answer:

@Controller creates a Map of model object and finds a view for that.
@RestController simply returns the object and object data is directly written into HTTP response as JSON or XML.

@RestController = @Controller + @ResponseBody
@RestController was added in  Spring 4.



Question 7:

Why Spring introduced @RestController when this job could be done by using @Controller and @ResponseBody?

Answer:

The functioning or output of @Controller and @ResponseBody is the default behavior of RESTFUL web services, that's why Spring introduced @RestController which combined the behavior of @Controller and @ResponseBody.  



Question 8:

Tell something about Swagger tools which you have used.

Answer:

Swagger Editor:  Can edit OpenAPI specifications.

Swagger UI : A collection of HTML/CSS/Javascript assets that dynamically generate beautiful documentation.

Swagger Codegen: Allows generation of API client libraries.

Swagger Parser: Library for parsing OpenAPI definitions from java.

Swagger Core: Java related libraries for creating, consuming and working with OpenAPI definitions.

Swagger Inspector: API testing tool

SwaggerHub : Built for teams working with OpenAPI.








That's all for this post.
Thanks for reading!!

Sunday, June 7, 2020

Java Interview @ Indie Games


Hi Friends,

In this post, I'm sharing java interview questions and answers asked in Indie games.



Question 1:

How do you kill a thread in java?

Answer:

There are two ways to kill a thread:

  • Stop the thread [Deprecated now]
  • Use a volatile variable and running thread will keep checking it's value and return from it's run method in an orderly fashion. 


Question 2:

Why is Thread.stop() deprecated?

Answer:

Because it is inherently unsafe. Stopping a thread causes it to unlock all the monitors that it has locked.(The monitors are unlocked as the ThreadDeath exception propagates up the stack.)
If any of the objects previously protected by these monitors were in an inconsistent state, other threads may now view these objects in an inconsistent state. Such objects are said to be damaged.

When threads operate on damaged objects, arbitrary behavior can result. This behavior may be subtle and difficult to detect.

ThreadDeath exception kills thread silently, thus the user has no warning that this program may be corrupted.
 


Question 3:

How to check if a String is numeric in java?

Answer:

We can use Apache Commons Lang 3.4 and 3.5 versions.

StringUtils.isNumeric() or NumberUtils.isParsable().



Question 4:

How can we timeout a thread? I want to run a thread for some fixed amount of time.If it is not completed within that time, I want to either kill it or throw some exception. How to do it?


Answer:

We can use ExecutorService framework of Java 5.

public class Test{

    public static void main(String[] args){

        ExecutorService service = Executors.newSingleThreadExecutor();
        Future<String> future = service.submit(new Task());

        try{

            future.get(4, Timeout.SECONDS);
        }
        catch(Exception e){
            future.cancel(true);
        }

        executor.shutDownNow();
    
    }

}


class Task implements Callable<String>{

    @Override
    public String call() throws Exception{

        Thread.sleep(5000);
        return "";
    }

}


In this code, thread sleeps for 5 seconds, but future will wait for 4 seconds and it will timeout and cancel it.




Question 5:

How to wait for all threads to finish using ExecutorService?

Answer:

We can use shutdown() and awaitTermination() methods of ExecutorService.

ExecutorService service = Executors.newFixedThreadPool(4);

while(...){

    service.execute(new Task());

}    
service.shutdown();
try{
    service.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
}
catch(InterruptedException e){

}



Question 6:

Can we create deadlock without thread in java?

Answer:

It is not possible to run the code without atleast one thread. A single thread can block itself in some cases e.g. attempting to upgrade a read lock to a write lock.
When a thread resource starves, it is called a livelock.

It is also possible to create a deadlock without creating an additional thread e.g. the finalizer thread and the main thread can deadlock each other.




That's all for this interview post.

Thanks for reading!!










CAP Theorem and external configuration in microservices

 Hi friends, In this post, I will explain about CAP Theorem and setting external configurations in microservices. Question 1: What is CAP Th...