Showing posts with label Interview. Show all posts
Showing posts with label Interview. Show all posts

Saturday, November 28, 2020

Interesting Properties of Data Structures

1. The stack data structure can come in handy here in representing this recursive structure of the problem. We can't really process this from the inside out because we don't have an idea about the overall structure. But, the stack can help us process this recursively i.e. from outside to inwards.

2. The capability of finding matching prefix is where the data structure called Trie would shine, comparing the hashset data structure. Not only can Trie tell the membership of a word, but also it can instantly find the words that share a given prefix. As it turns out, the choice of data structure (Trie VS. hashset), which could end with a solution that ranks either the top 5\%5% or the bottom 5\%5%.


Wednesday, November 25, 2020

Below are the Big O performance of common functions of different Java Collections.

List                 | Add  | Remove | Get  | Contains | Next | Data Structure
---------------------|------|--------|------|----------|------|---------------
ArrayList            | O(1) |  O(n)  | O(1) |   O(n)   | O(1) | Array
LinkedList           | O(1) |  O(1)  | O(n) |   O(n)   | O(1) | Linked List
CopyOnWriteArrayList | O(n) |  O(n)  | O(1) |   O(n)   | O(1) | Array



Set                   |    Add   |  Remove  | Contains |   Next   | Size | Data Structure
----------------------|----------|----------|----------|----------|------|-------------------------
HashSet               | O(1)     | O(1)     | O(1)     | O(h/n)   | O(1) | Hash Table
LinkedHashSet         | O(1)     | O(1)     | O(1)     | O(1)     | O(1) | Hash Table + Linked List
EnumSet               | O(1)     | O(1)     | O(1)     | O(1)     | O(1) | Bit Vector
TreeSet               | O(log n) | O(log n) | O(log n) | O(log n) | O(1) | Red-black tree
CopyOnWriteArraySet   | O(n)     | O(n)     | O(n)     | O(1)     | O(1) | Array
ConcurrentSkipListSet | O(log n) | O(log n) | O(log n) | O(1)     | O(n) | Skip List



Queue                   |  Offer   | Peak |   Poll   | Remove | Size | Data Structure
------------------------|----------|------|----------|--------|------|---------------
PriorityQueue           | O(log n) | O(1) | O(log n) |  O(n)  | O(1) | Priority Heap
LinkedList              | O(1)     | O(1) | O(1)     |  O(1)  | O(1) | Array
ArrayDequeue            | O(1)     | O(1) | O(1)     |  O(n)  | O(1) | Linked List
ConcurrentLinkedQueue   | O(1)     | O(1) | O(1)     |  O(n)  | O(n) | Linked List
ArrayBlockingQueue      | O(1)     | O(1) | O(1)     |  O(n)  | O(1) | Array
PriorirityBlockingQueue | O(log n) | O(1) | O(log n) |  O(n)  | O(1) | Priority Heap
SynchronousQueue        | O(1)     | O(1) | O(1)     |  O(n)  | O(1) | None!
DelayQueue              | O(log n) | O(1) | O(log n) |  O(n)  | O(1) | Priority Heap
LinkedBlockingQueue     | O(1)     | O(1) | O(1)     |  O(n)  | O(1) | Linked List



Map                   |   Get    | ContainsKey |   Next   | Data Structure
----------------------|----------|-------------|----------|-------------------------
HashMap               | O(1)     |   O(1)      | O(h / n) | Hash Table
LinkedHashMap         | O(1)     |   O(1)      | O(1)     | Hash Table + Linked List
IdentityHashMap       | O(1)     |   O(1)      | O(h / n) | Array
WeakHashMap           | O(1)     |   O(1)      | O(h / n) | Hash Table
EnumMap               | O(1)     |   O(1)      | O(1)     | Array
TreeMap               | O(log n) |   O(log n)  | O(log n) | Red-black tree
ConcurrentHashMap     | O(1)     |   O(1)      | O(h / n) | Hash Tables
ConcurrentSkipListMap | O(log n) |   O(log n)  | O(1)     | Skip List

Tuesday, September 22, 2020

int[] and Integer[] arrays - What is the difference?

This image should help you to understand the difference:






int is a number, it's a primitive type.

Integer is an object.

When you have an array of Integers, you actually have an array of objects. Array of ints is an array of primitive types.

Since arrays are objects, they're allocated on the heap. If it's an array of ints, these ints will be allocated on the heap too, within the array.

Further adding. to this..

There is a difference at run-time.

int[] is an array of primitive int values. Integer[] is an "object" array, holding references to Integer objects.

Most important practical difference: int[] cannot hold null values.

int[] does store primitive types. And the array itself lives on the heap. However, those primitives are allocated as part of the array. They are not stored separately elsewhere on the heap. This is very similar to how a primitive field is part of an object instance: The object is on the heap, and its field is an integral part of that object (whereas for a non-primitive field, only the reference is stored inside the object and the target instance that reference points at is stored separately on the heap).


Ref : this link

Wednesday, September 2, 2020

FAANG : The Journey | Post 10 | Top 50 Google tagged questions. (With Links)

 

  1. Two Sum (https://leetcode.com/problems/two-sum)
  2. Insert Interval (https://leetcode.com/problems/insert-interval)
  3. Text Justification (https://leetcode.com/problems/text-justification)
  4. Minimum Window Substring (https://leetcode.com/problems/minimum-windowsubstring)
  5. Maximal Rectangle (https://leetcode.com/problems/maximal-rectangle)
  6. The Skyline Problem (https://leetcode.com/problems/the-skyline-problem)
  7. Maximal Square (https://leetcode.com/problems/maximal-square)
  8. Meeting Rooms II (https://leetcode.com/problems/meeting-rooms-ii)
  9. Find Median from Data Stream (https://leetcode.com/problems/find-median-from-datastream)
  10. Bulls and Cows (https://leetcode.com/problems/bulls-and-cows)
  11. Count of Smaller Numbers After Self (https://leetcode.com/problems/count-of-smallernumbers-after-self)
  12. Longest Increasing Path in a Matrix (https://leetcode.com/problems/longest-increasingpath-in-a-matrix)
  13. Longest Substring with At Most K Distinct Characters
    (https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters)
  14. Moving Average from Data Stream (https://leetcode.com/problems/moving-averagefrom-data-stream)
  15. Logger Rate Limiter (https://leetcode.com/problems/logger-rate-limiter)
  16. Design Hit Counter (https://leetcode.com/problems/design-hit-counter)
  17. Max Sum of Rectangle No Larger Than K (https://leetcode.com/problems/max-sum-ofrectangle-no-larger-than-k)
  18. Decode String (https://leetcode.com/problems/decode-string)
  19. Evaluate Division (https://leetcode.com/problems/evaluate-division)
  20. Split Array Largest Sum (https://leetcode.com/problems/split-array-largest-sum)
  21. Robot Room Cleaner (https://leetcode.com/problems/robot-room-cleaner)
  22. Random Pick with Weight (https://leetcode.com/problems/random-pick-with-weight)
  23. Subarray Sum Equals K (https://leetcode.com/problems/subarray-sum-equals-k)
  24. Longest Line of Consecutive One in Matrix (https://leetcode.com/problems/longest-lineof-consecutive-one-in-matrix)
  25. Design Search Autocomplete System (https://leetcode.com/problems/design-searchautocomplete-system)
  26. Split Array into Consecutive Subsequences (https://leetcode.com/problems/split-arrayinto-consecutive-subsequences)
  27. 24 Game (https://leetcode.com/problems/24-game)
  28. Minimum Window Subsequence (https://leetcode.com/problems/minimum-windowsubsequence)
  29. Network Delay Time (https://leetcode.com/problems/network-delay-time)
  30. Open the Lock (https://leetcode.com/problems/open-the-lock)
  31. Expressive Words (https://leetcode.com/problems/expressive-words)
  32. Find And Replace in String (https://leetcode.com/problems/find-and-replace-in-string)
  33. Guess the Word (https://leetcode.com/problems/guess-the-word)
  34. Hand of Straights (https://leetcode.com/problems/hand-of-straights)
  35. Shortest Subarray with Sum at Least K (https://leetcode.com/problems/shortestsubarray-with-sum-at-least-k)
  36. X of a Kind in a Deck of Cards (https://leetcode.com/problems/x-of-a-kind-in-a-deck-ofcards)
  37. Minimum Area Rectangle (https://leetcode.com/problems/minimum-area-rectangle)
  38. Validate Stack Sequences (https://leetcode.com/problems/validate-stack-sequences)
  39. Flip Equivalent Binary Trees (https://leetcode.com/problems/flip-equivalent-binarytrees)
  40. Minimum Domino Rotations For Equal Row (https://leetcode.com/problems/minimumdomino-rotations-for-equal-row)
  41. Longest String Chain (https://leetcode.com/problems/longest-string-chain)
  42. Shortest Way to Form String (https://leetcode.com/problems/shortest-way-to-formstring)
  43. Confusing Number II (https://leetcode.com/problems/confusing-number-ii)
  44. Delete Nodes And Return Forest (https://leetcode.com/problems/delete-nodes-andreturn-forest)
  45. Snapshot Array (https://leetcode.com/problems/snapshot-array)
  46. String Transforms Into Another String (https://leetcode.com/problems/string-transformsinto-another-string)
  47. Divide Chocolate (https://leetcode.com/problems/divide-chocolate)
  48. Divide Array in Sets of K Consecutive Numbers (https://leetcode.com/problems/dividearray-in-sets-of-k-consecutive-numbers)
  49. Minimum Distance to Type a Word Using Two Fingers
    (https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers)
  50. Time Needed to Inform All Employees (https://leetcode.com/problems/time-needed-toinform-all-employees)

Monday, June 8, 2020

Top 50 Google tagged questions. (With Links)

  1. Two Sum (https://leetcode.com/problems/two-sum)
  2. Insert Interval (https://leetcode.com/problems/insert-interval)
  3. Text Justification (https://leetcode.com/problems/text-justification)
  4. Minimum Window Substring (https://leetcode.com/problems/minimum-window-substring)
  5. Maximal Rectangle (https://leetcode.com/problems/maximal-rectangle)
  6. The Skyline Problem (https://leetcode.com/problems/the-skyline-problem)
  7. Maximal Square (https://leetcode.com/problems/maximal-square)
  8. Meeting Rooms II (https://leetcode.com/problems/meeting-rooms-ii)
  9. Find Median from Data Stream (https://leetcode.com/problems/find-median-from-data-stream)
  10. Bulls and Cows (https://leetcode.com/problems/bulls-and-cows)
  11. Count of Smaller Numbers After Self (https://leetcode.com/problems/count-of-smaller-numbers-after-self)
  12. Longest Increasing Path in a Matrix (https://leetcode.com/problems/longest-increasing-path-in-a-matrix)
  13. Longest Substring with At Most K Distinct Characters
    (https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters)
  14. Moving Average from Data Stream (https://leetcode.com/problems/moving-average-from-data-stream)
  15. Logger Rate Limiter (https://leetcode.com/problems/logger-rate-limiter)
  16. Design Hit Counter (https://leetcode.com/problems/design-hit-counter)
  17. Max Sum of Rectangle No Larger Than K (https://leetcode.com/problems/max-sum-of-rectangle-no-larger-than-k)
  18. Decode String (https://leetcode.com/problems/decode-string)
  19. Evaluate Division (https://leetcode.com/problems/evaluate-division)
  20. Split Array Largest Sum (https://leetcode.com/problems/split-array-largest-sum)
  21. Robot Room Cleaner (https://leetcode.com/problems/robot-room-cleaner)
  22. Random Pick with Weight (https://leetcode.com/problems/random-pick-with-weight)
  23. Subarray Sum Equals K (https://leetcode.com/problems/subarray-sum-equals-k)
  24. Longest Line of Consecutive One in Matrix (https://leetcode.com/problems/longest-lineof-consecutive-one-in-matrix)
  25. Design Search Autocomplete System (https://leetcode.com/problems/design-search-autocomplete-system)
  26. Split Array into Consecutive Subsequences (https://leetcode.com/problems/split-array-into-consecutive-subsequences)
  27. 24 Game (https://leetcode.com/problems/24-game)
  28. Minimum Window Subsequence (https://leetcode.com/problems/minimum-window-subsequence)
  29. Network Delay Time (https://leetcode.com/problems/network-delay-time)
  30. Open the Lock (https://leetcode.com/problems/open-the-lock)
  31. Expressive Words (https://leetcode.com/problems/expressive-words)
  32. Find And Replace in String (https://leetcode.com/problems/find-and-replace-in-string)
  33. Guess the Word (https://leetcode.com/problems/guess-the-word)
  34. Hand of Straights (https://leetcode.com/problems/hand-of-straights)
  35. Shortest Subarray with Sum at Least K (https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k)
  36. X of a Kind in a Deck of Cards (https://leetcode.com/problems/x-of-a-kind-in-a-deck-of-cards)
  37. Minimum Area Rectangle (https://leetcode.com/problems/minimum-area-rectangle)
  38. Validate Stack Sequences (https://leetcode.com/problems/validate-stack-sequences)
  39. Flip Equivalent Binary Trees (https://leetcode.com/problems/flip-equivalent-binarytrees)
  40. Minimum Domino Rotations For Equal Row (https://leetcode.com/problems/minimum-domino-rotations-for-equal-row)
  41. Longest String Chain (https://leetcode.com/problems/longest-string-chain)
  42. Shortest Way to Form String (https://leetcode.com/problems/shortest-way-to-formstring)
  43. Confusing Number II (https://leetcode.com/problems/confusing-number-ii)
  44. Delete Nodes And Return Forest (https://leetcode.com/problems/delete-nodes-andreturn-forest)
  45. Snapshot Array (https://leetcode.com/problems/snapshot-array)
  46. String Transforms Into Another String (https://leetcode.com/problems/string-transformsinto-another-string)
  47. Divide Chocolate (https://leetcode.com/problems/divide-chocolate)
  48. Divide Array in Sets of K Consecutive Numbers (https://leetcode.com/problems/divide-array-in-sets-of-k-consecutive-numbers)
  49. Minimum Distance to Type a Word Using Two Fingers
    (https://leetcode.com/problems/minimum-distance-to-type-a-word-using-two-fingers)
  50. Time Needed to Inform All Employees (https://leetcode.com/problems/time-needed-toinform-all-employees)

Wednesday, November 6, 2019

Common Database Interview Questions

SQL query to delete duplicate rows














Delete duplicate rows using Common Table Expression(CTE)

   WITH CTE AS
(
SELECT *,ROW_NUMBER() OVER (PARTITION BY col1,col2,col3 ORDER BY col1,col2,col3) AS RN
FROM MyTable
)

DELETE FROM CTE WHERE RN<>1
 

Ref: http://www.besttechtools.com/articles/article/sql-query-to-delete-duplicate-rows

strongly recommend to follow this article ::http://codaffection.com/sql-server-article/delete-duplicate-rows-in-sql-server/

nth highest salary in mysql

Solution to finding the 2nd highest salary in SQL
Now, here is what the SQL will look like:

SELECT MAX(Salary) FROM Employee
WHERE Salary NOT IN (SELECT MAX(Salary) FROM Employee )

SELECT * /*This is the outer query part */
FROM Employee Emp1
WHERE (N-1) = ( /* Subquery starts here */
SELECT COUNT(DISTINCT(Emp2.Salary))
FROM Employee Emp2
WHERE Emp2.Salary > Emp1.Salary)

Ref : https://www.programmerinterview.com/database-sql/find-nth-highest-salary-sql/


Display Nth Record from Employee table

SELECT * FROM (
  SELECT
    ROW_NUMBER() OVER (ORDER BY key ASC) AS rownumber,
    columns
  FROM tablename
) AS foo
WHERE rownumber <= n

OR

SELECT
    *
FROM
    (
        SELECT
            ROW_NUMBER () OVER (ORDER BY MyColumnToOrderBy) AS RowNum,
            *
        FROM
            Table_1
    ) sub
WHERE
    RowNum = 23


ROW_NUMBER is an analytic function. It assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order_by_clause, beginning with 1.

SELECT department_id, last_name, employee_id, ROW_NUMBER()
   OVER (PARTITION BY department_id ORDER BY employee_id) AS emp_id
   FROM employees;

DEPARTMENT_ID LAST_NAME                 EMPLOYEE_ID     EMP_ID
------------- ------------------------- ----------- ----------
           10 Whalen                            200          1
           20 Hartstein                         201          1
           20 Fay                               202          2
           30 Raphaely                          114          1
           30 Khoo                              115          2
           30 Baida                             116          3
           30 Tobias                            117          4
           30 Himuro                            118          5
           30 Colmenares                        119          6
           40 Mavris                            203          1
. . .
          100 Popp                              113          6
          110 Higgins                           205          1
          110 Gietz                             206          2

The following inner-N query selects all rows from the employees table but returns only the fifty-first through one-hundredth row:

SELECT last_name FROM
   (SELECT last_name, ROW_NUMBER() OVER (ORDER BY last_name) R FROM employees)
   WHERE R BETWEEN 51 and 100;

Ref : https://stackoverflow.com/questions/16568/how-to-select-the-nth-row-in-a-sql-database-table#42765
https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions137.htm


Display first 5 Records from Employee table

will work with above query with rownum<6

Find duplicate rows in table.

option 1 :

SELECT
    a,
    b,
    COUNT(*) occurrences
FROM t1
GROUP BY
    a,
    b
HAVING

    COUNT(*) > 1;

option 2 :

Using common table expression  (Read this fir CTE https://www.sqlservertutorial.net/sql-server-basics/sql-server-cte/)

WITH cte AS (
    SELECT
        a,
        b,
        COUNT(*) occurrences
    FROM t1
    GROUP BY
        a,
        b
    HAVING
        COUNT(*) > 1
)
SELECT
    t1.id,
    t1.a,
    t1.b
FROM t1
    INNER JOIN cte ON
        cte.a = t1.a AND
        cte.b = t1.b
ORDER BY
    t1.a,
    t1.b;

Option 3 :

Using ROW_NUMBER

WITH cte AS (
    SELECT
        col,
        ROW_NUMBER() OVER (
            PARTITION BY col
            ORDER BY col) row_num
    FROM
        t1
)
SELECT * FROM cte
WHERE row_num > 1;

Ref : https://www.sqlservertutorial.net/sql-server-basics/sql-server-find-duplicates/


How to find Nth highest salary from a table

DENSE_RANK
DENSE_RANK computes the rank of a row in an ordered group of rows and returns the rank as a NUMBER.

https://www.sqlservertutorial.net/sql-server-window-functions/sql-server-dense_rank-function/



Option 1 :
Using DENSE_RANK()

select * from(
select ename, sal, dense_rank()
over(order by sal desc)r from Employee)
where r=&n;

https://www.geeksforgeeks.org/find-nth-highest-salary-table/



SELECT * FROM ( SELECT e.*, ROW_NUMBER() OVER (ORDER BY salary DESC) rn FROM Employee e ) WHERE rn = N; /*N is the nth highest salary*/

Read more: https://javarevisited.blogspot.com/2016/01/4-ways-to-find-nth-highest-salary-in.html#ixzz6A4ttYeVW

Sunday, September 22, 2019

Spring Boot Interview Questions - Part 1

1. What does the @SpringBootApplication annotation do internally?

@SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration, and @ComponentScan with their default attributes.

@Configuration :
Indicates that a class declares one or more @Bean methods and may be processed by the Spring container to generate bean definitions and service requests for those beans at runtime, for example:
 @Configuration
 public class AppConfig {

     @Bean
     public MyBean myBean() {
         // instantiate, configure and return bean ...
     }
 }

@EnableAutoConfiguration
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.

@ComponentScan
Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML's <context:component-scan> element.
Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

2. How to disable a specific auto-configuration class or exclude any package?


//By using "exclude"- in classpath
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})


//By using "excludeName" - not in classpath
@EnableAutoConfiguration(excludeName={Foo.class})

//By using property file
spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration

3.  What is Spring Actuator? What are its advantages?

It provides many features, i.e. what beans are created, the mapping in the controller, the CPU usage, etc. Automatically gathering and auditing health and metrics can then be applied to your application.

It provides a very easy way to access the few production-ready REST endpoints and fetch all kinds of information from the web. But by using these endpoints, you can do many things to see here the endpoint docs.

Enabling/disabling the actuator is easy; the simplest way is to enable features to add the dependency (Maven/Gradle) to the spring-boot-starter-actuator, i.e. Starter. If you don't want the actuator to be enabled, then don't add the dependency.

4. What is a shutdown in the actuator?

Shutdown is an endpoint that allows the application to be gracefully shutdown. This feature is not enabled by default. You can enable this by using management.endpoint.shutdown.enabled=true in your application.properties file. But be careful about this if you are using this.

5. Is this possible to change the port of Embedded Tomcat server in Spring boot?

Yes, it's possible to change the port. You can use the application.properties file to change the port. But you need to mention "server.port" (i.e. server.port=8081). Make sure you have application.properties in your project classpath; REST Spring framework will take care of the rest. If you mention server.port=0 , then it will automatically assign any available port.

6. Can we override or replace the Embedded Tomcat server in Spring Boot?

Yes, we can replace the Embedded Tomcat with any other servers by using the Starter dependencies. You can use spring-boot-starter-jetty  or spring-boot-starter-undertow as a dependency for each project as you need.

spring-boot-starter-web comes with Embedded Tomcat. We need to exclude this dependency.

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
  </exclusions>
</dependency>

Adding Dependencies
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>

7.Can we disable the default web server in the Spring Boot application?

The major strong point in Spring is to provide flexibility to build your application loosely coupled. Spring provides features to disable the web server in a quick configuration. Yes, we can use the application.properties to configure the web application type, i.e.  spring.main.web-application-type=none.


8. How does it work? How does it know what to configure?

• Auto-configuration works by analyzing the classpath

The meat of the code is the use of the @ConditionalOnClass annotation

9. How to reload my changes on Spring Boot without having to restart server?

Include following maven dependency in the application.
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>springloaded</artifactId>
 <version>1.2.6.RELEASE</version>
</dependency>

Automatic restart

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>


10. How to implement Spring web using Spring boot?
Web Application Convenience
• Boot automatically configures
– A DispatcherServlet & ContextLoaderListener
– Spring MVC using same defaults as @EnableWebMvc
• Plus many useful extra features:
– Static resources served from classpath
• /static, /public, /resources or /META-INF/resources
– Templates served from /templates
• If Velocity, Freemarker, Thymeleaf, or Groovy on classpath
– Provides default /error mapping
• Easily overridden
– Default MessageSource for I18N

11. How to configure datasource using Spring boot?
• Use either spring-boot-starter-jdbc or spring-boot-starterdata-jpa and include a JDBC driver on classpath
• Declare properties

spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
– Spring Boot will create a DataSource with properties set
– Will even use a connection pool if the library is found on the classpath!


12 How do you add Add a Servlet, Filter or Listener to an application?
There are two ways to add Servlet, Filter, ServletContextListener and the other listeners supported by the Servlet spec to your application. You can either provide Spring beans for them or enable scanning for Servlet components.

13. How do you Enable HTTP response compression in spring boot?
HTTP response compression is supported by Jetty, Tomcat, and Undertow. It can be enabled by adding server.compression.enabled=true in application.properties.

14. How to execute Spring Batch jobs on startup?
Spring Batch auto-configuration is enabled by adding @EnableBatchProcessing (from Spring Batch) somewhere in your context. By default, it executes all Jobs in the application context on startup.

15. How do you Create a deployable war file in spring boot?
Step 1: Extend SpringBootServletInitializer and override its configure method.
Step 2: Change packing type to war in pom.xml or in build.gradle.
Step 3: Mark the embedded servlet container dependency as provided.

16.  How to write custom log configuration in spring boot?
You can force Spring Boot to use a particular logging system using the org.springframework.boot.logging.LoggingSystem system property. The value should be the fully-qualified class name of a logging system implementation. You can also disable Spring Boot’s logging configuration entirely by using a value of none.

17. What are Profiles in spring boot?
Spring Profiles provide a way to segregate parts of your application configuration and make it only available in certain environments. Any @Component or @Configuration can be marked with @Profile to limit when it is loaded.

18. What is spring-boot-starter-parent?
The spring-boot-starter-parent is a special starter that makes Maven or Gradle dependency-management easier by adding jars to your classpath.
It adds a basic set of spring jars needed for any type of spring based applications.

19. Can you control logging with Spring Boot? How?
Yes, we can control logging with Spring Boot by specifying log levels on application.properties file. Spring Boot loads this file when it exists in the classpath and it can be used to configure both Spring Boot and application code.

Spring Boot uses Commons Logging for all internal logging and you can change log levels by adding following lines in the application.properties file:

logging.level.org.springframework=DEBUG
logging.level.com.demo=INFO

20. 

Multithreading | Concurrency Interview Questions (Along with JAVA 8 Enhancements)

1. How can a Java application access the current thread?



public class MainThread {

    public static void main(String[] args) {

        long id = Thread.currentThread().getId();

        String name = Thread.currentThread().getName();

        ...

    }

}



2. What properties does each Java thread have?

Each Java thread has the following properties:



an identifier of type long that is unique within the JVM

a name of type String

a priority of type int

a state of type java.lang.Thread.State

a thread group the thread belongs to



3. What states can a thread have and what is the meaning of each state?

4. Is it possible to start a thread twice?

No, after having started a thread by invoking its start() method, a second invocation of start() will throw an IllegalThreadStateException.

5. What is a daemon thread?

A daemon thread is a thread whose execution state is not evaluated when the JVM decides if it should stop or not. The JVM stops when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement for example monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped:





public class Example {

    private static class MyDaemonThread extends Thread {

        public MyDaemonThread() {

            setDaemon(true);

        }

        @Override

        public void run() {

            while (true) {

                try {

                    Thread.sleep(1);

                } catch (InterruptedException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new MyDaemonThread();

        thread.start();

    }

}

The example application above terminates even though the daemon thread is still running in its endless while loop.



6.How to take Thread Dump



You can generate a thread dump under Unix/Linux by running kill -QUIT <pid>, and under Windows by hitting Ctl + Break



7. What are differences between wait() and sleep() method in Java?

wait():

wait() method releases the lock.

wait() is the method of Object class.

wait() is the non-static method – public final void wait() throws InterruptedException { //…}

wait() should be notified by notify() or notifyAll() methods.

wait() method needs to be called from a loop in order to deal with false alarm.

wait() method must be called from synchronized context (i.e. synchronized method or block), otherwise it will throw IllegalMonitorStateException

sleep():



sleep() method doesn’t release the lock.

sleep() is the method of java.lang.Thread class.

sleep() is the static method – public static void sleep(long millis, int nanos) throws InterruptedException { //… }

after the specified amount of time, sleep() is completed.

sleep() better not to call from loop(i.e. see code below).

sleep() may be called from anywhere. there is no specific requirement.



8.  What happens when an uncaught exception leaves the run() method?

I can happen that an unchecked exception escapes from the run() method. In this case the thread is stopped by the Java Virtual Machine. It is possible to catch this exception by registering an instance that implements the interface UncaughtExceptionHandler as an exception handler.



This is either done by invoking the static method Thread.setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler), which tells the JVM to use the provided handler in case there was no specific handler registerd on the thread itself, or by invoking setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler) on the thread instance itself.



9. What is the difference between the two interfaces Runnable and

Callable?



The interface Runnable defines the method run() without any return value whereas the interface Callable allows the method call() to return a value and to throw an exception.



10. What is a shutdown hook?

A shutdown hook is a thread that gets executed when the JVM shuts down. It can be registered by invoking addShutdownHook(Runnable) on the Runtime instance:



Runtime.getRuntime().addShutdownHook(new Thread() {

    @Override

    public void run() {

    }

});



11. Need for Callable



There are two ways of creating threads – one by extending the Thread class and other by creating a thread with a Runnable. However, one feature lacking in  Runnable is that we cannot make a thread return result when it terminates, i.e. when run() completes. For supporting this feature, the Callable interface is present in Java.



12. Callable vs Runnable



For implementing Runnable, the run() method needs to be implemented which does not return anything, while for a Callable, the call() method needs to be implemented which returns a result on completion. Note that a thread can’t be created with a Callable, it can only be created with a Runnable.

Another difference is that the call() method can throw an exception whereas run() cannot.



A Runnable, however, does not return a result and cannot throw a checked exception.



Method signature that has to overridden for implementing Callable.



public Object call() throws Exception;



13. Future

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation. The result can only be retrieved using method get when the computation has completed, blocking if necessary until it is ready. Cancellation is performed by the cancel method. Additional methods are provided to determine if the task completed normally or was cancelled. Once a computation has completed, the computation cannot be cancelled.



Observe that Callable and Future do two different things – Callable is similar to Runnable, in that it encapsulates a task that is meant to run on another thread, whereas a Future is used to store a result obtained from a different thread. In fact, the Future can be made to work with Runnable as well, which is something that will become clear when Executors come into the picture.



 14. Shutting down exector



Finally, When you are done using the ExecutorService you should shut it down, so the threads do not keep running.



1

executor.shutdown();

For instance, if your application is started via a main() method and your main thread exits your application, the application will keep running if you have an active ExecutorService in your application. The active threads inside this ExecutorService prevents the JVM from shutting down.



To terminate the threads inside the ExecutorService you call its shutdown() method. The ExecutorService will not shut down immediately, but it will no longer accept new tasks, and once all threads have finished current tasks, the ExecutorService shuts down. All tasks submitted to the ExecutorService before shutdown() is called, are executed.



15.  Future Task Example :



CallableCalculater.java:


package com.jcg;

import java.util.concurrent.Callable;

/**
 * @author ashraf
 *
 */
public class CallableCalculater implements Callable {

    private long first;
    private long last;
    private long divisor;
   

    /**
     * Instantiates a new callable calculater.
     *
     * @param first the first
     * @param last the last
     * @param divisor the divisor
     */
    public CallableCalculater(long first, long last, long divisor) {
        this.first = first;
        this.last = last;
        this.divisor = divisor;
    }


    @Override
    public Long call() throws Exception {

        return Calculater.calculateNumberOfDivisible(first, last, divisor);
    }

}
CallableCalculater.java is wrapping the calculateNumberOfDivisible() of Calculater.java in a Callable task to be given to our FutureTask later on.

FutureTaskDemo.java:


package com.jcg;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;

/**
 * @author ashraf
 *
 */
public class FutureTaskDemo {
   
    // Maximum number to check
    public static final long MAX_NUMBER = 3000000000l;
   
    // DIVISOR to be used in calculation
    private static final long DIVISOR = 3;

    /**
     * @param args
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public static void main(String[] args) {
       
        // Sequential execution
        System.out.println("Starting sequential execution ....");
        long timeStart = System.currentTimeMillis();
        long result = Calculater.calculateNumberOfDivisible(0, MAX_NUMBER, DIVISOR);
        long timeEnd = System.currentTimeMillis();
        long timeNeeded = timeEnd - timeStart;
        System.out.println("Result         : " + result + " calculated in " + timeNeeded + " ms");
       
       
        // Parallel execution
        System.out.println("Starting parallel execution ....");
        long timeStartFuture = System.currentTimeMillis();
       
        long resultFuture = 0;
       
        // Create a new ExecutorService with 2 thread to execute and store the Futures
        ExecutorService executor = Executors.newFixedThreadPool(2);
        List<FutureTask> taskList = new ArrayList<FutureTask>();

        // Start thread for the first half of the numbers
        FutureTask futureTask_1 = new FutureTask(new CallableCalculater(0, MAX_NUMBER / 2, DIVISOR));
        taskList.add(futureTask_1);
        executor.execute(futureTask_1);

        // Start thread for the second half of the numbers
        FutureTask futureTask_2 = new FutureTask(new CallableCalculater(MAX_NUMBER / 2 + 1, MAX_NUMBER, 3));
        taskList.add(futureTask_2);
        executor.execute(futureTask_2);

        // Wait until all results are available and combine them at the same time
        for (FutureTask futureTask : taskList) {
            try {
                resultFuture += futureTask.get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }
       
        // Shutdown the ExecutorService
        executor.shutdown();
       
        long timeEndFuture = System.currentTimeMillis();
        long timeNeededFuture = timeEndFuture - timeStartFuture;
        System.out.println("Result (Future): " + resultFuture + " calculated in " + timeNeededFuture + " ms");

    }

}


16.  Fork/Join Framework



The effective use of parallel cores in a Java program has always been a challenge. There were few home-grown frameworks that would distribute the work across multiple cores and then join them to return the result set. Java 7 has incorporated this feature as a Fork and Join framework.



Basically the Fork-Join breaks the task at hand into mini-tasks until the mini-task is simple enough that it can be solved without further breakups. It’s like a divide-and-conquer algorithm. One important concept to note in this framework is that ideally no worker thread is idle. They implement a work-stealing algorithm in that idle workers steal the work from those workers who are busy.



ForkJoinPool



The ForkJoinPool is basically a specialized implementation of ExecutorService implementing the work-stealing algorithm we talked about above. We create an instance of ForkJoinPool by providing the target parallelism level i.e. the number of processors as shown below:



ForkJoinPool pool = new ForkJoinPool(numberOfProcessors);



Where numberOfProcessors = Runtime.getRunTime().availableProcessors();



If you use a no-argument constructor, by default, it creates a pool of size that equals the number of available processors obtained using above technique.

Although you specify any initial pool size, the pool adjusts its size dynamically in an attempt to maintain enough active threads at any given point in time. Another important difference compared to other ExecutorService's is that this pool need not be explicitly shutdown upon program exit because all its threads are in daemon mode.



ForkJoinTask





This is an abstract class for creating tasks that run within a ForkJoinPool. The Recursiveaction and RecursiveTask are the only two direct, known subclasses of ForkJoinTask. The only difference between these two classes is that the RecursiveAction does not return a value while RecursiveTask does have a return value and returns an object of specified type.



In both cases, you would need to implement the compute method in your subclass that performs the main computation desired by the task.



The ForkJoinTask class provides several methods for checking the execution status of a task. The isDone() method returns true if a task completes in any way. The isCompletedNormally() method returns true if a task completes without cancellation or encountering an exception, and isCancelled() returns true if the task was cancelled. Lastly, isCompletedabnormally() returns true if the task was either cancelled or encountered an exception.



18 Example Implementations of Fork/Join Pool Framework

In this example, you will learn how to use the asynchronous methods provided by the ForkJoinPool and ForkJoinTask classes for the management of tasks. You are going to implement a program that will search for files with a determined extension inside a folder and its subfolders. The ForkJoinTask class you’re going to implement will process the content of a folder. For each subfolder inside that folder, it will send a new task to the ForkJoinPool class in an asynchronous way. For each file inside that folder, the task will check the extension of the file and add it to the result list if it proceeds.

The solution to above problem is implemented in FolderProcessor class, which is given below:

Implementation Sourcecode
FolderProcessor.java

package forkJoinDemoAsyncExample;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.RecursiveTask;

public class FolderProcessor extends RecursiveTask<List<String>>
{
   private static final long serialVersionUID = 1L;
   //This attribute will store the full path of the folder this task is going to process.
   private final String      path;
   //This attribute will store the name of the extension of the files this task is going to look for.
   private final String      extension;

   //Implement the constructor of the class to initialize its attributes
   public FolderProcessor(String path, String extension)
   {
      this.path = path;
      this.extension = extension;
   }

   //Implement the compute() method. As you parameterized the RecursiveTask class with the List<String> type,
   //this method has to return an object of that type.
   @Override
   protected List<String> compute()
   {
      //List to store the names of the files stored in the folder.
      List<String> list = new ArrayList<String>();
      //FolderProcessor tasks to store the subtasks that are going to process the subfolders stored in the folder
      List<FolderProcessor> tasks = new ArrayList<FolderProcessor>();
      //Get the content of the folder.
      File file = new File(path);
      File content[] = file.listFiles();
      //For each element in the folder, if there is a subfolder, create a new FolderProcessor object
      //and execute it asynchronously using the fork() method.
      if (content != null)
      {
         for (int i = 0; i < content.length; i++)
         {
            if (content[i].isDirectory())
            {
               FolderProcessor task = new FolderProcessor(content[i].getAbsolutePath(), extension);
               task.fork();
               tasks.add(task);
            }
            //Otherwise, compare the extension of the file with the extension you are looking for using the checkFile() method
            //and, if they are equal, store the full path of the file in the list of strings declared earlier.
            else
            {
               if (checkFile(content[i].getName()))
               {
                  list.add(content[i].getAbsolutePath());
               }
            }
         }
      }
      //If the list of the FolderProcessor subtasks has more than 50 elements,
      //write a message to the console to indicate this circumstance.
      if (tasks.size() > 50)
      {
         System.out.printf("%s: %d tasks ran.\n", file.getAbsolutePath(), tasks.size());
      }
      //add to the list of files the results returned by the subtasks launched by this task.
      addResultsFromTasks(list, tasks);
      //Return the list of strings
      return list;
   }

   //For each task stored in the list of tasks, call the join() method that will wait for its finalization and then will return the result of the task.
   //Add that result to the list of strings using the addAll() method.
   private void addResultsFromTasks(List<String> list, List<FolderProcessor> tasks)
   {
      for (FolderProcessor item : tasks)
      {
         list.addAll(item.join());
      }
   }

   //This method compares if the name of a file passed as a parameter ends with the extension you are looking for.
   private boolean checkFile(String name)
   {
      return name.endsWith(extension);
   }
}
And to use above FolderProcessor, follow below code:

Main.java

package forkJoinDemoAsyncExample;

import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.TimeUnit;

public class Main
{
   public static void main(String[] args)
   {
      //Create ForkJoinPool using the default constructor.
      ForkJoinPool pool = new ForkJoinPool();
      //Create three FolderProcessor tasks. Initialize each one with a different folder path.
      FolderProcessor system = new FolderProcessor("C:\\Windows", "log");
      FolderProcessor apps = new FolderProcessor("C:\\Program Files", "log");
      FolderProcessor documents = new FolderProcessor("C:\\Documents And Settings", "log");
      //Execute the three tasks in the pool using the execute() method.
      pool.execute(system);
      pool.execute(apps);
      pool.execute(documents);
      //Write to the console information about the status of the pool every second
      //until the three tasks have finished their execution.
      do
      {
         System.out.printf("******************************************\n");
         System.out.printf("Main: Parallelism: %d\n", pool.getParallelism());
         System.out.printf("Main: Active Threads: %d\n", pool.getActiveThreadCount());
         System.out.printf("Main: Task Count: %d\n", pool.getQueuedTaskCount());
         System.out.printf("Main: Steal Count: %d\n", pool.getStealCount());
         System.out.printf("******************************************\n");
         try
         {
            TimeUnit.SECONDS.sleep(1);
         } catch (InterruptedException e)
         {
            e.printStackTrace();
         }
      } while ((!system.isDone()) || (!apps.isDone()) || (!documents.isDone()));
      //Shut down ForkJoinPool using the shutdown() method.
      pool.shutdown();
      //Write the number of results generated by each task to the console.
      List<String> results;
      results = system.join();
      System.out.printf("System: %d files found.\n", results.size());
      results = apps.join();
      System.out.printf("Apps: %d files found.\n", results.size());
      results = documents.join();
      System.out.printf("Documents: %d files found.\n", results.size());
   }
}
Output of above program will look like this:

Main: Parallelism: 2
Main: Active Threads: 3
Main: Task Count: 1403
Main: Steal Count: 5551
******************************************
******************************************
Main: Parallelism: 2
Main: Active Threads: 3
Main: Task Count: 586
Main: Steal Count: 5551
******************************************
System: 337 files found.
Apps: 10 files found.
Documents: 0 files found.

How it works?
In the FolderProcessor class, Each task processes the content of a folder. As you know, this content has the following two kinds of elements:

Files
Other folders
If the task finds a folder, it creates another Task object to process that folder and sends it to the pool using the fork() method. This method sends the task to the pool that will execute it if it has a free worker-thread or it can create a new one. The method returns immediately, so the task can continue processing the content of the folder. For every file, a task compares its extension with the one it’s looking for and, if they are equal, adds the name of the file to the list of results.

Once the task has processed all the content of the assigned folder, it waits for the finalization of all the tasks it sent to the pool using the join() method. This method called in a task waits for the finalization of its execution and returns the value returned by the compute() method. The task groups the results of all the tasks it sent with its own results and returns that list as a return value of the compute() method.





19. Difference between Fork/Join Framework And ExecutorService



The main difference between the Fork/Join and the Executor frameworks is the work-stealing algorithm. Unlike the Executor framework, when a task is waiting for the finalization of the sub-tasks it has created using the join operation, the thread that is executing that task (called worker thread ) looks for other tasks that have not been executed yet and begins its execution. By this way, the threads take full advantage of their running time, thereby improving the performance of the application.



Existing Implementations in JDK

There are some generally useful features in Java SE which are already implemented using the fork/join framework.



1) One such implementation, introduced in Java SE 8, is used by the java.util.Arrays class for its parallelSort() methods. These methods are similar to sort(), but leverage concurrency via the fork/join framework. Parallel sorting of large arrays is faster than sequential sorting when run on multiprocessor systems.



2) Parallelism used in Stream.parallel(). Read more about this parallel stream operation in java 8.





20.  JAVA 8 Enhancements



Java JDK8 included the big fat interface called CompletionStage in the java.util.concurrent package. The same package also contains CompletableFuture which is a library implementation of CompletionStage. In this post we would see how CompletionStage and CompletableFuture provide piped asynchronous API thus enhancing reactive programming support in Java at the platform level.





21. CompletableFuture



CompletableFuture is a concrete implementation of a CompletionStage and it also implements the java.util.concurrent.Future interface as well. This is the class which models a task (which may or may not be asynchronous) and exposes various methods to interact with the task; for instance, we have methods to check if the task has completed; whether it has completed exceptionally; we even have APIs to chain dependencies between multiple tasks; cancelling uncompleted tasks, so on and so forth. We would be looking into some of these APIs soon.





A CompletableFuture can be instantiated and related methods can be called upon it, and we will see this in action in the subsequent section. However, there are convenient, static overloaded factory methods which provides further flexibility so that rather than worrying about harnessing CompletableFuture for a task, we can just concentrate on the task itself. I will explain this in a bit, but lets quickly have a look at the overloaded factory methods that I am talking about:

CompletableFuture supplyAsync() API


public static CompletableFuture supplyAsync(Supplier supplier)
public static CompletableFuture supplyAsync(Supplier supplier, Executor executor)
java.util.function.Supplier is a functional interface which accepts nothing and “supplies” an output. The supplyAsync() API expects that a result-producing task be wrapped in a Supplier instance and handed over to the supplyAsync() method, which would then return a CompletableFuture representing this task. This task would, by default, be executed with one of the threads from the standard java.util.concurrent.ForkJoinPool (public static ForkJoinPool commonPool()).

However, we can also provide custom thread pool by passing a java.util.concurrent.Executor instance and as such the Supplier tasks would be scheduled on threads from this Executor instance.

So to sum up the, the easiest way of using CompletableFuture API is to wrap the task you want to execute in a Supplier – you may additionally supply an Executor service as needed – and hand it over to the supplyAsync() method which would return you the CompletableFuture!

There is yet another variant API available for retrieving a CompletableFuture. Notice that while discussing supplyAsync() I wrote that this is to be used when task would be result-bearing, in other words, when we expect the task to return back some output. However, in all cases where the task might not return any output, we may use the runAsyn() API, instead:

CompletableFuture runAsync() API


public static CompletableFuture runAsync(Runnable runnable)
public static CompletableFuture runAsync(Runnable runnable, Executor executor)
Notice that runAsync() expects a java.lang.Runnable instance, and we know that Runnable.run() does not return any result! This is the reason that the returned CompletableFuture type erases itself to Void type.



22. Completing the CompletableFuturer manually



A CompletableFuture can be instantiated through its no-arg constructor. And then we can manually provide a Runnable instance to a custom thread; and then CompletableFuture API provides complete method using which the CompletableFuture can be manually completed:

How to manually complete a CompletableFuture


//1. Why named CompletableFuture?
        CompletableFuture completableFuture1 = new CompletableFuture();
        new Thread (()-> {
            try {
                Thread.sleep(4000L);
            } catch (Exception e) {
                completableFuture1.complete(-100.0);
            }
            /*
             * we can manually "complete" a CompletableFuture!!
             * this feature is not found with the classical Future interface
             */
            completableFuture1.complete(100.0);
        },"CompFut1-Thread").start();
       
        System.out.println("ok...waiting at: "+new Date());
        System.out.format("compFut value and received at: %f, %s \n", completableFuture1.join(), new Date());


23. More cases of Completable future



https://www.callicoder.com/java-8-completablefuture-tutorial/



https://examples.javacodegeeks.com/core-java/util/concurrent/completablefuture/java-completionstage-completablefuture-example/

Very Good Article for Completable future :

https://netjs.blogspot.com/2018/11/completablefuture-in-java-with-examples.html


24.