Scenario Based Questions in Java

Scenario 1: Caching

You need to load stock exchange security codes with price from a database and cache them for performance. The security codes need to be refreshed say every 30 minutes. This cached data needs to be populated and refreshed by a single writer thread and read by several reader threads. How will you ensure that your read/write solution is scalable and thread safe?

Solution

The java.util.concurrent.locks package provides classes that implement read/write locks where the read lock can be executed in parallel by multiple threads and the write lock can be held by only a single thread. The ReadWriteLock interface maintains a pair of associated locks, one for read-only and one for writing. The readLock( ) may be held simultaneously by multiple reader threads, while the writeLock( ) is exclusive. In general, this implementation improves performance and scalability when compared to the mutex locks (i.e. via synchronized key word) when

  1. When There Are More Read Operations and The Duration of Each Read Is Longer Compared to Write Operations and Their Duration.
  2. The Performance Also Depends on The Machine You Are Running the Code On, Especially If It Has Multi-Core Processors, As It Allows for Better Parallelism.

Caching.java

Output:

Writing .....
Reading .....12.35
Reading .....12.35

Scenario 2: Asynchronous Processing

If you have a requirement to generate online reports or feed files by pulling out millions of historical records from a database, what questions will you ask, and how will you go about designing it?

Solution:

Designing a system is all about asking the right questions to gather requirements.

Online Vs Offline? Should we restrict the online reports for only last 12 months of data to minimise the report size and to get better performance, and provide reports/feeds for the data older than 12 months via offline processing? For example, Bank statements for last 12 months via online & for transactions older than 12 months via offline asynchronous processing without blocking the customer from browsing rest of the website. Reports can be generated asynchronously and once ready can be emailed or downloaded via a URL at a later time.

What report generation framework to use like Jasper Reports, Open CSV, XSL-FO with Apache FOP, etc depending on the required output formats?

How to handle exceptional scenarios? send an error email, use a monitoring system like Tivoli or Nagios to raise production support tickets on failures, etc?

Security requirements. Are we sending feed/report with PII (i.e. Personally Identifiable Information) data via email? Do we need proper access control to restrict who can generate which online reports? Should we password protect the email attachments? Are there any compliance or regulatory requirements like PCI (i.e. Payment Card Industry), GDPR (i.e. General Data Protection Regulation), ACCC (i.e. Australian Competition and Consumer Commission), etc depending on the jurisdictions served by the application?

Should we schedule the offline reports to run during off peak time? For example, enter all the requests for a report into a "Request" table and then schedule a process to run at say midnight to refer to all pending requests in the "Request" table to generate and store the relevant reports in an outbox for the customers to download. An email can be sent to clients with the report URL to download the report.

Archival and purging straggles of the historical reports. What is the report retention period for the requirements relating to auditing and compliance purpose? How big are the files?

An online application with a requirement to produce time consuming reports or a business process (e.g. re-balancing accounts, aggregating hierarchical information, etc) could benefit from making these long running operations asynchronous. Once the reports or the long running business process is completed, the outcome can be communicated to the user via emails or asynchronously refreshing the web page via techniques known as "server push (JEE Async Servlet)" or "client pull (Refresh meta tag)". A typical example would be

  1. A user makes an online request for an aggregate report or a business process like re-balancing his/her portfolios.
  2. The user request will be saved to a database table for a separate process to periodically pick it up and process it asynchronously.
  3. The user could now continue to perform other functionality of the website without being blocked.
  4. A separate process running on the same machine or different machine can periodically scan the table for any entries and produce the necessary reports or execute the relevant business process. This could be a scheduled job that runs once during off-peak or every 10 minutes. This depends on the business requirement.
  5. Once the report or the process is completed, notify the user via emails or making the report available online to be downloaded.

Scenario 3: Regular Expression

We need to find and change a text from 'Client' to 'Customer' in 350+ html files.

Solution

Regex.java

Output:

All HTML files have been updated.

Scenario 4: Concurrency Management

Reference counting where a shared resource is incremented or decremented. The increment/decrement operations must be thread safe. For example, a counter that keeps track of the number of active logged in users by incrementing the count when users log in and decrementing the count when the users log out. Sometimes you want to allow a finite number of concurrent accesses say 3 users at a time.

Solution:

Mutex: is a single key to an object (E.g. a toilet). One person can have the key and occupy the toilet at the time. When finished, the person gives (or releases) the key to the next person in the queue. In Java, every object has a mutex and only a single thread can get hold of a mutex.

Semaphore: Is a number of free identical toilet keys. For example, having 3 toilets with identical locks and keys. The semaphore count is set to 3 at beginning and then the count is decremented as people are acquiring the key to the toilets. If all toilets are full, i.e. there are no free keys left, the semaphore count is 0. Now, when one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

ConcurrencyManagement.java

Output:

Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Semaphore is acquired
Could not acquire semaphore

Scenario 5: Externalize Business Rules

We are asked to design an application, which validates data with 100+ rules to comply with the government compliance requirements and tax laws. These compliance requirements can change and the application need to quickly and easily adapt to changing requirements.

Solution:

Harness the power of Rules Engines like Drools. Drools is a popular open source business rules and work flow engine. It helps you externalise the rules in database tables or excel spreadsheets as opposed to embedding within the Java code. The rules are executed in the form of when given a ($condition) then execute the ($consequence). The business will be the custodian of these rules that can be easily viewed on an excel spreadsheet or via querying the database tables. A GUI could be built to maintain these rules that reside in a database.

Scenario 6: Auditing

We have a requirement to maintain a history of insertion, modification, and deletion to the "Customer" table. How will you go about accomplishing this?

Solution:

  1. Create an ETL (i.e. Extract Transform & Load) batch job that periodically extracts all the changes to batch files and send those files to a Data warehouse system, which loads these batch files to a SCD Type 2 history table. SCD Type 2 means maintain each change. This is discussed in detail at 13 Data Warehouse interview Q&As - Fact Vs Dimension, CDC, SCD, etc.
  2. Asynchronously via publish & subscription paradigm. Publish each change as an event to a message oriented middle-ware like Apache Kafka, Rabbit MQ, Websphere MQ, etc & separate subscriber application will save each event to a SQL or NoSQL history table.
  3. Create database table triggers to insert superseded records to a separate history table. A database trigger is procedural code that is automatically executed in response to certain events like insert, update, etc on a particular table or view in a database. Care must be taken in using or writing triggers as incorrectly written or used triggers can significantly impact performance of your database.

Scenario 6: Student Grades System

There is a list of students with their (name, grades). We have to find the name of the student who has the highest grade.

GradeSystem.java

Output:

(First Method) Student with the highest grade:
Name: Daniel
Grade: 99.5
(Second Method) Student with the highest grade:
Name: Daniel
Grade: 99.5

Scenario 7: Data Transformation

We have Given a list of strings and we have to convert them to uppercase using Java 8 streams.

UpperCaseConverter.java

Output:

 [JAVA, PYTHON, REACT, JAVASCRIPT]

Output 2:

JAVA
PYTHON
REACT
JAVASCRIPT

Scenario 8: Filtering and Sorting on Data

For the given list of elements, perform Filtering and Sorting on the elements. Write a Java 8 program to perform operations like filter out the odd numbers from list and sort the remaining ones in ascending order.

FilterOddNumberAndSort.java

Output:

Unsorted Unfiltered List = [1, 34, 22, 13, 55, 4, 3, 87, 11, 22, 12]
Sorted Filtered List = [4, 12, 22, 22, 34]

Scenario 9: Transaction Management

For the given transaction data with (payer, payee, amount), calculate the total amount received by each payee. Here you have to use the grouping and Summing concept of Java 8.

TransactionAnalyzer.java

Output:

{Mona=270.0, Charlie=150.0, Reha=210.0}
{Mona=270.0, Charlie=150.0, Reha=210.0}

Scenario 10: Sales Management

In the retail marketplace, there are multiple transactions that happen from time to time. We have to perform the data analysis over the revenue.

For the Given list of sales transactions (transactionID, productID, quantity, price), we have to find the top N products (by revenue) sold in the last 3 months using Java 8.

Here, N is the number of products that we want.

TopNProductsByRevenue.java

Output:

Top 2 products by revenue in the last 3 months:
ProductID: 1, Revenue: 826.6999999999999
ProductID: 3, Revenue: 504.0

Scenario 12: Employee Management System

Given Employee details, we have to sort the employee details on basis of employee's name using Java 8.

EmployeeSorting.java

Output:

Mohan
Rohan
Sohan





Latest Courses