Monday, August 17, 2026

Java 8 Complete Reference

Complete tutorial with examples and interview guidance

Java 8 Complete Feature Guide

A practical, detailed guide to the release that changed modern Java development. Learn lambdas, functional interfaces, streams, Optional, the Date and Time API, CompletableFuture, collection enhancements, common mistakes, and senior-level interview questions.

Lambda ExpressionsStream APIOptionaljava.timeCompletableFutureMap API

1What Changed in Java 8?

Java 8 brought functional-style programming to Java while retaining its object-oriented foundation. The major changes include lambda expressions, method references, functional interfaces, default methods, streams, Optional, a modern Date and Time API, and asynchronous composition through CompletableFuture.

Collection dataStream pipelineResult
Important mental model: A collection stores data. A stream does not normally store data; it describes operations to perform on a source.

2Lambda Expressions

A lambda expression provides an implementation for the single abstract method of a functional interface.

(parameters) -> expression
(parameters) -> {
    statements;
}

Before Java 8

Collections.sort(employees, new Comparator<Employee>() {
    @Override
    public int compare(Employee first, Employee second) {
        return first.getName().compareTo(second.getName());
    }
});

Using a lambda

employees.sort((first, second) ->
    first.getName().compareTo(second.getName()));

Variable capture

int minimumSalary = 50_000; // Effectively final

employees.stream()
    .filter(employee -> employee.getSalary() > minimumSalary)
    .forEach(System.out::println);
A local variable captured by a lambda must be final or effectively final. Avoid modifying shared state inside lambdas, especially in parallel execution.

3Functional Interfaces

@FunctionalInterface
interface SalaryRule {
    boolean test(Employee employee);
}
InterfaceInput and outputMethodUse
Predicate<T>T to booleantest()Filtering
Function<T,R>T to Rapply()Transformation
Consumer<T>T to voidaccept()Performing an action
Supplier<T>No input to Tget()Lazy object creation
UnaryOperator<T>T to Tapply()Same-type transformation
BinaryOperator<T>T and T to Tapply()Combining values
Predicate<Employee> highPaid =
    employee -> employee.getSalary() > 100_000;

Function<Employee, String> employeeName = Employee::getName;
Consumer<Employee> printEmployee = System.out::println;
Supplier<List<Employee>> listFactory = ArrayList::new;

Predicate<Employee> highPaidITEmployee = highPaid.and(
    employee -> "IT".equals(employee.getDepartment()));
Performance tip: Primitive specializations such as IntPredicate, IntConsumer and ToIntFunction can reduce boxing and unboxing.

4Method and Constructor References

Static method

numbers.stream()
    .reduce(Integer::sum);

Bound instance method

employees.forEach(
    System.out::println);

Unbound instance method

employees.stream()
    .map(Employee::getName);

Constructor reference

Supplier<List<Employee>> factory =
    ArrayList::new;
A method reference is shortened lambda syntax. Use it when it makes the intention clearer, not simply because it is shorter.

5Default and Static Interface Methods

interface Auditable {

    default String auditMessage() {
        return "Audited at " + Instant.now();
    }

    static boolean isValid(String value) {
        return value != null && !value.trim().isEmpty();
    }
}

Conflict-resolution rules

  1. A concrete class method wins over an interface default method.
  2. A method from a more specific child interface wins over its parent interface.
  3. If unrelated interfaces declare conflicting defaults, the implementing class must override the method.
interface A {
    default void print() { System.out.println("A"); }
}

interface B {
    default void print() { System.out.println("B"); }
}

class Example implements A, B {
    @Override
    public void print() {
        A.super.print();
    }
}

6Stream API Deep Dive

SourceIntermediate operationsTerminal operation
List<String> names = employees.stream()
    .filter(employee -> employee.getSalary() > 80_000)
    .sorted(Comparator.comparing(Employee::getSalary).reversed())
    .map(Employee::getName)
    .collect(Collectors.toList());

Stateless

filter, map and flatMap process elements independently.

Stateful

distinct and sorted may retain information about previously seen elements.

Terminal

collect, reduce, count, match, find and forEach trigger execution.

map() versus flatMap()

List<String> uniqueSkills = employees.stream()
    .flatMap(employee -> employee.getSkills().stream())
    .map(String::toUpperCase)
    .distinct()
    .sorted()
    .collect(Collectors.toList());

reduce()

double totalSalary = employees.stream()
    .map(Employee::getSalary)
    .reduce(0.0, Double::sum);

int total = IntStream.rangeClosed(1, 100).sum();

Short-circuit operations

boolean anyHighPaidEmployee = employees.stream()
    .anyMatch(employee -> employee.getSalary() > 200_000);

Optional<Employee> firstITEmployee = employees.stream()
    .filter(employee -> "IT".equals(employee.getDepartment()))
    .findFirst();
Lazy execution: Intermediate operations do not run until a terminal operation requests results. Short-circuiting can prevent the entire source from being processed.

7Collectors and Employee Examples

Group by department

Map<String, List<Employee>> byDepartment =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment));

Count per department

Map<String, Long> countByDepartment =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.counting()));

Maximum salary employee

Map<String, Optional<Employee>> highestPaid =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.maxBy(Comparator.comparing(
            Employee::getSalary))));

Average salary

Map<String, Double> averageSalary =
    employees.stream().collect(Collectors.groupingBy(
        Employee::getDepartment,
        Collectors.averagingDouble(
            Employee::getSalary)));

Third-highest distinct salary, department-wise

employees.stream()
    .collect(Collectors.groupingBy(Employee::getDepartment))
    .forEach((department, employeeList) -> {

        Double salary = employeeList.stream()
            .map(Employee::getSalary)
            .distinct()
            .sorted(Comparator.reverseOrder())
            .skip(2)
            .findFirst()
            .orElse(null);

        System.out.println(department + " -> " + salary);
    });

Why distinct? The third-highest salary normally means the third distinct salary. Duplicate salary values should share the same rank.

toMap() with duplicate-key handling

Map<String, Employee> employeeByName = employees.stream()
    .collect(Collectors.toMap(
        Employee::getName,
        Function.identity(),
        BinaryOperator.maxBy(
            Comparator.comparing(Employee::getSalary))));
When two elements produce the same map key, toMap() requires a merge function. Without it, a duplicate-key exception is thrown.

8Parallel Streams and Spliterator

double totalSalary = employees.parallelStream()
    .mapToDouble(Employee::getSalary)
    .sum();

Consider parallel streams when

  • The dataset is large and in memory.
  • Work is CPU-intensive and independent.
  • The source can be split efficiently.
  • Reduction is associative.

Avoid them when

  • Operations perform blocking I/O.
  • The collection is small.
  • Shared mutable state is involved.
  • Ordering costs dominate.
  • Common-pool contention is risky.

Spliterator supports both traversal and partitioning. Characteristics such as ORDERED, DISTINCT, SORTED, SIZED and SUBSIZED help the stream framework understand a data source.

Interview point: Parallel does not automatically mean faster. Benchmark using realistic data and workload.

9Optional

Optional<Employee> employeeOptional = repository.findById(id);

String name = employeeOptional
    .filter(employee -> employee.getSalary() > 50_000)
    .map(Employee::getName)
    .orElse("Unknown");

orElse()

value.orElse(createDefault());
// createDefault() is called eagerly

orElseGet()

value.orElseGet(this::createDefault);
// Supplier runs only when empty

Flatten nested Optional values

Optional<String> city = employeeOptional
    .flatMap(Employee::getAddress)
    .map(Address::getCity);
Use Optional mainly as a return type. Avoid calling get() without checking, and generally avoid Optional fields, parameters and collections of Optional.

10Modern Date and Time API

TypePurpose
LocalDateDate without time or zone
LocalTimeTime without date or zone
LocalDateTimeDate and time without a zone
InstantA point on the UTC timeline
ZonedDateTimeDate and time with a region-based zone
OffsetDateTimeDate and time with a numeric UTC offset
PeriodDate-based amount
DurationTime-based amount
LocalDate joiningDate = LocalDate.of(2020, Month.JANUARY, 15);
long years = ChronoUnit.YEARS.between(
    joiningDate, LocalDate.now());

DateTimeFormatter formatter =
    DateTimeFormatter.ofPattern("dd-MM-yyyy");
String formattedDate = joiningDate.format(formatter);

Instant currentInstant = Instant.now();
ZonedDateTime indiaTime = currentInstant.atZone(
    ZoneId.of("Asia/Kolkata"));
The central java.time classes are immutable and thread-safe. LocalDateTime is not a global timestamp because it contains no time-zone or offset information.

11CompletableFuture

CompletableFuture<Employee> employeeFuture =
    CompletableFuture.supplyAsync(
        () -> loadEmployee(id), executor);

CompletableFuture<String> result = employeeFuture
    .thenApply(Employee::getName)
    .exceptionally(exception -> "Unknown");

Combine independent calls

CompletableFuture<Profile> profileFuture =
    CompletableFuture.supplyAsync(this::loadProfile, executor);

CompletableFuture<Salary> salaryFuture =
    CompletableFuture.supplyAsync(this::loadSalary, executor);

CompletableFuture<EmployeeView> viewFuture =
    profileFuture.thenCombine(
        salaryFuture, EmployeeView::new);
MethodPurpose
thenApply()Transform a completed result
thenCompose()Chain and flatten a dependent future
thenCombine()Combine two independent results
allOf() / anyOf()Coordinate multiple futures
handle()Process either a result or exception
exceptionally()Recover from a failure
In server applications, use a suitably configured executor. Blocking the shared common pool can affect unrelated operations.

12Collection, Map and Comparator Improvements

Collection operations

employees.forEach(System.out::println);
employees.removeIf(employee -> !employee.isActive());
employees.replaceAll(this::normalize);

Map operations

employeeMap.forEach((id, employee) ->
    System.out.println(employee));

Employee employee = employeeMap.getOrDefault(id, defaultEmployee);
employeeMap.putIfAbsent(id, newEmployee);

departmentEmployees
    .computeIfAbsent(department, key -> new ArrayList<>())
    .add(employee);

wordCount.merge(word, 1, Integer::sum);

Put Map values into another list

List<Employee> employeeList =
    new ArrayList<>(employeeMap.values());

Comparator composition

Comparator<Employee> employeeComparator =
    Comparator.comparing(Employee::getDepartment)
        .thenComparing(
            Employee::getSalary,
            Comparator.reverseOrder())
        .thenComparing(
            Employee::getName,
            Comparator.nullsLast(
                String.CASE_INSENSITIVE_ORDER));

HashSet.add() return value

Set<Integer> seen = new HashSet<>();

numbers.stream()
    .filter(number -> !seen.add(number))
    .forEach(System.out::println);

HashSet.add() returns true when the element is inserted and false when an equal element already exists. Therefore, !seen.add(number) selects duplicates.

13Other Important Java 8 Features

Base64

String encoded = Base64.getEncoder()
    .encodeToString("Java 8".getBytes(
        StandardCharsets.UTF_8));

String decoded = new String(
    Base64.getDecoder().decode(encoded),
    StandardCharsets.UTF_8);

StringJoiner

StringJoiner joiner =
    new StringJoiner(", ", "[", "]");

joiner.add("Java").add("Spring");

Repeatable annotations

@Repeatable(Roles.class)
@interface Role { String value(); }

@interface Roles { Role[] value(); }

@Role("ADMIN")
@Role("AUDITOR")
class UserService {}

Files.lines()

try (Stream<String> lines =
         Files.lines(logFilePath)) {

    long errors = lines
        .filter(line -> line.contains("ERROR"))
        .count();
}
  • Metaspace: Native-memory Metaspace replaced PermGen for class metadata.
  • Target-type inference: Generic type inference was improved in more invocation contexts.
  • Parameter names: Reflection can read parameter names when compiled using -parameters.
  • Concurrency: Java 8 added classes such as StampedLock, LongAdder and LongAccumulator.
  • Nashorn: Java 8 included a JavaScript engine, but it should not be chosen for modern application designs.

14Common Java 8 Mistakes

Reusing a stream

A stream is consumed after a terminal operation and cannot be reused.

Shared mutation

Avoid updating external mutable collections from a stream pipeline.

Optional.get()

Prefer map, flatMap, orElseGet or orElseThrow.

Assuming null safety

Streams do not make null elements or mappers automatically safe.

Incorrect time type

Do not use LocalDateTime when you need a global timestamp.

Blind parallelization

Measure before using parallel streams and avoid blocking calls.

15Java 8 Interview Questions

Why can a functional interface contain default and static methods?

The single-abstract-method rule counts abstract instance methods. Default and static methods already have implementations.

What is the difference between a collection and a stream?

A collection stores elements and supports repeated traversal. A stream is a consumable, normally lazy computation pipeline using internal iteration.

What is the difference between map() and flatMap()?

map() transforms each input into one result. flatMap() transforms inputs into streams and flattens those streams into one pipeline.

Why must reduce operations be associative?

Parallel execution can combine partitions in different groupings. Associativity ensures those groupings produce the same result.

findFirst() versus findAny()?

findFirst() respects encounter order. findAny() allows more freedom and may be useful when any matching result is acceptable.

orElse() versus orElseGet()?

orElse() evaluates its argument eagerly. orElseGet() invokes its supplier only when the Optional is empty.

thenApply() versus thenCompose()?

thenApply() maps a value to another value. thenCompose() chains a function that returns a future and flattens the nested future.

Why can parallelStream() be risky in a web application?

It commonly uses the shared ForkJoin common pool. Blocking work, request concurrency, small tasks and ordering requirements can create unpredictable performance.

What is the difference between intermediate and terminal stream operations?

Intermediate operations return another stream and are normally lazy. Terminal operations produce a result or side effect and trigger execution.

What happens when toMap() receives duplicate keys?

It throws an exception unless a merge function is supplied to decide how duplicate values should be combined or selected.

Java 8 Complete Guide
Save this post for revision and practice each example with your own Employee data.

Saturday, July 13, 2024

Java Unit Test MCQ

 Question 1


Which framework is most commonly used for unit testing in Java?


JUnit  

TestNG  

Mockito  

Selenium

Answer:  


JUnit



Question 2

In JUnit 5, which annotation is used to indicate a test method?


@TestCase  

@RunWith  

@Test  

@Before

Answer:  


@Test



Question 3

Which JUnit annotation is used to execute some code before each test method?


@BeforeAll  

@After  

@BeforeEach  

@BeforeTest

Answer:  


@BeforeEach



Question 4

Which method in JUnit is used to check if two objects are equal?


assertSame  

assertTrue  

assertEquals  

assertNotNull

Answer:  


assertEquals



Question 5

Which of the following is a mocking framework often used in Java unit tests?


TestNG  

Mockito  

JUnit  

Cucumber

Answer:  


Mockito



Question 6

In Mockito, which method is used to create a mock object?


mock()  

createMock()  

mockObject()  

newMock()

Answer:  


mock()



Question 7

What does the @Mock annotation do in Mockito?


It creates a real object  

It creates a mock object  

It verifies a method call  

It initializes a mock object

Answer:  


It creates a mock object



Question 8

Which JUnit annotation is used to run a piece of code after all tests in the test class have been run?


@AfterEach  

@AfterAll  

@AfterTest  

@After

Answer:  


@AfterAll



Question 9

In TestNG, which annotation is equivalent to JUnit's @BeforeEach?


@BeforeTest  

@BeforeMethod  

@BeforeClass  

@BeforeSuite

Answer:  


@BeforeMethod



Question 10

Which Mockito method is used to verify that a method was called with specific arguments?


verify()  

check()  

assert()  

confirm()

Answer:  


verify()



Question 11

In JUnit 5, which annotation is used to disable a test method?


@Ignore  

@Disabled  

@Skip  

@Deactivate

Answer:  


@Disabled



Question 12

Which of the following is not a lifecycle method in JUnit 5?


@BeforeEach  

@AfterEach  

@BeforeClass  

@BeforeAll

Answer:  


@BeforeClass



Question 13

Which of the following assertions is used to check if a condition is false in JUnit?


assertTrue()  

assertFalse()  

assertNull()  

assertNotNull()

Answer:  


assertFalse()



Question 14

What is the primary purpose of unit testing?


To test the entire application as a whole  

To test individual units or components in isolation  

To test the user interface  

To test the performance of the application

Answer:  


To test individual units or components in isolation



Question 15

In Mockito, which method is used to return a specific value when a method is called?


when().thenReturn()  

doReturn().when()  

mock().thenReturn()  

verify().thenReturn()

Answer:  


when().thenReturn()



Question 16

Which JUnit annotation is used to provide a timeout for a test method?


@Timeout  

@Test(timeout = 1000)  

@TimeLimit  

@Test(timeout = 1)

Answer:  


@Timeout



Question 17

Which of the following is not a valid JUnit assertion?


assertEquals()  

assertNotNull()  

assertThrows()  

assertEmpty()

Answer:  


assertEmpty()



Question 18

Which JUnit 5 annotation is used to run a test multiple times?


@Repeat  

@RepeatedTest  

@LoopTest  

@TestRepeat

Answer:  


@RepeatedTest



Question 19

In TestNG, which annotation is used to indicate that a method should be executed before any test methods in the current class?


@BeforeTest  

@BeforeClass  

@BeforeMethod  

@BeforeSuite

Answer:  


@BeforeClass



Question 20

In Mockito, how can you mock a method to throw an exception?


when(methodCall).thenThrow(new Exception())  

doThrow(new Exception()).when(methodCall)  

throwException(new Exception()).when(methodCall)  

when(methodCall).throw(new Exception())

Answer:  


when(methodCall).thenThrow(new Exception())

Friday, July 12, 2024

Create a function that checks the connection status and reconnects if necessary

 const redis = require('redis');

const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { client.quit(); client.connect((err) => { if (err) { console.error('Failed to reconnect to Redis:', err); reject(err); } else { console.log('Reconnected to Redis'); resolve(); } }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });


  1. Use the following code to check the connection and reconnect if necessary:

const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { try { const pong = await pingAsync(); if (pong === 'PONG') { console.log('Redis connection is healthy'); } else { console.log('Unexpected response from Redis:', pong); await reconnect(); } } catch (err) { console.error('Redis connection error:', err); await reconnect(); } } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { // Quit the current client client.quit(() => { // Create a new client instance const newClient = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client newClient.on('connect', () => { console.log('Reconnected to Redis'); resolve(newClient); }); newClient.on('error', (err) => { console.error('Failed to reconnect to Redis:', err); reject(err); }); // Replace the old client with the new client client = newClient; }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });




++++++++++++++++++++++++++++++++++++++++++++++++++++ 3. With timeout
const redis = require('redis'); const { promisify } = require('util'); // Create a Redis client with a connection timeout (in milliseconds) let client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `ping` method to check connection const pingAsync = promisify(client.ping).bind(client); // Function to check if connection is available and reconnect if not async function ensureConnection() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Connection check timed out')); }, 5000); // 5 seconds timeout for the connection check pingAsync().then(pong => { clearTimeout(timeout); if (pong === 'PONG') { console.log('Redis connection is healthy'); resolve(); } else { console.log('Unexpected response from Redis:', pong); reconnect().then(resolve).catch(reject); } }).catch(err => { clearTimeout(timeout); console.error('Redis connection error:', err); reconnect().then(resolve).catch(reject); }); }); } // Function to reconnect to Redis async function reconnect() { return new Promise((resolve, reject) => { const timeout = setTimeout(() => { reject(new Error('Reconnection timed out')); }, 10000); // 10 seconds timeout for reconnection // Quit the current client client.quit(() => { // Create a new client instance client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Handle connection events for the new client client.on('connect', () => { clearTimeout(timeout); console.log('Reconnected to Redis'); resolve(); }); client.on('error', (err) => { clearTimeout(timeout); console.error('Failed to reconnect to Redis:', err); reject(err); }); }); }); } // Example usage: Check connection and reconnect if necessary ensureConnection() .then(() => { console.log('Connection check complete'); }) .catch(err => { console.error('Error during connection check:', err); }); // Close the connection gracefully on process exit process.on('exit', () => { client.quit(); }); client.on('error', (err) => { console.error('Redis error:', err); });

FlushDB in Redis in node js

 const express = require('express');

const redis = require('redis'); const { promisify } = require('util'); const app = express(); const PORT = 3000; // Replace with your desired port // Create a Redis client with a connection timeout (in milliseconds) const client = redis.createClient({ host: '127.0.0.1', // Replace with your Redis server host port: 6379, // Replace with your Redis server port if different from default connect_timeout: 10000 // 10 seconds timeout }); // Promisify the `flushdb` method const flushdbAsync = promisify(client.flushdb).bind(client); // Function to flush the Redis database async function flushRedisDatabase() { try { const result = await flushdbAsync(); return { message: 'Database flushed successfully', result }; } catch (err) { console.error('Error flushing database:', err); throw err; } } // REST endpoint to flush the Redis database app.post('/flushdb', async (req, res) => { try { const response = await flushRedisDatabase(); res.status(200).json(response); } catch (err) { res.status(500).json({ error: 'Error flushing database', details: err.message }); } }); // Start the Express server app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); }); // Additional Redis client event handlers for better debugging client.on('connect', () => { console.log('Connected to Redis'); }); client.on('error', (err) => { console.error('Redis error:', err); }); client.on('ready', () => { console.log('Redis client ready'); }); client.on('reconnecting', () => { console.log('Reconnecting to Redis...'); }); client.on('end', () => { console.log('Redis connection closed'); });


Wednesday, July 10, 2024

Redis connection in node js

 import redis from 'redis';

// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { // options.error contains the error object returned by the last attempt to connect if (options.error && options.error.code === 'ECONNREFUSED') { // If the connection was refused by the server, log the error and stop retrying console.error('The server refused the connection'); return new Error('The server refused the connection'); } // options.total_retry_time is the total time (in milliseconds) that the client has been trying to reconnect if (options.total_retry_time > 1000 * 60 * 60) { // If the total retry time exceeds 1 hour, log the error and stop retrying console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } // options.attempt is the number of retry attempts so far if (options.attempt > 10) { // If the number of retry attempts exceeds 10, log the error and stop retrying console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time, which increases with each attempt // options.attempt * 100 gives a delay that increases by 100ms with each attempt // Math.min ensures the delay does not exceed 3000ms (3 seconds) return Math.min(options.attempt * 100, 3000); } }); // Event listener for successful connection client.on('connect', function() { console.log('Redis client connected'); }); // Event listener for errors client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;

Redis connection in node js

 import redis from 'redis';

// Create a Redis client with retry strategy const client = redis.createClient({ host: 'localhost', // Replace with your Redis server host port: 6379, // Replace with your Redis server port retry_strategy: function (options) { if (options.error && options.error.code === 'ECONNREFUSED') { // End reconnecting on a specific error and flush all commands with a individual error console.error('The server refused the connection'); return new Error('The server refused the connection'); } if (options.total_retry_time > 1000 * 60 * 60) { // End reconnecting after a specific timeout and flush all commands with a individual error console.error('Retry time exhausted'); return new Error('Retry time exhausted'); } if (options.attempt > 10) { // End reconnecting with built in error console.error('Too many retry attempts'); return undefined; } // Reconnect after a specific time return Math.min(options.attempt * 100, 3000); } }); client.on('connect', function() { console.log('Redis client connected'); }); client.on('error', function (err) { console.error('Something went wrong ' + err); }); export default client;

Thursday, June 13, 2024

Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws

Clear cache || FlushDB || Clear Redis Cache ||Node js ||aws 



const express = require('express');

const redis = require('redis'); const app = express(); const port = 3000; // Replace with your actual hostname and port const client = redis.createClient({ host: 'your-elasticache-hostname', port: your-elasticache-port }); client.on('error', (err) => { console.log("Error " + err); }); app.get('/flushall', (req, res) => { client.flushdb((err, succeeded) => { if (err) { res.status(500).send({ error: 'Failed to flush Redis cache' }); } else { res.send({ message: 'Redis cache successfully flushed' }); } }); }); app.listen(port, () => { console.log(`App running on port ${port}`); });

===============================
Method 2: with lamda 

const Redis = require('ioredis'); exports.handler = async (event, context) => { const redis = new Redis({ host: 'YOUR_REDIS_HOST', // replace with your host port: YOUR_REDIS_PORT, // replace with your port password: 'YOUR_REDIS_PASSWORD', // replace with your password (if any) db: 0, }); try { // Ping Redis to check connection const ping = await redis.ping(); console.log('Ping:', ping); // Clear all keys await redis.flushdb(); console.log('Cache cleared'); return { statusCode: 200, body: 'Cache cleared' }; } catch (error) { console.log('Error:', error); return { statusCode: 500, body: 'Error clearing cache' }; } finally { // Disconnect from Redis await redis.quit(); } };

=============================================
Methos 3: with redis dependency: const redis = require('redis'); exports.handler = async (event, context) => { return new Promise((resolve, reject) => { const client = redis.createClient({ host: 'YOUR_REDIS_HOST', // replace with your host port: YOUR_REDIS_PORT, // replace with your port password: 'YOUR_REDIS_PASSWORD', // replace with your password (if any) db: 0, }); client.on('connect', function() { console.log('Connected to Redis'); client.flushdb(function (err, succeeded) { if (err) { console.error('Error:', err); reject({ statusCode: 500, body: 'Error clearing cache' }); } else { console.log('Cache cleared'); resolve({ statusCode: 200, body: 'Cache cleared' }); } // Disconnect from Redis client.quit(); }); }); client.on('error', function (err) { console.error('Error:', err); reject({ statusCode: 500, body: 'Error clearing cache' }); }); }); };

Sunday, May 19, 2024

Calculate your Age

Calculate Age Age Calculator

Age Calculator

Friday, February 16, 2024

what is meant by --max-request-journal-entries and --no-request-journal in wiremock configuration

max-request-journal-entries and no-request-journal in wiremock configuration


In WireMock, the request journal is a built-in feature that keeps a record of incoming requests and their corresponding responses. It can be helpful for debugging and analysis purposes.


--max-request-journal-entries is an option that allows you to set a limit on the number of requests that the request journal stores. When this limit is reached, older requests will be removed from the journal to make room for new ones. By setting this option, you can control the memory usage of the request journal.


For example, using --max-request-journal-entries=10000 will limit the request journal to store a maximum of 10,000 requests.


--no-request-journal is an option that disables the request journal entirely. When this option is used, WireMock will not store any requests or responses in the request journal. Disabling the request journal can help reduce memory consumption and improve performance, especially during load testing or in production environments where request logging is not necessary.


In summary:


--max-request-journal-entries: Sets a limit on the number of requests stored in the request journal.

--no-request-journal: Disables the request journal completely.

Thursday, January 18, 2024

Sort an array of 0s, 1s and 2s | Dutch National Flag problem

Sort an array of 0s, 1s and 2s |

Dutch National Flag problem


👀👀👀👀👀


/*

* This program defines a sortArray() method that sorts

* an array of 0s, 1s, and 2s using

* the Dutch National Flag algorithm.

*/


public class Sort012 {


public static void swap(int[] arr,int i,int j) {

int temp;

temp=arr[i];

arr[i]=arr[j];

arr[j]=temp;

}

public static void sortArray(int[] arr) {

int low =0;

int mid =0;

int high =arr.length-1;

while(mid<=high) {

switch (arr[mid]) {

case 0:

swap(arr,low,mid);

low++;

mid++;

break;

case 1:

mid++;

break;

case 2:

swap(arr,mid,high);

high--;

break;

default:

break;

}

}

}


public static void main(String... aa) {

int arr[]= {2,0,1,0,2,1,2,0,1,0,2,1};

sortArray(arr);

for(int i:arr) {

System.out.print(i+" ");

}

}

}


Output:

0 0 0 0 1 1 1 1 2 2 2 2



Wednesday, January 17, 2024

Merge two sorted linked lists


Merge two sorted linked lists


public class MergeLinkedLists {

static class ListNode {

int val;

ListNode next;

public ListNode() {}


public ListNode(int val) {

this.val = val;

}


public ListNode(int val, ListNode next) {

this.val = val;

this.next = next;

}

}

public static ListNode mergeTwoLists(ListNode list1, ListNode list2) {

ListNode mergedList = new ListNode();

ListNode current = mergedList;


while (list1 != null && list2 != null) {

if (list1.val <= list2.val) {

current.next = list1;

list1 = list1.next;

} else {

current.next = list2;

list2 = list2.next;

}

current = current.next;

}


if (list1 != null) {

current.next = list1;

} else {

current.next = list2;

}


return mergedList.next;

}


public static void main(String[] args) {

// Example usage:

ListNode list1 = new ListNode(1, new ListNode(2, new ListNode(4)));

ListNode list2 = new ListNode(1, new ListNode(3, new ListNode(4)));


ListNode mergedList = mergeTwoLists(list1, list2);

while (mergedList != null) {

System.out.print(mergedList.val + " ");

mergedList = mergedList.next;

}

}

}


Time Complexity: O(M + N), Where M and N are the size of the list1 and list2 respectively.
Auxiliary Space: O(M+N), Function call stack space


Output:


1 1 2 3 4 4


Geeks link:

    Merge To Linked List


Create a Digital Clock using HTML and JavaScript

Create a Digital Clock using HTML and JavaScript  <! DOCTYPE html> < html > < head > ...

Followers

Search This Blog

Popular Posts