Core Java:
- OOP principles (SOLID, DRY, KISS)
- Difference between stack & heap memory
- Explain about JRE & Class Loader Subsystem
- Difference between Interface & Abstract Class
- Can you create instance of abstract class?
No, you can not create instance of abstract class in Java, they are incomplete. Even though, if your abstract class don’t contain any abstract method, you can not create instance of it. By making a class abstract, you told compiler that, it’s incomplete and should not be instantiated. Java compiler will throw error, when a code tries to instantiate abstract class. - Implementing two interfaces with two default methods of the same signature in Java 8
I1.super().defaultMethod(); - String pooling
- Custom Immutable Class
- String Vs String Buffer Vs String BuilderThe main difference between the three most commonly used String classes as follows.1. String Buffer and StringBuilder objects are mutable whereas String class objects are immutable.2. String Buffer class implementation is synchronized while StringBuilder class is not synchronized.3. Concatenation operator "+" is internally implemented by Java using either String Buffer or StringBuilder.Criteria to choose among String, String Buffer and StringBuilder4. If the Object value will not change in a scenario use String Class because a String object is immutable.5. If the Object value can change and will only be modified from a single thread, use a StringBuilder because StringBuilder is unsynchronized (means faster).6. If the Object value may change, and can be modified by multiple threads, use a String Buffer because String Buffer is thread safe(synchronized).
- Contract between equals and hash code
- Comparator and Comparable with program
- Serialize concept
- Synchronize concepts
- Custom Exception class creation (Checked & UnChecked)
- Difference between ClassNotFoundExcepiton Vs NoClassDefinitonFoundError
- Object class methods
- Difference types of Garbage collectors
- Final, finally and finalize()
- Recursion
- Java 8, Java 11, Java 15, Java 17(Sealed/Switch Evolution) and Java 22 features with examples
- Functional Interface implementations (Consumer, Supplier, Function, Predicate, Bifunction with Realtime use cases)
- Default method, static method usages in Functional Interfaces
- Difference between Streams Vs Collections
- Streams Intermediate and terminal operations.
- Streams Map Vs Flat Map
- Lambdas, Optional (diff between of, ofNullable, orElse, orElseGet, orElseThrow, isPresent)
- Is-A vs Has-A Relationships.
- Composition Vs Aggregation.
- State vs stateless
- Java Reflection API
- Exception handling
- If thread is distroyed, then can we restart the same thread.
Calling start() on a thread that has already been started and finished will result in a java.lang.IllegalThreadStateException.
Reactive Programming
- Project Reactor, RxJava
- Event-driven architecture, backpressure
- Reactive streams, non-blocking IO
Garbage Collection (G1, CMS, ZGC)
- JVM heap and stack management
- Profiling tools (JProfiler, VisualVM)
- Analyzing memory leaks, thread dumps, and heap dumps
Classloaders and Reflection
- Custom class loaders
- Dynamic class loading
- Reflection for runtime behavior manipulation
Threads:
- Thread Vs Runnable Vs Processor
- How Threads communicating each other using wait, notify, notifyAll
- Difference between sleep vs wait vs join vs yield, including when and why you would use one vs. the other.
- sleep vs wait, notify, notifyall explained ... > join method
- How to create Custom Thread Pool
- What is Race Condition (Mutual Exclusion, Synchronization)
- What is the difference between Runnable and Callable
- What is Thread Local Storage
- What is the ThreadLocal class? How and why would you use it?
- Volatile & Atomic classes
- What is Future & Executors
- Fork/Join framework
- What is the difference between Executors Vs Completable Future.
- Difference between SupplyAysnc , RunAsync
- How to execute parallel, sequence and merge completable future
- How can we execute threads in sequence and parallel using Executors.
- Understanding of race conditions, deadlocks, and thread pools
- Difference between Submit & Execute
- Semaphore & CountDownLatch (How to limit the no of threads execution on a method)
- Difference between Synchronized method vs Synchronized block
- Difference between Static locking & instance method locking
- What is ReadWrite Lock? Does ConcurrentHashMap uses ReadWrite Lock?
- How do you avoid deadlock while coding?
- How do find if your program has deadlock?
- User threads and daemon threads.
User threads are high-priority threads.The JVM will wait for any user thread to complete its task before terminating it.
Daemon threads are low-priority threads whose only role is to provide services to user threads.
Daemon threads are used for background supporting tasks and are only needed while normal threads are executing. eg: GC thread is a daemon thread.
Collections:
- List Vs Set Vs Map [order, internal DS, complexity, initial size and load factor]
- Difference between Array List & LinkedList with complexity and use case, underlying DS & initial size, load factor
- Difference between HashSet & LinkedHashSet with complexity and use case, underlying DS & initial size, load factor
- Difference between HashTable & HashMap with complexity and use case, underlying DS & initial size, load factor
- Fail-fast Vs Fail-safe
- Difference between HashMap & Concurrent HashMap, how both internally works.
- How does ConcurrentHashMap achieves it's scalability?
- Difference between Vector & Stack
- Concurrency implementation classes like CopyOnWriteArrayList, ConcurrencyHashMap
- Double LinkedList Circular problem.
- Explain HashMap/ConcurrentHashMap with LRU Cache.
- How HashMap internally works when hash collision happens like put and get operation (LinkedList, post java 8 BalancedTree).
- How to store different objects in TreeSet and sorting based on ID (Ex: Employee & Student & Customer)
- Difference between Comparator & Comparable interfaces
- How to add Student object as key in the HashMap (we have to implement object uniqueness using hash code & equals)
- How to prevent duplicates in the Array List (adding list to set & override the add method of Array List)
Spring / SpringBoot / Restful / FeignClient / WebClient:
- Restful http methods implementation and usages, status codes (1xx,2xx,3xx,4xx,5xx)
- Difference between Controller and RestController
- Difference between Spring and Spring Boot
- @SpringBootApplication (@componentscan , @configuration, @Enableautoconfiguration)
- Stereotype Annotations
- Difference between @Component and @Service and @Repository
- @Autowired, @Qualifier , @Primary, @Bean,@Value, @Profile and all anotations usages
- Spring Scopes, what will happen when we inject @singleTon bean into prototype Vice versa.
- Spring different types of DI's (constructor, setter, Field)
- Difference between IOC & DI
- Difference between Class and Bean
- Dependency Injection Pattern, which is quite popular in Spring Framework
- Spring Bean Life CycleBean life cycle is managed by the spring container. When we run the program then, first of all, the spring container gets started. After that, the container creates the instance of a bean as per the request, and then dependencies are injected. And finally, the bean is destroyed when the spring container is closed. Therefore, if we want to execute some code on the bean instantiation and just after closing the spring container, then we can write that code inside the custom init() method and the destroy() method.
- PostConstruct vs PreConstruct usecase
- How to handle the excepitons in Spring(@ControllerAdvice,@Excepitonhandler)
- Stateful Vs Stateless
- Idempotent methods
- Difference between PathVaraible, RequestParam (defaultValue, how to pass addtional parameters what will happen)
- GraphQL / QueryDSL usages and how can we implement
- Difference between Restful , FiegnClient and WebClient
- How to call external api from Restful , FiegnClient and WebClient
- ResponseEntity as a Return Type different implementations in Restful
- How to Achieve the Pagination
- How to implement the Versioing
- How to implement the Cache
- Difference between Filters & Interceptors
- Difference between SpringBoot 2.7 & 3.0
- InMemory Cache in SpringBoot
- Spirng AOP
- Spring Transactions (ACID principles, Propagations, Isolation levels)
- Propagation Required, RequriedNew, Mandatory, NESTED, Support realtime usecases
- Microservice 12 factor Design Principles
- Spring JPA, native queries implementation and calling the function , procedure
- Difference between CURDRepository, PagingAndSortingRepository , JPARepository methods
- Performance of Native SQL query and JPA
- Hibernate Vs JPA
- JPA Identity Generators and how to implement custom ID generator
- JPA how to implement Interceptors
- How to handle the exception without having service layer in repository.
- Spring Security (Authentication Vs Authorization) [WebSecurityConfigurerAdapter and configure overload methods internal implementation)
- Spring Security 3.0 changes like SecurityFilterChain, UserDetails, PasswordEncoder, AuthenticationManager, HttpRequest,requestMatchers.
- JWT, OAUTH2.0
- Swagger and OpenAPI
- How to exclude EmbededTomcat and add JettyServer or UnderTow.
- How to handle bulk requests in single rest endpoint(tomcat levels threads configuration, connection pool)
- Spring actuator and profiling (health check,matrix,loggers) and (configuration and annotations)
- Spring Cache using redis,elastic search or any other cache
- How to handle logging in spring boot distributed micro services(ELK,ZIppkin,Splunk,Datadog,Cloudwatch) (root level and package level logging)
- How to integrate ELK or Splunk in spring boot application.
- How we can implemention security in micro service archture.
- How to handle transactions in distributed micro servcies(saga design pattern).
- How to handle data consistance in micro service.
- How many ways one micro service to another micro service communication.
- Spring Cloud Config.
- JPA @EmbededID and @Embedable
- JPA eager loading vs lazy loading.
- Service discovery (Eureka, Consul)
- Why do we need circuit breaker in microservices?Use of the Circuit Breaker pattern can allow a microservice to continue operating when a related service fails, preventing the failure from cascading and giving the failing service time to recover.
The circuit breaker allows microservices to communicate as usual and monitor the number of failures occurring within the defined time period. If the failure count exceeds the specified threshold value, the circuit breaker will move to the Open state. If not, it will reset the failure count and timeout period.
Design patterns
- Which design patterns have you used?
- Design Patterns (Creational, Structural and Behavioral)
- Saga design pattern (different types of Orchestration and chrograph).
- CQRS design pattern
- Eureka and service registry, discovery.
- Circuit breaker (Historyic and resilience, fault tolerance). how internal will work
- Micro services service per DB and all service single DB.
- If using Eureka one micro service to another micro service how internal flow work (service1 to eureka server to service 2) and exceptions.
- Load balancing and gateway (configuration and routing in detailed) and different types of gateway and load balancers
- Micro service vertical and horizontal scaling.
- Custom Singleton Implementation & break that using Reflection
- Singleton with double locking
- How to implement Custom Factory Method
CI/CD :
- Difference in Maven build and maven deploy,package,install( maven build life cycle)
- What is git cherypick commit.
- What is difference git pull and fetch.
- How to create jenkins pipline stages and pipeline file.
- Use of git web hook.
- Create jenkins pipeline for AWS deployment in (EC2,ECS,EKS,Lamda)
- How to take branch name dynamically in jenkins.
- What is jenkins secreat store.
- How to create multi branch jenkins pipeline
- Why we need interal depency repository.
- How we can resolve code conflicts.
- What is git rebase
- How to create Jenkins multi pipeline.
Docker/Kubernetes:
- What is docker file and configuration for spring boot application docker file.
- What is docker compose and docker swarm
- Docker commands build,logs,services,pull,push images,descirption.
- What is docker image and what it contains.
- How to upload and pull image in ECR and Dockerhub
- What is advantage and usage of docker.
- Kubernetes architecture and components(POD,Master node,cluster,ReplcaSet,Service,Vault,ingress,kubelet,kubeproxy,configMap)
- Kubernetes Deployment vs Service
- Kubernetes get pods,nodes,describe,clusters,service,logs.
- How do you check the logs in kubernates using command.
- How do you configure kubernetes load balancing and gateway.
- Kubernetes advantages
- How to restrict IP's using Kubernetes.
- Jenkins pipeline using docker and kubernetes.
Testing:
- BDD using cucumber and Jbehave.
- TDD using Junit, mockito, powerMockito, SpringBootTest, TestNG. [All Annotations].
- Spring Boot Web Flux test cases
- Spring Integration Test cases
- Mock Vs Stub
- Inject, spy
- Write test case for void method.
AWS:
- Lambda Pros / Cons [ColdStart Latency].
- Step function
- How many ways we can invoke a lambda
- SQS VS SNS
- S3 usage and different types of data encryption S3.
- Can create same bucket name with different regions.
- how to integrate spring boot with lamda.
- What is ECS and how to deploy micro services and configuration steps each (Cluster creation,service creation,Task defination,Domains,VPN network)
- How to configure VPN inbound and outbound ECS.
- What is EC2 and how to deploy spring boot micro service (pros and cons)
- Difference in Fargate and EC2.
- What is Fargate
- AWS RDS and ECR configuration.
- Usages of EKS and difference Kubernates.
- Difference in Dynamo DB and MonogoDb (with index creation).
- Different types of AWS gateways and Load Balancers.
- Subnet and VPN configuration for IP restrictions one server to another server.
- Difference Cloudwatch and cloudtrail.
- How to integrate spring boot with cloudwatch.
- What is IAM rules.
- What is Elastic bean stack.
- AWS cli commands for ECS, EC2.
Database:
- ACID principles, CAP theorem
- Example on group by and having
- Difference between where and having.
- Joins
- UNION vs UNIONALL vs UNION_BYNAME
- rownumber, rank and dense_rank
- Database Shard's
- How to optimize long running query.
- Create views (normal view and materialized view), function and procedure.
- With clause, sub queries, merge query.
- Indexing (kinds of indexing..), foreign key, composite key, primary key.
- How do you prevent SQL Injection in Java Code?
- This question is more asked to Java EE developers than core Java developers but still a good question to know, PreparedStatement is the way to go. PreparedStatement not only provides better performance but also shield from SQL Injection attack. If you are working more on Java EE or J2EE side, than you should also be familiar with other security issues including Session Fixation attack or Cross Site Scripting attack and how to resolve them.
- Optimistic vs Pessimistic
- ORM principles, entity relationships
- Sql query to join two tables with left join
- Select Nth highest salary (example 2nd highest salary).SELECT DISTINCT value FROM TableORDER BY value DESCLIMIT 2But if you must select the second value using SQL, how about:SELECT MIN(value)FROM ( SELECT DISTINCT value FROM Table
ORDER BY value DESC
LIMIT 2
) AS t
Kafka:
- What is Kafka and architecture?
- What is Kafka Schema?
- Kafka Cluster Mirroring?
- Kafka producer ACKS, linger.ms,batch.size?
- How to avoid duplicates sending from producer (idempotent.true)?
- Kafka producer partitioning (RoundRobin,Key based, Custom Key)?
- Kafka Consumer message filtering?
- Kafka Consumer offset commit/rollback/seek?
- Kafka Consumer retry mechanism from reading dead letter topic?
- Kafka flow and use cases
- Broker and leader brokers
- kafka consumers group and consumers rebalencing and use case
- Explain the kafka flow and use case in your project
- Consumer lag issues and how you resolved
- Kafka zookeeper
Tools:
- Kong Gateway
- zuul, Apigee, reverse proxy.
Performance Tuning & Optimization
- JVM tuning, garbage collection optimization
- Experience in analyzing performance issues using tools like JMeter, Virtual VM and identifying root cause to fix.
-Tools for profiling and monitoring (Prometheus, Grafana)
======================================================
Interview with master card
- Spring boot test cases, asked me to explained repository mock example
- Asked me to tell flow of controller example.
- Spring boot request flow
- What is microservices how will you develop , I explained 12 factor app.
- Spring scopes
- @bean,
- @component
- Bean life cycle Bean injection
- Autowired and two bean same name @qualifier
- Project request flow> Project details
- Project technologies
- Rest full all, Mappings POST VS PUT VS PATCH,
- PUT explain with one example and expected me to tell if record is not avail in db
- Transactional management
- Joins in table one to one one to many with example
- Java 8 > Given list of string ask me to display if letter > 5 \
- Given list of string ask me to throw RunTimeException if string contains " " space
- Abstract class vs InterfaceThreadsThread Life cycleIf thread is distroyed, then can we restart the same thread. Calling
start()
on a thread that has already been started and finished will result in ajava.lang.IllegalThreadStateException
.Thread ScheduleSpringSQLjoinstable, views, matViewsVulnarebilitiesKafka related questionsSpring data vs Hibernate vs JDBCBeanscopesHash MapKafkaschema in kafkacontract between producer / consumer in kafka or restbackward, forward compatibilitySyncronized MethodHashmap vs concurrentHashMap
Interview with TELUS Internation:
- How many ways to create objects in java
- System.out.println means
- Thread runnable usage
- Array vs Arrays (Sort, min max....etc)
- Spring boot actuators use case
- Spring boot request flow
- Spring request flow, expected resolvers perspective
- Ways to do request mapping & get mapping
- Lamda expressions
- Hibernate session factory
- heapdump /shutdown spring actuators
Interview with Wells fargo:
- spring boot annontations
- api to api call
- LDAP and spring security and application security
- MongoDB aggregations
- Micro services Uses
- tell me about your project
- About AGILE
- How to write rest api
- APIGEE gate way configuration
Interview American bank:
1) > how to get empname from Mongodb db.employees.find({ name: "John Doe" }, { name: 1 })
> cascading types: ALL render all from parend to child all operation
> @requestBody
1> conditional interface > A java.util.concurrent.locks.Condition interface provides a thread ability to suspend its execution, until the given condition is true.
A Condition object is necessarily bound to a Lock and to be obtained using the newCondition() method.
await(). await(milliseconds) , signal(), SignalAll()
4> @configuration properties
5> @value
6> diff bw Mock Bean vs Mock
8> runnable vs callble
In summary, Runnable is used for tasks that don't return a value, while Callable is used for tasks that return a result. Additionally, Callable allows for checked exceptions, and the result can be obtained through a Future object.
9> finally return will dominate try method
10> put vs POST request how do you form a request
11> rest anonattion explain each
12> person have age , >16, 16< java 1.8
13> API server, api gate way
14> AOP related question
What is ZUUL in microservices?
Zuul Server is an API Gateway application. It handles all the requests and performs the dynamic routing of microservice applications. It works as a front door for all the requests. It is also known as Edge Server. Zuul is built to enable dynamic routing, monitoring, resiliency, and security.
Here are four key points to differentiate NoSQL databases from SQL (relational) databases:
Data Model:
SQL databases use a structured, tabular data model with predefined schemas. Data is organized into tables with rows and columns, and relationships between tables are established using primary and foreign keys.
NoSQL databases use a variety of data models, including key-value, document, columnar, and graph. These models provide flexibility in handling unstructured and semi-structured data, allowing for schemaless designs and dynamic data structures.
Scalability and Performance:
SQL databases are typically vertically scalable, meaning they scale by adding more resources (e.g., CPU, RAM) to a single server. They excel in handling complex queries and maintaining data integrity.
NoSQL databases are designed for horizontal scalability, allowing them to distribute data across multiple servers or clusters. They can handle high volumes of read/write operations and provide excellent performance for large-scale applications and big data scenarios.
Query Language:
SQL databases use Structured Query Language (SQL) to define and manipulate data. SQL provides a standardized syntax for querying and modifying relational data. It offers powerful features like joins, aggregations, and transaction management.
NoSQL databases often have their own query languages or APIs specific to the chosen data model. Examples include MongoDB's query language, Cassandra Query Language (CQL), and Amazon DynamoDB's API. These languages may have a simpler syntax optimized for their specific data model.
Data Consistency and Transactions:
SQL databases emphasize data consistency, enforcing strict ACID (Atomicity, Consistency, Isolation, Durability) properties. Transactions ensure that data modifications occur atomically and maintain the database in a consistent state.
NoSQL databases prioritize availability and partition tolerance, as defined in the CAP theorem. They often sacrifice strict consistency in favor of eventual consistency or offer tunable consistency models. Transactions may be supported to some extent, but with more relaxed isolation guarantees.
SQL databases are relational, and NoSQL databases are non-relational.
SQL databases use structured query language (SQL) and have a predefined schema. NoSQL databases have dynamic schemas for unstructured data.
SQL databases are vertically scalable, while NoSQL databases are horizontally scalable.
SQL databases are table-based, while NoSQL databases are document, key-value, graph, or wide-column stores.
SQL databases are better for multi-row transactions, while NoSQL is better for unstructured data like documents or JSON.
1) > how to get empname from Mongodb
db.employeeCollection.find({condition based render},{roll:1, _id: 0});
db.users.insert({
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin",
"address": [
{
"building": "22 A, Indiana Apt",
"pincode": 123456,
"city": "Los Angeles",
"state": "California"
},
{
"building": "170 A, Acropolis Apt",
"pincode": 456789,
"city": "Chicago",
"state": "Illinois"
}
]
}
})
This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as −
>db.users.findOne({"name":"Tom Benzamin"},{"address":1})
Note that in the above query, db and users are the database and collection respectively.
The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance.
Modeling Referenced Relationships
This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document's id field.
{
"_id":ObjectId("52ffc33cd85242f436000001"),
"contact": "987654321",
"dob": "01-01-1991",
"name": "Tom Benzamin",
"address_ids": [
ObjectId("52ffc4a5d85242602e000000"),
ObjectId("52ffc4a5d85242602e000001")
]
}
As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection.
>var result = db.users.findOne({"name":"Tom Benzamin"},{"address_ids":1})
>var addresses = db.address.find({"_id":{"$in":result["address_ids"]}})
>>>>>>>>>>>>>>>>>>>>>>>>>>>>
@Document("groceryitems")
public class GroceryItem {
@Id
private String id;
private String name;
private int quantity;
private String category;
public GroceryItem(String id, String name, int quantity, String category) {
//initiate constructore variable
}
}
public interface ItemRepository extends MongoRepository<GroceryItem, String> {
@Query("{name:'?0'}")
GroceryItem findItemByName(String name);
@Query(value="{category:'?0'}", fields="{'name' : 1, 'quantity' : 1}")
List<GroceryItem> findAll(String category);
public long count();
}
application.props
spring.data.mongodb.uri=mongodb+srv://<username>:<pwd>@<cluster>.mongodb.net/mygrocerylist
spring.data.mongodb.database=mygrocerylist
@SpringBootApplication
@EnableMongoRepositories
public class MdbSpringBootApplication implements CommandLineRunner{
@Autowired
ItemRepository groceryItemRepo;
public static void main(String[] args) {
SpringApplication.run(MdbSpringBootApplication.class, args);
}
MongoTemplate>>> used for update queries Query query = Query.createQuery(Criteria.where("name").is(name));
Update update = new Update(0;
update.set(quantity,new quatity)
>>>UPDATE query
@Component
public class CustomItemRepositoryImpl implements CustomItemRepository {
@Autowired
MongoTemplate mongoTemplate;
public void updateItemQuantity(String name, float newQuantity) {
Query query = new Query(Criteria.where("name").is(name));
Update update = new Update();
update.set("quantity", newQuantity);
UpdateResult result = mongoTemplate.updateFirst(query, update, GroceryItem.class);
if(result == null)
System.out.println("No documents updated");
else
System.out.println(result.getModifiedCount() + " document(s) updated..");
}
}
𝗟𝗼𝗮𝗱 𝗕𝗮𝗹𝗮𝗻𝗰𝗲𝗿 𝘃𝘀. 𝗥𝗲𝘃𝗲𝗿𝘀𝗲 𝗣𝗿𝗼𝘅𝘆 𝘃𝘀. 𝗔𝗣𝗜 𝗚𝗮𝘁𝗲𝘄𝗮𝘆
What are the differences between a load balancer, a reverse proxy, and an API gateway?
All three are used to optimize and manage web traffic. However, they vary in their function and use cases:
A 𝗹𝗼𝗮𝗱 𝗯𝗮𝗹𝗮𝗻𝗰𝗲𝗿 is a device that distributes incoming network traffic across multiple servers. The goal is to ensure that no single server is overwhelmed with traffic, which can lead to slow response times or even downtime. Load balancers are ideal for high-traffic websites or applications that need to handle a large volume of requests.
A 𝗿𝗲𝘃𝗲𝗿𝘀𝗲 𝗽𝗿𝗼𝘅𝘆, on the other hand, is a server that sits between the client and the webserver. The reverse proxy intercepts requests from clients and forwards them to the appropriate server. The reverse proxy can also cache frequently requested content, which can help improve performance and reduce server load. Reverse proxies are ideal for websites or applications that need to handle a large number of concurrent connections.
An 𝗔𝗣𝗜 𝗴𝗮𝘁𝗲𝘄𝗮𝘆 is a server that acts as an intermediary between clients and backend servers. The API gateway is responsible for managing API requests, enforcing security policies, and handling authentication and authorization. API gateways are ideal for microservices architectures, where multiple services need to be accessed through a single API.
Ref
1. 𝗟𝗼𝗮𝗱 𝗕𝗮𝗹𝗮𝗻𝗰𝗲𝗿 𝘃𝘀. 𝗥𝗲𝘃𝗲𝗿𝘀𝗲 𝗣𝗿𝗼𝘅𝘆 𝘃𝘀. 𝗔𝗣𝗜 𝗚𝗮𝘁𝗲𝘄𝗮𝘆: 𝗗𝗲𝗺𝘆𝘀𝘁𝗶𝗳𝘆𝗶𝗻𝗴 𝗪𝗲𝗯 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁𝘂𝗿𝗲𝘀: https://lnkd.in/gfzyT42k
2. 𝗚𝗿𝗼𝗸𝗸𝗶𝗻𝗴 𝗦𝘆𝘀𝘁𝗲𝗺 𝗗𝗲𝘀𝗶𝗴𝗻 𝗙𝘂𝗻𝗱𝗮𝗺𝗲𝗻𝘁𝗮𝗹𝘀: https://lnkd.in/gtcCT-dJ
====>
Top 10 Microservices Patterns Every Developer Should Know -
Why are Patterns in Software Development Important?
✅ They provide a shared language for developers, boosting communication and collaboration.
✅ They enhance software quality and security, helping to dodge common vulnerabilities.
✅ They accelerate development and boost software's scalability and flexibility.
𝗧𝗼𝗽 𝗠𝗶𝗰𝗿𝗼𝘀𝗲𝗿𝘃𝗶𝗰𝗲𝘀 𝗣𝗮𝘁𝘁𝗲𝗿𝗻𝘀 :
𝗔𝗣𝗜 𝗚𝗮𝘁𝗲𝘄𝗮𝘆 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Acts as the traffic controller for all incoming requests, routing them to the appropriate service.
𝗦𝗲𝗿𝘃𝗶𝗰𝗲 𝗠𝗲𝘀𝗵 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Orchestrates inter-service communication, managing load balancing, service discovery, and security.
𝗕𝘂𝗹𝗸𝗵𝗲𝗮𝗱 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Isolates each service in a separate "compartment" for failure resilience.
𝗖𝗶𝗿𝗰𝘂𝗶𝘁 𝗕𝗿𝗲𝗮𝗸𝗲𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Prevents system-wide failures by halting requests to a failing or unresponsive service.
𝗘𝘃𝗲𝗻𝘁-𝗗𝗿𝗶𝘃𝗲𝗻 𝗔𝗿𝗰𝗵𝗶𝘁𝗲𝗰𝘁𝘂𝗿𝗲 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Facilitates communication between services through event publishing and subscribing.
𝗦𝗶𝗱𝗲𝗰𝗮𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Deploys an auxiliary "sidecar" service alongside each microservice to handle tasks like logging, monitoring, and security.
𝗦𝘁𝗿𝗮𝗻𝗴𝗹𝗲𝗿 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Gradually replaces a monolithic application with microservices.
𝗦𝗲𝗿𝘃𝗶𝗰𝗲 𝗥𝗲𝗴𝗶𝘀𝘁𝗿𝘆 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Acts as a phonebook for microservices, facilitating inter-service communication.
𝗦𝗮𝗴𝗮 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Manages transactions spanning multiple services by breaking them into steps and providing compensating actions if something goes wrong.
🔟 𝗖𝗤𝗥𝗦 𝗣𝗮𝘁𝘁𝗲𝗿𝗻: Separates the read and write operations for data, allowing independent optimization and scaling.
import java.util.*;
import java.lang.*;
import java.io.*;
// The main method must be in a class named "Main".
class Main {
public static void main(String[] args) {
System.out.println("Hello world!");
// The main method must be in a class named "Main".
//Afghanistan
//Albania
//Algeria
//Andorra
//Angola
//Antigua and Barbuda
//Argentina
//Armenia
//Australia
//Austria
//Azerbaijan
//please create a collection with all the above countries
//then iterate over them
//if you find any countrie that has more than 5 letters, print the name
//if you find a space character, throw an run time exception
List list = Arrays.asList("Afghanistan","alb","Algeria", "Antigua and Barbuda", "Argentina", "Armenia");
//list.stream().filter((str)-> str.length() > 5).forEach(System.out::println);
int count = list.stream().anyMatch((str) -> str.contains(" "));
if( count > 1) {
throw new RuntimeException();
}
}
}
//Minimal operations
/*
you are given an array of size N the only operation that you are allowed to perform on the array is to swap two elements.
your task is to find the minimun number of operations needed to put this array into ascending order.
Input
the first line of input contains an integer N representing the number of elements of the array rr[]
the second line of input consists of N space-separated values of the array ar[]
Constrains:
1<= N <=100
1<=a[i] <=1000
note:Bruce force solutions will timeout on large test cases hence optional solution is required.
input
4
6 4 2 1
out put :2
5
1 5 4 3 2
output:2
*
* */;
public static int minSwaps(int[] nums)
{
int len = nums.length;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < len; i++)
map.put(nums[i], i);
Arrays.sort(nums);
// To keep track of visited elements. Initialize
// all elements as not visited or false.
boolean[] visited = new boolean[len];
Arrays.fill(visited, false);
// Initialize result
int ans = 0;
for (int i = 0; i < len; i++) {
// already swapped and corrected or
// already present at correct pos
if (visited[i] || map.get(nums[i]) == i)
continue;
int j = i, cycle_size = 0;
while (!visited[j]) {
visited[j] = true;
// move to next node
j = map.get(nums[j]);
cycle_size++;
}
// Update answer by adding current cycle.
if (cycle_size > 0) {
ans += (cycle_size - 1);
}
}
return ans;
}
2nd Program:
Question 1)
import java.util.HashSet;
import java.util.Set;
public class Game {
public static void main(String[] args) {
int N = 25;
int[] A = {22, 10, 12, 10, 23, 21, 12, 17, 24, 18, 22, 15, 23, 18, 18, 19, 13, 18, 19, 12, 16, 19, 14, 16, 15};
System.out.println(calculatePossibleWinners(N, A)); // Output should be 23
int N1 = 6;
int[] A1 = {5,2,2,3,6,6};
System.out.println(calculatePossibleWinners(N1, A1));
int N2 = 2;
int[] A2 = {1,1};
System.out.println(calculatePossibleWinners(N2, A2));
}
public static int calculatePossibleWinners(int N, int[] A) {
// Find the minimum energy in the array
int minEnergy = Integer.MAX_VALUE;
for (int energy : A) {
if (energy < minEnergy) {
minEnergy = energy;
}
}
// Count how many friends have the minimum energy
int minEnergyCount = 0;
for (int energy : A) {
if (energy == minEnergy) {
minEnergyCount++;
}
}
// Calculate the total number of possible winners
int possibleWinners = N - minEnergyCount;
return possibleWinners;
}
}
import java.util.Arrays;
import java.util.List;
public class ParkingSelection {
public static String findClosestAvailableBasement(List<Integer> carCounts, List<Integer> distances) {
int numBasements = carCounts.size(); // Assuming both lists are of the same size
int[] capacities = {100, 200, 300, 500}; // Capacities of basements B1, B2, B3, B4
// Initialize the minimum distance and the corresponding basement
int minDistance = Integer.MAX_VALUE;
String closestBasement = "Exit";
// Check each basement to find the closest available spot
for (int i = 0; i < numBasements; i++) {
int availableSpots = capacities[i] - carCounts.get(i);
if (availableSpots > 0 && distances.get(i) < minDistance) {
minDistance = distances.get(i);
closestBasement = "B" + (i + 1);
}
}
return closestBasement;
}
public static void main(String[] args) {
List<Integer> carCounts = Arrays.asList(100, 50, 40, 40); // Example car counts
List<Integer> distances = Arrays.asList(5, 6, 5, 7); // Example distances
// Find and print the closest available basement
String result = findClosestAvailableBasement(carCounts, distances);
System.out.println(result);
carCounts = Arrays.asList(100, 200, 300, 500); // Example car counts
distances = Arrays.asList(5, 6, 8,3); // Example distances
// Find and print the closest available basement
result = findClosestAvailableBasement(carCounts, distances);
System.out.println(result);
}
}
Program 3:
public class MinimumCostEqualWires {
public static void main(String[] args) {
//Scanner scanner = new Scanner(System.in);
// Read the value of N
int N = 6;
// Read the array A[i]
//int[] A = new int[]{2,3,1,4,5};
// int[] A = new int[]{2,3,1,5,2};
int[] A = new int[]{1,4,7,8,2,3};
Arrays.sort(A);
int median;
if (N % 2 == 0) {
median = A[N / 2 - 1];
} else {
median = A[N / 2];
}
int cost = 0;
for (int i = 0; i < N; i++) {
cost += Math.abs(A[i] - median);
}
// Print the minimum cost
System.out.println(cost);
// scanner.close();
}
}
Next Problem:
public class HighestScoringString {
public static void main(String[] args) {
String[] strings = {"abc", "def", "abcd"};
String highestScoringString = getHighestScoringString(strings);
System.out.println("Highest Scoring String: " + highestScoringString);
}
public static String getHighestScoringString(String[] strings) {
String highestScoringString = "";
int highestScore = 0;
for (String s : strings) {
int score = getStringScore(s);
if (score > highestScore) {
highestScore = score;
highestScoringString = s;
}
}
return highestScoringString;
}
private static int getStringScore(String s) {
int score = 0;
for (char c : s.toCharArray()) {
score += (c - 'a' + 1);
}
return score;
}
}
How to Design an Application – High-Level Overview & Key Factors
Designing an application requires a structured approach, ensuring scalability, security, performance, and maintainability. Below is a high-level step-by-step guide along with the key factors to consider.
1. Understanding Business Requirements
- Define the core objectives of the application.
- Identify stakeholders and their expectations.
- Gather functional & non-functional requirements (e.g., performance, security, scalability).
- Decide on user roles and permissions.
2. Choosing the Right Architecture
- Monolithic vs. Microservices
- Monolithic: Suitable for small applications with simple logic.
- Microservices: Best for large-scale applications with independent services.
- Layered Architecture (3-tier or N-tier)
- Presentation Layer (UI - Angular, React)
- Business Logic Layer (Spring Boot, Node.js)
- Data Layer (MySQL, PostgreSQL, MongoDB)
- Event-Driven Architecture using Kafka or RabbitMQ for async processing.
- Serverless Architecture for cost-efficient and scalable applications (AWS Lambda, GCP Functions).
3. Technology Stack Selection
- Frontend: Angular, React, Redux, TypeScript
- Backend: Java 17, Spring Boot 3.x, Node.js
- Databases: PostgreSQL, MySQL, MongoDB, Redis (for caching)
- Messaging System: Apache Kafka, RabbitMQ
- Security: OAuth2, SAML, JWT, 3DS2.2
- Cloud Services: AWS (EC2, S3, RDS, Lambda), GCP
- DevOps & CI/CD: Docker, Kubernetes, Jenkins, GitLab, Terraform
4. Application Design Principles
- Scalability:
- Horizontal scaling with load balancers (HAProxy, Apache Proxy Server, Spring Gateway).
- Stateless microservices with autoscaling.
- Performance Optimization:
- Caching mechanisms (Redis, Memcached).
- Database indexing and query optimization.
- Security:
- Use HTTPS, OAuth2, SAML for authentication.
- Implement Role-Based Access Control (RBAC).
- Resilience & Fault Tolerance:
- Implement circuit breaker patterns (Resilience4j).
- Ensure disaster recovery with data replication.
5. API Design & Integration
- RESTful API / GraphQL
- API Gateway (Spring Cloud Gateway, Kong, Apigee) for security & throttling.
- Rate Limiting & Logging (ELK Stack: Elasticsearch, Logstash, Kibana).
6. Deployment & Monitoring
- Containerization:
- Dockerize the application for consistency across environments.
- Orchestration & Scaling:
- Deploy using Kubernetes (K8s) on AWS EKS / GKE / OpenShift.
- Monitoring & Logging:
- Use Prometheus & Grafana for performance monitoring.
- Centralized logging with ELK Stack.
Conclusion
By following this structured approach, an application can be designed with scalability, security, and performance in mind while ensuring ease of maintenance. 🚀
No comments:
Post a Comment