Home - ashish-ghub/docs GitHub Wiki

Interview preparation

https://github.com/wuyichen24

Java:

Trouble shooting thread dumps

java 8

https://www.interviewbit.com/java-8-interview-questions/

spring-security https://www.interviewbit.com/spring-security-interview-questions/

Owasp: https://owasp.org/www-project-top-ten/ https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html

Spring: https://www.interviewbit.com/spring-interview-questions/

SQL https://www.interviewbit.com/sql-interview-questions/

Linux https://www.interviewbit.com/linux-interview-questions/


Java

  1. What is dynamic polymorphism ?
  2. What is immutable class? example, use cases
  3. Write a immutable class for a Employee has String name, int id, Date doj, Float salary, hobbies List
  4. what changes needs be done in this class to use it as key in hashmap
  5. want to sort employee basis on salary
  6. add clone functionality to Employee
  7. What is concurrent hash map? how it works ?
  8. What is the difference between thread and process? inter thread communication and inter-process communication
  1. When should I use a CompletionService over an ExecutorService?

You should use a CompletionService over an ExecutorService when you need to efficiently process results as they become available, regardless of the order in which tasks were submitted. Here are specific scenarios and use cases where CompletionService is preferable:

  1. what is the issue in current code how you can improve it

public static String getDepartmentName(Employee employee) { if (employee != null) { Department department = employee.getDepartment(); if (department != null) { String name = department.getName(); if (name != null) { return name; } } } return "Unknown Department"; }

public static String getDepartmentName(Employee employee) { return Optional.ofNullable(employee) // Wrap the employee in an Optional .map(Employee::getDepartment) // Get the department if the employee exists .map(Department::getName) // Get the name if the department exists .orElse("Unknown Department"); // Default value if any of the above is null }


Key Scenarios for Using CompletionService

  1. Results in Completion Order:

    • If you want to handle the results as soon as tasks complete, rather than waiting for all tasks to finish, CompletionService is ideal.
    • For example:
      • Processing web scraping tasks where you consume each result as soon as a page is scraped.
      • Handling database queries that return at different times.
  2. Dynamic Result Processing:

    • If the time required to process results varies between tasks, you can consume results dynamically with CompletionService, keeping your program responsive.
    • Example: Aggregating responses from multiple APIs that have variable response times.
  3. Optimizing Throughput:

    • With CompletionService, you can start consuming and processing results immediately without waiting for all tasks to complete.
    • This helps in reducing the memory footprint by processing and discarding results incrementally.
  4. Polling for Results:

    • Use CompletionService if you need to poll for results but do not want to block the calling thread unnecessarily.
    • The poll() method allows you to check for completed tasks without blocking.
  5. Simpler Result Management:

    • When using ExecutorService, you would need to track all submitted Future objects and iterate through them to check if they are done.
    • CompletionService automatically handles this by maintaining an internal queue of completed tasks.

When to Stick with ExecutorService

  1. Task Submission and Waiting for All Results:

    • If your workflow requires submitting tasks and waiting for all of them to complete before proceeding, then ExecutorService (along with invokeAll) might be simpler.
  2. Sequential Result Processing:

    • If results need to be processed in the exact order of task submission, ExecutorService is a better fit because CompletionService processes tasks based on completion order.
  3. Custom Complex Logic:

    • If you need more control over task execution, result collection, or specific synchronization requirements, ExecutorService gives you more flexibility.

Practical Examples

Using CompletionService:

Process tasks in the order they complete:

import java.util.concurrent.*;

public class CompletionServiceExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        CompletionService<String> completionService = new ExecutorCompletionService<>(executor);

        // Submit tasks
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            completionService.submit(() -> {
                Thread.sleep(taskId * 1000); // Simulate variable task duration
                return "Result from Task " + taskId;
            });
        }

        // Consume results as they complete
        for (int i = 1; i <= 5; i++) {
            Future<String> result = completionService.take(); // Blocks until a task completes
            System.out.println(result.get());
        }

        executor.shutdown();
    }
}

Using ExecutorService:

Wait for all tasks to complete and process results in submission order:

import java.util.concurrent.*;

public class ExecutorServiceExample {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executor = Executors.newFixedThreadPool(3);
        List<Future<String>> futures = new ArrayList<>();

        // Submit tasks
        for (int i = 1; i <= 5; i++) {
            final int taskId = i;
            futures.add(executor.submit(() -> {
                Thread.sleep(taskId * 1000); // Simulate variable task duration
                return "Result from Task " + taskId;
            }));
        }

        // Consume results in submission order
        for (Future<String> future : futures) {
            System.out.println(future.get()); // Blocks until the task is done
        }

        executor.shutdown();
    }
}

Key Differences

Feature CompletionService ExecutorService
Result Order Based on task completion (dynamic). Based on task submission (static).
Result Access Non-blocking poll() or blocking take() for completed. Must iterate over Future objects and use isDone() or get().
Ease of Incremental Processing Simple, results are queued as tasks finish. Requires manual polling or synchronization for incremental results.
Flexibility Best for dynamic, unordered result processing. Best for static or sequential result handling.

Final Recommendation

  • Use CompletionService when completion order is more important than submission order, and you want to process results as they are available.
  • Stick with ExecutorService when you need submission order or want to block until all tasks finish for simpler workflows.

Q. how to implement retry basic retry mechanism
int maxRetries = 3; int retryCount = 0;

`while (retryCount < maxRetries) {`
`try {`
	`// Your operation here`
	`break; // Exit loop on success`
`} catch (Exception e) {`
	`// Handle exception (log, wait)`
	`retryCount++;`
`}`
`}`

`if (retryCount == maxRetries) {`
`// Handle all retries failed scenario`
`}   ` 

Q. what is the issue with simple retry and what are better way ?

There are a couple of issues with a simple retry mechanism that just repeats an operation a fixed number of times:

Increased Load: If multiple clients retry simultaneously after a failure, it can overload the system even further. This can worsen the original problem and make recovery more difficult. Inefficiency: Retries might happen too frequently, wasting resources if the underlying issue isn't resolved quickly.

              Simple Retry	             Exponential Backoff with Jitter

Load on System Can overload Lower load due to distributed retries Efficiency Inefficient retries possible More efficient retries Configuration Limited Flexible configuration (attempts, delay) Exception Handling All exceptions retried Specific exceptions retried

Here are better ways to implement retries with backoff:

Exponential Backoff: This strategy increases the wait time between retries exponentially. This gives the service more time to recover with each attempt and avoids overwhelming it with retries.

**Random Jitter: ** In addition to exponential backoff, introducing a random amount of wait time (jitter) can further prevent retry collisions. This ensures clients don't all retry at the exact same moment after the backoff period.

Configurable Retry Attempts: The ability to define the maximum number of retries allows you to control how persistent the retry behavior is.

Specific Exception Handling: Not all exceptions warrant retries. Ideally, you should only retry for transient exceptions that might resolve themselves on a subsequent attempt.

**Security : **

What is a vulnerability? how many types of them you have addressed ?

What is micro service architecture ?

What are the various security feature provided by spring ?

What is Directory traversal/ path-traversal sequences ? How to prevent a directory traversal attack? https://portswigger.net/web-security/file-path-traversal

What is oauth2 ? what is different grant type in oauth2 ?

What is CSRF? how would you design a solution to apply it across microservices?

What is XSS ? how do you fix them ?

What is brute force attack ? How would you protect it for authentication ? How would you design this feature ? ( good password policy with password size at least 8 or more chars, IP blocking, ( when ip is common like citrix or load balancer ip), MFA)

How would you design a solution where you need to enable you customer's employee can login with same username and password from our application login page ?

How would you design a solution where you need to enable, authentication from customer's portal and based on users role defined at customer end we need to map roles in our product for authorization ?

What is Oidc ?

How would you develop a system or procedure to eliminate vulnerabilities across products in a systematic way may initially targeting only critical then in next sprint major and so on ?

What is issue with this below code ?

  1. XSS

    <script> var x = '<%= token %>'; var d = document.createElement('div'); d.innerHTML = x; document.body.appendChild(d); </script>
  2. Open redirection issue

    protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
    {
      String query = request.getQueryString();
      if (query.contains("fwd"))
       {
          String fwd = request.getParameter("fwd");
          try
          {
            request.getRequestDispatcher(fwd).forward(request, response);
          }
          catch (ServletException e)
          {
            e.printStackTrace();
          }
       }
    }
    

**Trouble shooting **

  • Deadlock identification, mitigations
  • Application slow analysis
  • Memory leaks identification
  • what you do to remote debug a docker running container

performance issue troubleshooting

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/opt/com/data/heapdump/heapdump-reporter-pm-23-9ptwc.dump -XX:InitialHeapSize=14000000000 -XX:MaxHeapSize=14000000000 -XX:+PrintCommandLineFlags -XX:+PrintGC -XX:+PrintGCApplicationConcurrentTime -XX:+PrintGCApplicationStoppedTime -XX:+PrintGCDateStamps -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC -XX:+PrintSafepointStatistics -XX:+PrintTenuringDistribution -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC

**GWT / java script: **

What GWT ? its feature? How do you debug GWT application ? https://www.tutorialspoint.com/gwt/gwt_interview_questions.htm

https://medium.com/@pulapaphani/why-overriding-equals-and-hashcode-in-java-b5f869f985d2

Employee implements Comparable {

private String name; 
private int salary; 

// Used to sort movies by year (desc order)
public int compareTo(Employee m) 
{ 
    return this.salary- m.salary; 
} 

}

solid-design-principle

https://stackify.com/solid-design-open-closed-principle/

  1. Single Responsibility Principle
  2. Open/Closed Principle
  3. Liskov Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion

https://github.com/xoraus/CrackingTheSQLInterview

XML :

https://www.tutorialspoint.com/java_xml/java_xml_parsers.htm

Linux :

Symbolic link ln -s src folderpath linkname

Listing java process: ps -auxww grep java | grep <>

checking free memory : free -g

check size of directory du -sh path

Heapdums:

jmap -dump:format=b,file= Example: jmap -dump:format=b,file=/opt/tmp/heapdump.bin 37320

jcmd

  1. jcmd GC.heap_dump
  2. where
  3. pid: is the Java Process Id, whose heap dump should be captured
  4. file-path: is the file path where heap dump will be written in to.
  5. Example:
  6. 1 jcmd 37320 GC.heap_dump /opt/tmp/heapdump.bin

What is a vulnerability? A vulnerability is a hole or a weakness in the application, which can be a design flaw or an implementation bug, that allows an attacker to cause harm to the stakeholders of an application. Stakeholders include the application owner, application users, and other entities that rely on the application.

Please do not post any actual vulnerabilities in products, services, or web applications. Those disclosure reports should be posted to bugtraq or full-disclosure mailing lists.

Examples of vulnerabilities Lack of input validation on user input Lack of sufficient logging mechanism Fail-open error handling Not closing the database connection properly

https://owasp.org/www-project-top-ten/

  1. ACID Properties in DBMS transaction

Atomicity Atomicity requires that each transaction be "all or nothing": if one part of the transaction fails, then the entire transaction fails, and the database state is left unchanged. An atomic system must guarantee atomicity in each and every situation, including power failures, errors and crashes. To the outside world, a committed transaction appears (by its effects on the database) to be indivisible ("atomic"), and an aborted transaction does not happen.

Consistency The consistency property ensures that any transaction will bring the database from one valid state to another. Any data written to the database must be valid according to all defined rules, including constraints, cascades, triggers, and any combination thereof. This does not guarantee correctness of the transaction in all ways the application programmer might have wanted (that is the responsibility of application-level code), but merely that any programming errors cannot result in the violation of any defined rules.

Isolation The isolation property ensures that the concurrent execution of transactions results in a system state that would be obtained if transactions were executed sequentially, i.e., one after the other. Providing isolation is the main goal of concurrency control. Depending on the concurrency control method (i.e., if it uses strict - as opposed to relaxed - serializability), the effects of an incomplete transaction might not even be visible to another transaction.

Durability The durability property ensures that once a transaction has been committed, it will remain so, even in the event of power loss, crashes, or errors. In a relational database, for instance, once a group of SQL statements execute, the results need to be stored permanently (even if the database crashes immediately thereafter). To defend against power loss, transactions (or their effects) must be recorded in a non-volatile memory.

  1. Which operator is used to search for a specified text pattern in a column?

The LIKE operator is used in a WHERE clause to search for a specified pattern in a column. There are two wildcards used in conjunction with the LIKE operator: % - The percent sign represents zero, one, or multiple characters _ - The underscore represents a single character

Examples:

WHERE CustomerName LIKE 'a%' -- Finds any values that starts with "a" WHERE CustomerName LIKE '%a' -- Finds any values that ends with "a" WHERE CustomerName LIKE '%or%' -- Finds any values that have "or" in any position WHERE CustomerName LIKE 'r%' -- Finds any values that have "r" in the second position WHERE CustomerName LIKE 'a%_%' -- Finds any values that starts with "a" and are at least 3 characters in length WHERE ContactName LIKE 'a%o' -- Finds any values that starts with "a" and ends with "o"

  1. How to write a query to show the details of a student from Students table whose FirstName starts with 'K'?

SELECT * FROM Students WHERE FirstName LIKE 'K%'.

Explanation from previous question applies.

  1. performance tuning of oracle

  2. What is a trigger? Triggers in SQL is kind of stored procedures used to create a response to a specific action performed on the table. You can invoke triggers explicitly on the table in the database. Triggers are, in fact, written to be executed in response to any of the following events: A database manipulation (DML) statement (DELETE , INSERT , or UPDATE ) A database definition (DDL) statement (CREATE , ALTER , or DROP ). A database operation (SERVERERROR , LOGON , LOGOFF , STARTUP , or SHUTDOWN). Action and Event are two main components of SQL triggers when certain actions are performed the event occurs in response to that action.


XML Parser:

Dom Parser − Parses an XML document by loading the complete contents of the document and creating its complete hierarchical tree in memory.

SAX Parser − Parses an XML document on event-based triggers. Does not load the complete document into the memory.

JDOM Parser − Parses an XML document in a similar fashion to DOM parser but in an easier way.

StAX Parser − Parses an XML document in a similar fashion to SAX parser but in a more efficient way.

XPath Parser − Parses an XML document based on expression and is used extensively in conjunction with XSLT.

DOM4J Parser − A java library to parse XML, XPath, and XSLT using Java Collections Framework. It provides support for DOM, SAX, and JAXP.

⚠️ **GitHub.com Fallback** ⚠️