Summary

This document appears to be a Java developer interview quiz, outlining various topics like Design Patterns, Collections Framework, Stream API, Concurrency and more, with sample questions.

Full Transcript

Explain how you would implement inter-service communication in a distributed system. What tools or protocols would you use? Design Patterns 1. Objective Questions: What is the difference between the Singleton and Prototype design patterns? When would you use the Factory M...

Explain how you would implement inter-service communication in a distributed system. What tools or protocols would you use? Design Patterns 1. Objective Questions: What is the difference between the Singleton and Prototype design patterns? When would you use the Factory Method pattern versus the Abstract Factory pattern? Explain the benefits of the Observer pattern. 2. Open Questions: How would you implement a caching mechanism using the decorator design pattern? Can you design a solution for a real-world problem (e.g., booking a ticket) using the Command pattern? Let me know if you want to expand on any of these sections or if you need example answers for any of the questions. Answer it Here are answers for the quiz questions: Collections Framework Objective Answers: 1. HashMap vs. ConcurrentHashMap: HashMap is not thread-safe, while ConcurrentHashMap is thread-safe. 4/10 In ConcurrentHashMap , the entire map is not locked; instead, it uses a segmented locking mechanism for better concurrency. 2. TreeSet vs. HashSet: TreeSet maintains elements in sorted order, while HashSet does not. Use TreeSet when sorting is required, and HashSet when performance (O(1) for add, remove, contains) is critical. 3. ArrayList vs. LinkedList: ArrayList uses a dynamic array; LinkedList uses a doubly linked list. ArrayList is better for random access; LinkedList is better for frequent insertions and deletions. 4. Duplicate Handling in HashSet : HashSet uses HashMap internally and ensures uniqueness by using the hashCode and equals methods of the elements. Open Answers: 1. Designing a Data Structure for Unique Items: Use HashSet for constant-time operations. For thread-safe requirements, use ConcurrentHashMap with dummy values or Collections.synchronizedSet. 2. Fail-fast vs. Fail-safe Iterators: Fail-fast iterators (e.g., in ArrayList ) throw ConcurrentModificationException if the collection is modified structurally during iteration. Fail-safe iterators (e.g., in CopyOnWriteArrayList ) operate on a snapshot of the collection. Stream API Objective Answers: 1. map vs. flatMap : map transforms each element into another object, maintaining a one-to-one mapping. 5/10 flatMap flattens streams of streams into a single stream. 2. collect Method: The collect method accumulates elements of a Stream into a container like List , Set , or custom structures. 3. Sequential vs. Parallel Streams: Sequential streams process elements in order, using a single thread. Parallel streams split the work into multiple threads but add overhead for thread management. Open Answers: 1. Group Employees by Department: java Map avgSalaryByDept = employees.stream().collect(Collectors.groupingBy( Employee::getDepartment, Collectors.averagingDouble(Employee::getSalary) )); 2. Find Second Highest Number: java Optional secondHighest = numbers.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst(); Java 8 Features Objective Answers: 1. Purpose of Optional : 6/10 Optional helps avoid NullPointerException by explicitly representing the presence or absence of a value. 2. Functional Interfaces: Function : Accepts an input and produces a result. Consumer : Accepts an input but produces no result. Supplier : Produces a result with no input. 3. default Keyword: Introduced to add methods to interfaces without breaking existing implementations. Open Answers: 1. Refactoring Legacy Code: Replace loops with Streams. Use lambda expressions for anonymous classes implementing functional interfaces. 2. Method References Example: java List names = Arrays.asList("Alice", "Bob"); names.forEach(System.out::println); // Method reference to println Concurrency Objective Answers: 1. synchronized vs. ReentrantLock : ReentrantLock provides more control (e.g., try-lock, fairness). synchronized is easier to use but less flexible. 2. ForkJoinPool : A pool for tasks that can be broken into smaller subtasks recursively. 3. CompletableFuture : 7/10 Used for asynchronous programming. Supports chaining and combining tasks. Open Answers: 1. Multi-threaded Transaction Processing: Use a BlockingQueue for task submission and a thread pool ( ExecutorService ). Use Atomic classes or StampedLock for contention minimization. 2. Thread-safe Singleton: java public class Singleton { private static volatile Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { synchronized (Singleton.class) { if (instance == null) { instance = new Singleton(); } } } return instance; } } Spring Framework Objective Answers: 1. Annotations: @Component : Generic stereotype for Spring-managed components. @Service : Specifically for business logic/service layer. @Repository : Specifically for persistence layer. 2. Bean Lifecycle: 8/10 Steps: Instantiation -> Dependency Injection -> Initialization -> Destruction. 3. @Transactional : Manages transactions declaratively, ensuring atomicity and consistency. Open Answers: 1. REST API Design: Use @RestController , @RequestMapping , @ExceptionHandler for exception handling, and @Valid for validation. 2. Spring Security: Use OAuth2 or JWT for authentication. Implement role-based access control using @PreAuthorize or @Secured. Microservices Objective Answers: 1. API Gateway: Acts as a single entry point for microservices, handling routing, load balancing, and authentication. 2. Synchronous vs. Asynchronous Communication: Synchronous: Immediate response needed (e.g., REST API). Asynchronous: Decoupled communication (e.g., messaging systems like Kafka). 3. Service Discovery: Automatically locates services in a distributed system. Tools: Eureka, Consul, Zookeeper. Open Answers: 1. High Availability: Use load balancers, redundant instances, circuit breakers, and retries. 2. Inter-service Communication: 9/10 Use REST (synchronous) or message queues (asynchronous). Tools: RabbitMQ, Kafka, gRPC. Design Patterns Objective Answers: 1. Singleton vs. Prototype: Singleton: One instance per JVM. Prototype: A new instance for every request. 2. Factory Method vs. Abstract Factory: Factory Method: Creates objects of one type. Abstract Factory: Creates families of related objects. 3. Observer Benefits: Promotes loose coupling between subjects and observers. Open Answers: 1. Decorator Pattern for Caching: Wrap the original service with a caching layer that stores results. 2. Command Pattern: Encapsulate booking logic into commands and execute them using an invoker for better flexibility. Let me know if you want further elaboration! 10/10

Use Quizgecko on...
Browser
Browser