Short Java 8 Notes
Short Java 8 Notes
Example:
public class Student implements Usage:
Comparable<Student> {
[Link](list, new
int rollNo;
NameComparator());
String name;
}
[Link] = name;
✅ Key Differences:
Feature Comparable Comparator
@Override
public int compareTo(Student other) Packag [Link] [Link]
{ e
return [Link] -
[Link]; // sort by rollNo Method compareTo(Ob compare(Object
ascending ject o) o1, Object o2)
}
Used for Natural ordering Custom ordering
}
ConcurrentHashMap<String, PlayerPosition>
livePlayers = new ConcurrentHashMap<>();
✅ Use
Key Takeaways
multithreading for:
● Performance (parallel processing).
● Responsiveness (UI remains
// Thread 1: Updates player position
[Link]("Player1", new Position(x,
smooth).
y)); ● Scalability (handling multiple
clients).
// Thread 2: Reads positions for rendering
PlayerPosition pos =
[Link]("Player1");
Why Multithreading?
🔷 What is ExecutorService?
ExecutorService is part of the
● Real-time synchronization of game [Link] package and provides a
state. high-level API to manage threads.
We use:
E-Com Prevent synchronized,
ExecutorService executor =
merce overselling ReentrantLoc
inventory k [Link](5);
[Link](() ->
doSomething());
🏪
Banking Avoid AtomicIntege
(ATM) incorrect r,
balance synchronized Real-world Analogy: A
updates
Restaurant and Chefs
Imagine a restaurant (your application) that
Multipla Sync player ConcurrentHa
handles food orders (tasks). You have:
yer positions in shMap
● Waiters taking orders (main thread /
Games real-time
client requests)
● A pool of chefs (threads) who cook ExecutorService executor
the meals =
● A kitchen manager (ExecutorService) [Link](3);
who assigns orders to chefs
Runnable balanceTask = ()
Benefits:
-> {
● Chefs (threads) are reused
● No need to hire (create) and fire
(destroy) for every new order [Link]("Checking
● Smooth operation with better balance: " +
performance and scalability [Link]().getName())
🔧 Basic Syntax:
ExecutorService executor =
;
try {
[Link](2000); } catch
[Link](3); (InterruptedException e) {}
💻 Real-world Example:
Processing Customer Bank
[Link]("Transferring
money: " +
[Link]().getName())
Requests ;
try {
[Link](3000); } catch
Suppose you’re building a banking backend
system that processes various customer (InterruptedException e) {}
tasks like:
● Balance inquiry [Link]("Money
● Money transfer transferred.");
● Bill payment };
👇 Code Example:
import [Link].*;
[Link]("Paying bill:
" +
[Link]().getName())
public class BankRequestProcessor
;
{
try {
[Link](1000); } catch
public static void
(InterruptedException e) {}
main(String[] args) {
management. It improves
[Link]("Bill paid."); scalability and avoids the
}; overhead of manually creating
[Link](balanceTask); and managing threads.”
[Link](transferTask);
[Link](billPaymentTask); In an Airlines Reservation System
✅
[Link](); //
Don't forget this!
} Common Microservices in
} an Airline Project
🔍 Important Types of
Executors:
Here’s a detailed breakdown of the most
common microservices you’d design:
✅ Best Practices:
● Return available seats, prices
🧠 Interview Tip:
4. Booking Service
Handles ticket booking and cancellation.
Responsibilities:
“ExecutorService decouples ● Book flights
task submission from thread
● Confirm seat availability (via Flight
Inventory) 9. Admin Service
● Generate booking reference number Internal service for staff to manage flights,
(PNR) pricing, maintenance, etc.
● Cancel reservations Responsibilities:
✅ Why?
(Razorpay, Stripe, etc.)
● Refunds
● Transaction logs You want to ensure that only authenticated
Responsibilities:
● Send email, SMS, or push Step 2: Create JwtTokenFilter to validate
notifications incoming tokens
● Booking confirmation java
public class JwtTokenFilter extends
● Flight status updates OncePerRequestFilter {
🔒 2.
UsernamePasswordAuthenticationToken("service"
, null, new ArrayList<>());
Role-Based Access Control
[Link]().setAuthent
ication(auth); (RBAC)
} Add roles in JWT claims and verify them.
} java
CopyEdit
.antMatchers("/notify/internal/**").hasRole("
[Link](request,
INTERNAL_SERVICE")
response);
📢 3.
}
}
Service-to-Service
Step 3: Configure Spring Security
Communication Security
If other microservices (like Booking) call Notification
java
Service:
@Configuration Option A: Use JWT with a shared
@EnableWebSecurity secret between services
public class SecurityConfig extends
Generate tokens with ROLE_INTERNAL_SERVICE,
WebSecurityConfigurerAdapter {
and only trusted services can use them.
@Override Option B: Use mutual TLS (mTLS)
protected void configure(HttpSecurity Use client/server certificates to authenticate each
🕵️ 4. Audit Logging
http) throws Exception { service.
[Link]().disable()
.authorizeRequests()
Log:
.antMatchers("/notify/**").authenticated() ● Who sent the notification
.and() ● What data was sent
● When and to whom
🛡️ 5.
.sessionManagement().sessionCreationPolicy(Se
[Link]);
[Link](new
Rate Limiting & Throttling
JwtTokenFilter(),
Use tools like:
[Link]);
● Spring Bucket4j
}
● API Gateway (e.g., Kong, NGINX, Spring
Cloud Gateway)
}
🚨 6.
To prevent abuse (e.g., spamming SMS/Emails).
Step 4: Validate JWT Tokens
java Exception & Security Logging
public class JwtUtil { Log unauthorized attempts and unexpected
tokens with IP addresses.
🔁
private static final String SECRET_KEY =
"my-secret-key";
🧠 Real-World Architecture:
i++) {
Future<ValidationResult> f =
[Link](i);
1. Spring’s @Scheduled(cron = "...") is used String pnr = [Link](i);
to trigger the batch process, say, every 5
minutes. if ([Link]()) {
[Link](pnr + " —
2. Inside the scheduled method: Timed out");
} else {
○ You fetch the list of pending/impacted
PNRs (e.g., for upcoming schedule try {
changes). ValidationResult result =
[Link]();
○ You process them in parallel using [Link](pnr +
ExecutorService + Callable with " — Valid: " + [Link]);
timeout (as shown earlier). } catch (Exception e) {
✅
[Link](pnr +
" — Failed: " + [Link]());
Example: Cron + }
}
Multi-threaded Callable }
java }
import
[Link] private List<String>
eduled; fetchPnrsToValidate() {
import // Normally you query DB for pending
[Link]; schedule changes
return [Link]("OK123", "FAIL456",
import [Link].*; "LATE789");
import [Link].*; }
🔧 Setup Required
}
"departure": "Delhi",
"arrival": "Mumbai",
"duration": "2h"
1. Add @EnableScheduling in your Spring Boot
main class: }
@SpringBootApplication
@EnableScheduling
public class AirlineApp {
🔧 Built with:
public static void main(String[] args) { In Spring Boot, you create a REST API using
@RestController and @RequestMapping.
[Link]([Link],
args);
} java
} @RestController
2. Tune thread pool size as needed @RequestMapping("/api/flights")
⏰
([Link](n)). public class FlightController {
🔹 Example:
A REST API (Representational State Transfer API)
is a web service endpoint that exposes data or
functionality over HTTP.
java
WebClient client = [Link]();
Flight flight = [Link]()
.uri("[Link]
🔁 Real-World Microservices Use
Case
DEL-MUM")
.retrieve() 1. Flight Service exposes a REST
.bodyToMono([Link]) API:
.block(); // blocking call
✅ Summary of
http
GET /api/flights/DEL-MUM
Use
Mono<T>.
✅ Key Properties of
entries."
LinkedHashMap
Q)What is the purpose of the Map
Feature Description interface?
The Map interface represents a collection of
key-value pairs, providing methods for storing,
retrieving, and manipulating key-value associations.
🔹 2. Using LinkedHashSet
(Preserves Insertion Order)
Map<String, String> capitalMap = new HashMap<>(); List<String> list =
[Link]("India", "New Delhi"); [Link]("apple", "banana",
[Link]("USA", "Washington DC");
"apple", "orange");
[Link]([Link]("India"));
List<String> unique = new
Q) How does the contains() method work in ArrayList<>(new LinkedHashSet<>(list));
a Set? [Link](unique); // [apple,
banana, orange]
The contains() method checks if a specified
element exists in a Set by computing its hash ✅ Best of both worlds — removes duplicates and
preserves original order.
🔹 3. Using Java 8+ Streams
code and looking for it in the appropriate bucket.
Q)What happens when you insert a null a. Remove duplicates and collect to list:
key into a HashMap? List<String> unique = [Link]()
When you insert a null key into a HashMap, it .distinct().collect([Link]())
allows one null key, while Hashtable does not permit
;
null keys or values
Q) What is the difference between
Q) How do you convert an ArrayList to
[Link]() and [Link]()?
an array?
You can convert an ArrayList to an array using the
● [Link]() is a static
toArray () method, which can be called with or
without an array parameter. method used to sort any list
passed to it.
Q)What are the different ways to ● [Link]() is a default method
added in Java 8 to the List
traverse a List?
interface and sorts the list
You can traverse a List using a for loop,
in-place using a comparator.
enhanced for loop, Iterator, or ListIterator.
Q) How do you remove duplicates Q) How can you synchronize a List in
Java?
● A Map that maintains keys in a)Basic spring,spring boot jar files and
ascending order. dependent, relavent jar files.
● Typically implemented using b)required plugins
TreeMap. c)required Project Properties.
Q) Explain the difference between Q)How many ways are there to activate
toArray() and toArray(T[]). profiles in spring boot app?
@Bean(name =
2️ Create DataSource Configuration Class:
"secondaryEntityManagerFactory")
java public
@Configuration LocalContainerEntityManagerFactoryBean
@EnableTransactionManagement secondaryEntityManagerFactory(
public class DataSourceConfig { EntityManagerFactoryBuilder
builder,
@Primary
@Bean(name = "primaryDataSource") @Qualifier("secondaryDataSource")
@ConfigurationProperties(prefix = DataSource dataSource) {
"[Link]") return builder
public DataSource .dataSource(dataSource)
primaryDataSource() {
return .packages("[Link]")
[Link]().build();
} .persistenceUnit("secondary")
.build();
@Bean(name = "secondaryDataSource") }
@ConfigurationProperties(prefix =
"[Link]") @Primary
public DataSource @Bean(name =
secondaryDataSource() { "primaryTransactionManager")
return public PlatformTransactionManager
[Link]().build(); primaryTransactionManager(
} aryEntityManagerFactory")
@Qualifier("primEntityManagerFactory
@Primary emf) {
@Bean(name = return new
"primaryEntityManagerFactory") JpaTransactionManager(emf);
public }
LocalContainerEntityManagerFactoryBean
primaryEntityManagerFactory( @Bean(name =
"secondaryTransactionManager")
EntityManagerFactoryBuilder builder,
public PlatformTransactionManager
@Qualifier("primaryDataSource")
secondaryTransactionManager(
DataSource dataSource) {
return builder
@Qualifier("secondaryEntityManagerFactor
.dataSource(dataSource) y") EntityManagerFactory emf) {
.packages("[Link].p return new
JpaTransactionManager(emf);
rimary") } }
○ OAuth2, and more
3️⃣ Define Repositories for Each DB:
● Implementation:
Primary DB Config: ○ Via annotations like
@EnableWebSecurity and
java SecurityFilterChain (modern
@Configuration approach)
@EnableJpaRepositories( ○ Can also include custom filters and
authentication providers.
basePackages =
"[Link]",
entityManagerFactoryRef = 2️⃣ Basic Authentication
"primaryEntityManagerFactory",
● What it is: A simple method where the client
transactionManagerRef = sends a username:password
"primaryTransactionManager" Base64-encoded in every HTTP request
) header.
public class PrimaryDatabaseConfig {} ● Use case: Suitable for internal services or
development environments.
● Spring Boot Support:
Secondary DB Config: ○ Can be enabled using
java [Link]() in the security
@Configuration config.
@EnableJpaRepositories( ○ Or just use default security starter
(generates default credentials).
basePackages =
"[Link]",
entityManagerFactoryRef = 3️⃣ JWT (JSON Web Token)
"secondaryEntityManagerFactory", Authentication
transactionManagerRef =
"secondaryTransactionManager" ● What it is: Token-based stateless
authentication.
)
● How it works:
public class SecondaryDatabaseConfig {} ○ After successful login, a token is
generated and returned to the client.
Q) How many ways can we implement ○ The token is passed in the
security in Spring Boot? Authorization header for future
Answer: Spring Boot supports multiple ways to requests (Bearer <token>).
implement security depending on the ● Use case: RESTful APIs and stateless
application’s requirements. The most common applications.
methods include; ● Spring Boot Support: Custom
implementation with filters and token
validation logic using
1️⃣ Spring Security (Core Approach) OncePerRequestFilter.
@Autowired
Q) What is Spring Cloud and how does it
private MockMvc mockMvc;}
integrate with Spring Boot?
Spring Cloud provides tools to build microservices by
Q) What is @MockBean used for in Spring
offering features like service discovery (Eureka),
Boot? configuration management (Config Server), circuit
Answer: breakers (Hystrix or Resilience4J), API gateways
@MockBean is used to mock dependencies (Spring Cloud Gateway), and more. It integrates
(like services or repositories) in the Spring seamlessly with Spring Boot for distributed, resilient
application context during tests. It replaces the systems.
real bean with a mock version (typically using
Mockito).
Q) How do you use Spring Boot with Eureka public class SchedulerApp {}
for service discovery?
Add the following dependency: @Scheduled(fixedRate = 5000)
public void printTime() {
<dependency> [Link]("Running every 5
<groupId>[Link]</grou seconds");
pId> }
<artifactId>spring-cloud-starter-netflix
-eureka-client</artifactId> Q) What is the default logging framework in Spring
</dependency> Boot?
Spring Boot uses Logback as the default logging
Then, enable discovery using: framework. It can be configured using
[Link] or XML-based
@EnableDiscoveryClient [Link].
@SpringBootApplication
public class MyServiceApplication {} Q) How do you enable SSL in Spring Boot?
Configure the following properties:
Q) How to configure Spring Boot with Kafka?
Use the Spring Kafka starter dependency: properties
[Link]=8443
<dependency> [Link]-store=classpath:keystore.
<groupId>[Link]</grou jks
pId> [Link]-store-password=your-passw
<artifactId>spring-kafka</artifactId> ord
</dependency> [Link]-store-type=JKS
[Link]-alias=your-alias
Configure Kafka in [Link]:
Q) What is the purpose of @ComponentScan in
properties Spring Boot?
[Link]-servers=localhost @ComponentScan tells Spring where to look for
:9092 components, such as @Service, @Repository,
[Link]-id=my-group @Controller, etc. It's automatically included in
@SpringBootApplication, scanning the base
Q) How does Spring Boot support Docker? package and sub-packages.
Spring Boot applications can be containerized using
Docker by: Q) How to handle asynchronous processing in
Spring Boot?
● Creating a Dockerfile to define how to build Use @EnableAsync to enable async processing, and
the image. @Async to mark a method for async execution.
● Using spring-boot-maven-plugin to
build Docker images. @Configuration
This enables consistent deployment across
@EnableAsync
environments.
public class AsyncConfig {}
Q) How to schedule tasks in Spring Boot? @Service
Use @EnableScheduling on a configuration class public class MyService {
and annotate methods with @Scheduled. @Async
@EnableScheduling public CompletableFuture<String>
@SpringBootApplication processTask() {
return Q) How to implement basic authentication in
[Link]("Task Spring Boot?
completed"); Configure HTTP Basic security using:
}
@Override
}
protected void configure(HttpSecurity
Q) What is Spring Security? http) throws Exception {
Spring Security is a robust framework for securing [Link]().and().authorizeRequests
Java applications. It provides authentication, ().anyRequest().authenticated();
authorization, CSRF protection, and integrates with
various protocols (LDAP, OAuth2, JWT, etc.). Q) How to configure a message broker in Spring
Boot?
Q) How to enable Spring Security in a Spring Boot A: You can configure a message broker, such as
application? RabbitMQ or Kafka, by adding the required starter
Add the dependency: dependencies and application properties.
Example (RabbitMQ Dependency):
<dependency> <dependency>
<groupId>[Link]</group <groupId>[Link]</groupId>
<artifactId>spring-boot-starter-amqp</artifac
Id>
tId>
<artifactId>spring-boot-starter-security
</dependency>
</artifactId>
</dependency> Q) How do you send and receive messages with
RabbitMQ in Spring Boot?
Q) What is the default username and password in A: Use @RabbitListener for consuming messages
Spring Security?
and RabbitTemplate for sending messages.
The default username is user, and the password is
auto-generated at runtime and printed in the console @RabbitListener(queues = "queueName")
log. public void receiveMessage(String message) {
[Link]("Received: " + message);
Q) How to configure a custom login page in Spring
}
Security?
@Autowired
You can use the .formLogin() method in the private RabbitTemplate rabbitTemplate;
configure(HttpSecurity http) method:
public void sendMessage(String message) {
@Override [Link]("queueName",
protected void configure(HttpSecurity message);
http) throws Exception { }
[Link]().loginPage("/login").per
Q) What is Spring Kafka and how is it used in
mitAll();
Spring Boot?
}
A: Spring Kafka provides integration with Apache
Kafka, simplifying message publishing and
Q) What is method-level security in Spring consumption in Spring Boot applications.
Security? Example Dependency:
It allows restricting access at method level using
<dependency>
annotations like @PreAuthorize, @Secured.
<groupId>[Link]</grou
pId>
@PreAuthorize("hasRole('ADMIN')")
<artifactId>spring-kafka</artifactId>
public void deleteUser() {}
</dependency>
Q) How do you configure a Kafka producer and Q) How do you use Spring Cloud Eureka for
consumer in Spring Boot? service discovery?
A: Configure Kafka properties in A: Add the
[Link]. spring-cloud-starter-netflix-eureka-clie
Example: nt dependency and annotate the application with
[Link]-servers=localhost:9092 @EnableDiscoveryClient.
[Link]-id=test-group <dependency>
<groupId>[Link]</groupId>
Q) What is Reactive Programming in Spring Boot? <artifactId>spring-cloud-starter-netflix-eure
A: Reactive programming is a paradigm for handling ka-client</artifactId> </dependency>
asynchronous data streams. In Spring Boot, it's
supported by Spring WebFlux for building non-blocking Q) What is Spring Cloud Config?
applications. A: Spring Cloud Config provides centralized
configuration management for distributed systems.
Q) What is Spring WebFlux?
A: Spring WebFlux is a reactive web framework that [Link]=[Link]
enables non-blocking and asynchronous request
rver:8888
handling.
Q) How do you configure Spring Boot with Spring
Q) What are Mono and Flux in Spring WebFlux?
Cloud Config Server?
A: Mono represents 0 or 1 value; Flux represents 0
A: Use @EnableConfigServer in a Spring Boot
to N values asynchronously.
application.
Mono<String> mono = [Link]("Hello");
@SpringBootApplication
Flux<String> flux = [Link]("Hello",
@EnableConfigServer
"World");
public class ConfigServerApplication {
public static void main(String[] args) {
Q64) How to use @GetMapping in Spring
[Link](ConfigServerApplication
WebFlux?
.class, args); } }
A: Use @GetMapping in a reactive controller to return
Mono or Flux. Q) What is Spring Cloud Gateway and how is it
@RestController used with Spring Boot?
public class WebFluxController { A: It acts as an API gateway to route requests to
@GetMapping("/mono") different microservices.
public Mono<String> getMono() {
return [Link]("Hello, Reactive World!"); <dependency>
} } <groupId>[Link]</groupId>
<artifactId>spring-cloud-starter-gateway</art
Q) How do you handle exceptions in WebFlux? ifactId>
A: Use @ExceptionHandler in the controller or a </dependency>
global handler via @ControllerAdvice.
Q) How do you implement load balancing in Spring
Q) What is @ResponseStatus in WebFlux? Boot with Spring Cloud?
A: It is used to annotate methods or exceptions to A: Use Ribbon with @LoadBalanced on a
return specific HTTP status codes. RestTemplate bean.
@LoadBalanced
Q) What is Spring Cloud?
@Bean
A: Spring Cloud is a set of tools that help in building
public RestTemplate restTemplate() {
and managing microservices, offering solutions like
service discovery, config management, circuit return new RestTemplate();
breakers, load balancing, etc.
}
Q) What is validation in Spring public class UserRequest {
@Email(message = "Must be a valid
Boot and how is it supported?
email!")
A: Spring Boot supports validation private String email;
using JSR-380 (Jakarta Bean Validation, }
formerly [Link]). It enables
automatic input validation for REST API 3. @Size(min, max)
requests or form data using annotations Purpose: Validates that a string/collection
like @NotNull, @Email, @Min, etc. It has a length/size between min and max.
integrates with Spring via @Valid and Use Cases:
@Validated. ● Password length constraints.
● Limiting list/array size.
Q) What dependency is required for Example:
java
bean validation in Spring Boot? public class UserRequest {
A: You need the @Size(min = 6, max = 20, message =
spring-boot-starter-validation "Password must be 6-20 characters!")
private String password;
dependency. It brings in Hibernate
Validator, which is the reference @Size(max = 10, message = "Cannot
implementation of JSR-380. select more than 10 items!")
private List<String> preferences;
<dependency> }
<groupId>[Link]</group
Id> Other Key Annotations
<artifactId>spring-boot-starter-validati
Annot Purpose Example
on</artifactId> </dependency> ation
2. @Email
Purpose: Validates that a string is a How to Enable Validation in Spring
well-formed email address. Boot?
Use Case: 1. Add the validation starter (if not
● Email fields in registration forms. already present):
Example: <dependency>
java <groupId>[Link]</groupId>
<artifactId>spring-boot-starter-validation< Q) What is the difference between
/artifactId>
@Valid and @Validated in Spring
2. </dependency>
Boot?
3. Use @Valid in controller methods:
@PostMapping("/users")
public ResponseEntity<String> ● @Valid: Used on method parameters
createUser(@Valid @RequestBody UserRequest (e.g., in a controller) to trigger
user) { validation based on constraints.
return [Link]("Valid!"); ● @Validated: Supports validation
4. }
groups and method-level
5. Handle validation errors globally validation, typically used at
(using @ControllerAdvice): class level.
@ExceptionHandler(MethodArgumentNotValidExc
[Link])
public ResponseEntity<Map<String, String>> Example with @Valid:
handleValidationExceptions( @RestController
MethodArgumentNotValidException ex) { @RequestMapping("/users")
Map<String, String> errors = new
public class UserController {
HashMap<>();
@PostMapping
[Link]().getAllErrors().forEac public ResponseEntity<String>
h(error -> { addUser(@Valid @RequestBody User user) {
String fieldName = ((FieldError)
return [Link]("User is
error).getField();
String message = valid"); } }
[Link]();
[Link](fieldName, message); Example with @Validated:
}); @Validated
return
@Service
[Link]().body(errors); }
public class PaymentService {
@Min Annotation public void process(@Min(100) int
Purpose: Ensures a numeric value is greater amount) {
than or equal to the specified minimum. // Only processes if amount >= 100 } }
Applicable Types:
● int, long, short, BigDecimal, Q) What happens if validation fails when
BigInteger, etc. using @Valid in a controller?
Example: Age Validation A: Spring Boot will automatically
public class Employee { return a 400 Bad Request along with
@Min(value = 18, message = "Age must be validation error details in the response
at least 18!")
body.
private int age;
}
Q) How do you create a custom validator
@Max Annotation in Spring Boot?
Purpose: Ensures a numeric value is less A: Create a new annotation and its
than or equal to the specified maximum. associated validator class.
Example: Salary Validation
public class Employee { Step 1: Create the custom annotation
@Max(value = 100000, message = "Salary
@Constraint(validatedBy =
cannot exceed $100,000!")
private double salary; [Link])
} @Target({ [Link] })
@Retention([Link]) Q) What is the use of @Cacheable annotation
public @interface ValidUsername { in Spring Boot?
String message() default "Invalid A) The @Cacheable annotation marks a method's
username"; return value to be cached. If the method is called again
Class<?>[] groups() default {}; with the same parameters, the cached result is
Class<? extends Payload>[] payload() returned instead of executing the method again.
default {};
@Cacheable("products")
} public Product getProductById(Long id) {
Step 2: Implement the validator logic simulateSlowService(); // e.g., DB call
return
public class UsernameValidator [Link](id).orElse(nu
implements ll);
ConstraintValidator<ValidUsername,
String> { }
products is the cache name. On the first call, the
@Override method runs and the result is cached. Subsequent
public boolean isValid(String value, calls with the same id return the cached result.
ConstraintValidatorContext context) {
Q) What is the use of @CacheEvict
return value != null && annotation in Spring Boot?
[Link]("^[a-zA-Z0-9_]{5,20}$"); } A) The @CacheEvict annotation removes an entry
} from the cache. It's typically used when data
changes and the cache must be updated.
Step 3: Use the annotation in your model
● Add dependency:
●
🚩 Drawbacks:
locations
🔧 Internal Working:
[Link]:
pointers to the next and previous nodes.
[Link]=caffeine
[Link]=maximumSize=1
000,expireAfterAccess=5m ● It has an internal class called Node<E> with
data, next, and prev references.
● The list maintains references to the first and
Q) How do you configure Redis as a cache
last nodes.
provider in Spring Boot? ● Elements are not stored in contiguous memory,
and memory is allocated for each node
● Add dependency: separately.
<dependency> **********IMP
<groupId>[Link]</group @RestController
@RequestMapping("/api/employees")
Id>
public class EmployeeController {
<artifactId>spring-boot-starter-data-red private final List<String> employeeNames =
is</artifactId> [Link](
"John Doe","Jane Smith", "Alice Johnson",
</dependency>
"Bob Martin"};
● Configure properties:
[Link]=redis @GetMapping("/names")
[Link]=localhost public ResponseEntity<List<String>>
getEmployeeNames() {
[Link]=6379
return [Link](employeeNames); // HTTP 200
with body } }
Redis is suitable for distributed caching in
microservices environments. @PostMapping("/add")
✅ Goals }
[Link]();
}
● Synchronize access to the shared buffer. }
👷 Consumer Thread
● Prevent race conditions.
● Use wait-notify mechanism or modern
BlockingQueue.
class Consumer extends Thread {
import [Link];
import [Link]; public void run() {
class SharedBuffer {
try {
private final Queue<Integer> queue =
while (true) {
new LinkedList<>();
private final int capacity = 5; [Link]();
public synchronized void produce(int value) [Link](1000);
throws InterruptedException { }
while ([Link]() == capacity) { } catch (InterruptedException e)
wait(); // wait until not full {
} [Link](value); [Link]();
[Link]("Produced: " +
}
value);
}
notify(); // notify consumer }
}
public synchronized void consume()
throws InterruptedException {
while ([Link]()) {
🚀 Main Class
wait(); // wait until not empty } public class ProducerConsumerDemo {
int value = [Link](); public static void main(String[]
[Link]("Consumed: " + args) {
value); SharedBuffer buffer = new
notify(); // notify producer } } SharedBuffer();
✅ Output (sample) }
new Thread(consumer).start();
Produced: 0 }
Consumed: 0
Produced:
Produced:
Consumed:
1
2
1 …….
🔍 What does "statically typed"
mean?
✅ Example in Java:
import [Link].*;
❌
the compiler will throw an error.
int value = 0;
number = "Hello"; // Compile-time
try {
while (true) { error
[Link](value);
[Link]("Produced: " +
🔁 Comparison: Dynamically Typed
Languages
value++);
[Link](500); Languages like Python or JavaScript are dynamically
} typed, meaning variable types are determined at
} catch runtime, and type mismatches are only caught when
(InterruptedException e) { the code is run.
x = 10 # int
[Link]().interrupt();
x = "hello" # now a string - allowed at
}
runtime.
};
int a = 5;
String b = "test";
int result = a + b; // ❌ Compile-time
error
Even if Java allows casting, it’s explicit
and controlled, unlike weakly typed languages.