Java.Multithreading.What about synchronization and multithreading issues in servlet container ? Do we have smth right out of the box ?

🧵 Servlets Are Multithreaded by Default

When multiple clients send requests to the same servlet, the servlet container creates a new thread for each request, but only one instance of the servlet is created and shared across threads.

⚠️ This means:

If your servlet has shared mutable state, you can run into race conditions, data corruption, and thread-safety issues.


🛑 Example of a Thread Safety Issue

public class CounterServlet extends HttpServlet {
    private int counter = 0;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
        counter++; // 💣 Race condition!
        res.getWriter().write("Counter: " + counter);
    }
}

This servlet is not thread-safe. Multiple requests can corrupt the counter variable.

✅ How to Make It Thread-Safe

1. Use Local Variables (Preferred)

Local variables are stored on the thread’s stack, so each thread gets its own copy.

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    int localCounter = 0;
    localCounter++; // Safe
    res.getWriter().write("Local Counter: " + localCounter);
}

2. Synchronize Access

If you must use shared state, synchronize access:

private int counter = 0;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    synchronized (this) {
        counter++;
        res.getWriter().write("Counter: " + counter);
    }
}

But this can lead to bottlenecks — only one thread at a time enters the block.

3. Use Concurrent Utilities

Java gives you thread-safe classes out of the box:

private final AtomicInteger counter = new AtomicInteger();

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    int current = counter.incrementAndGet();
    res.getWriter().write("Counter: " + current);
}

Or use:

  • ConcurrentHashMap
  • CopyOnWriteArrayList
  • ReentrantLock (more control than synchronized)
  • ThreadLocal (for per-thread data)

🔒 Servlet Container Itself Ensures:

  • Each request runs in its own thread
  • Only one servlet instance per declaration
  • ServletContext and ServletConfig are shared objects — be careful!

❌ Not Thread-Safe by Default:

  • Instance variables in servlets
  • Shared objects like lists or maps without synchronization

✅ Thread-Safe by Default:

  • Local variables inside doGet() / doPost()
  • Immutable objects (String, Integer, etc.)
  • ThreadLocal for per-request storage

🧠 Summary

FeatureThread-Safe?Notes
Local variables✅Best choice
Instance variables (mutable)❌Use synchronized or Atomic types
ServletContext, HttpSession❌Be careful when storing mutable data
Java concurrent utils✅Use Atomic*, ConcurrentHashMap, etc.
ThreadLocal✅Great for request-specific data
Posted in Без рубрики | Comments Off on Java.Multithreading.What about synchronization and multithreading issues in servlet container ? Do we have smth right out of the box ?

Java.Servlet.How does a servlet container manage the servlet life cycle, when and what methods are called?

🔥 Let’s explore how a servlet container manages the servlet lifecycle step by step — including when and what methods are called.

🌀 Servlet Life Cycle Overview

The servlet container (like Tomcat or Jetty) controls the life of a servlet. It goes through three main phases:

1. Loading & Instantiation
2. Initialization (init)
3. Request Handling (service → doGet/doPost)
4. Destruction (destroy)

📦 1. Loading & Instantiation

  • When: The first time the servlet is requested, or at startup if load-on-startup is set in web.xml.
  • What: The container loads the servlet class and creates a single instance.
public class MyServlet extends HttpServlet {
    // Constructor is optional
    public MyServlet() {
        super();
        System.out.println("Constructor: Servlet instance created");
    }
}

Servlet container ensures only one instance per servlet — it’s multithreaded!

⚙️ 2. Initialization – init()

  • When: Called once after instantiation
  • What: Initializes the servlet — great place to read config params, set up DB connections, etc.
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    System.out.println("init(): Called once after servlet instantiation");
}

Only called once per servlet lifecycle.

🔁 3. Request Handling – service()

  • When: Every time a request is made to the servlet (e.g., from browser or REST client)
  • What: The container spawns a new thread and calls the service() method.
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    res.getWriter().write("Hello from doGet!");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {
    res.getWriter().write("Hello from doPost!");
}

The service() method routes to doGet(), doPost(), doPut(), etc., based on the HTTP method.

❌ 4. Destruction – destroy()

  • When: When the server is shutting down or the servlet is being undeployed.
  • What: Cleans up resources (e.g., closing DB connections, stopping threads).
@Override
public void destroy() {
    System.out.println("destroy(): Called once before servlet is removed");
}

Only called once — time to release heavy resources.

🚀 Summary Flowchart

   +------------------+
   | Class Loaded     |
   +------------------+
           ↓
   +------------------+
   | new MyServlet()  |
   +------------------+
           ↓
   +------------------+
   | init()           |
   +------------------+
           ↓
   +-------------------------------+
   | service() → doGet()/doPost() |
   +-------------------------------+
           ↓  (many times!)
   +------------------+
   | destroy()        |
   +------------------+

🧠 Pro Tips

  • Thread-safety: Because multiple requests are handled by threads on a single servlet instance, make sure shared data is synchronized.
  • init() vs constructor: Prefer init() for any config logic — container has more control here.
  • destroy() cleanup: Essential for avoiding memory leaks.
Posted in Без рубрики | Comments Off on Java.Servlet.How does a servlet container manage the servlet life cycle, when and what methods are called?

Java.Servlet.Why do we need application servers if we have servlet containers?

Yes — servlet containers like Tomcat can run web applications… so why do we need application servers like WildFly, GlassFish, or Payara?

Let’s break it down:

Continue reading →
Posted in Без рубрики | Comments Off on Java.Servlet.Why do we need application servers if we have servlet containers?

Java.Servlet.What is a “servlet container”?

A servlet container (also known as a servlet engine) is a part of a web server or application server that manages and executes Java servlets.


🔧 In simple terms:

A servlet container is the runtime environment for servlets — it:

  • Loads servlet classes
  • Manages their lifecycle (init, service, destroy)
  • Handles HTTP requests/responses
  • Manages threading, resource pooling, session tracking, etc.

🧠 Think of it like:

🧊 JVM runs Java classes
🧱 Servlet container runs servlet classes inside a web app

💼 Common Servlet Containers

Servlet ContainerDescription
Apache TomcatMost popular standalone servlet container
JettyLightweight, embeddable container
GlassFishFull Java EE server (includes servlet engine)
WildFly (JBoss)Java EE server (servlets + more)
UndertowLightweight, async servlet engine (used by WildFly)

🔄 Servlet Lifecycle (Managed by Container)

1. Class loading ➜
2. init()        ➜
3. service()     ➜ (runs on each request)
4. destroy()

The container ensures:

  • One servlet class instance (singleton)
  • Multiple threads for concurrent requests
  • Clean up after lifecycle ends

📦 Example in Tomcat:

  • You deploy a .war (Web Archive)
  • Tomcat loads your servlet and maps it to a URL like /login
  • When a request hits /login, Tomcat passes it to your servlet’s doGet() or doPost()

🚀 Features a servlet container provides:

  • HTTP request/response handling
  • URL-to-servlet mapping
  • Session management
  • Security (authentication, authorization)
  • Multithreading
  • Resource management (connection pools, caching)
Posted in Без рубрики | Comments Off on Java.Servlet.What is a “servlet container”?

Java.Servlets.What is the structure of a web project?

The structure of a web project depends on the tech stack you’re using (Java/Spring, Node.js, React, etc.), but in general, most web projects follow a modular structure with separation of concerns.

Here’s a common structure for a full-stack Java-based web project using Servlets or Spring Boot:


🏗️ General Web Project Structure

/my-web-app
│
├── src/                    # Source code
│   ├── main/
│   │   ├── java/           # Java source files
│   │   │   └── com/myapp/  # Your package
│   │   │       ├── controller/
│   │   │       ├── service/
│   │   │       ├── repository/
│   │   │       └── model/
│   │   └── resources/
│   │       ├── application.properties
│   │       ├── static/     # Static files (CSS, JS, images)
│   │       └── templates/  # HTML, JSP, Thymeleaf, etc.
│   └── test/               # Unit and integration tests
│
├── pom.xml or build.gradle # Project build configuration
├── README.md               # Project documentation
└── .gitignore              # Git ignore rules

🧩 Breakdown by Role

✅ controller/

  • Contains servlets or controllers (e.g., Spring @RestController)
  • Handles HTTP requests and sends responses

✅ service/

  • Business logic layer
  • Communicates between controller and repository

✅ repository/

  • Data access layer
  • Talks to database using JDBC, JPA, etc.

✅ model/

  • POJOs (Plain Old Java Objects)
  • Represents data (like User, Product, etc.)

✅ static/

  • Frontend assets like CSS, JavaScript, images

✅ templates/

  • View templates (JSP, Thymeleaf, Freemarker)

✅ application.properties

  • Configuration (e.g., port, DB connection)

🌐 Frontend Structure (React, Angular, etc.)

If you’re building the frontend separately, it may look like:

/frontend
├── public/
├── src/
│   ├── components/
│   ├── pages/
│   ├── App.tsx or App.js
│   └── index.tsx or index.js
├── package.json
└── tsconfig.json / babel.config.js

🧪 Test Directories

  • src/test/java → Unit & integration tests
  • Often mirrors your main Java package structure
Posted in Без рубрики | Comments Off on Java.Servlets.What is the structure of a web project?

Java.Servlet.What are the advantages of servlet technology over CGI (Common Gateway Interface)?

⚙️ 1. Better Performance

  • CGI: A new process is created for each request, which is expensive in terms of system resources.
  • Servlets: Run in a single JVM, and each request is handled by a thread, not a new process. This leads to faster execution and better scalability.

🔄 2. Multithreading

  • CGI: Doesn’t support multithreading. Each request = separate process = no shared memory.
  • Servlets: Are multithreaded. Multiple clients can be served by spawning threads inside the same servlet instance.

🧠 3. Resource Sharing

  • CGI: Since each request runs in its own process, it can’t easily share data between requests or users.
  • Servlets: Run in a shared context and can store data in memory, like in ServletContext, HttpSession, etc.

💡 4. Platform Independence

  • Servlets are written in Java and benefit from Java’s platform independence, while CGI scripts are often written in platform-specific languages (e.g., Perl, C).

📦 5. Extensive API Support

  • Servlets come with a rich Java EE API, including:
    • Session management
    • Cookies
    • Security
    • Integration with JDBC, JSP, and other Java technologies

🔐 6. Security and Maintainability

  • Servlets are managed by a container (like Tomcat, Jetty) which provides:
    • Authentication and authorization
    • Lifecycle management
    • Logging and monitoring

🛠️ 7. Ease of Development and Debugging

  • Java provides strong type checking, exception handling, and debugging tools that are better than traditional scripting languages used in CGI.

🧪 Summary Table

FeatureCGIServlet
Process per requestYesNo (thread per request)
PerformanceSlowerFaster
Memory usageHigherLower
API supportLimitedRich Java APIs
ScalabilityPoorExcellent
Session managementManualBuilt-in
SecurityManual handlingContainer-managed
Posted in Без рубрики | Comments Off on Java.Servlet.What are the advantages of servlet technology over CGI (Common Gateway Interface)?

Java.Servlet.What is a “servlet”?

A servlet is a Java program that runs on a Java-enabled web server (like Apache Tomcat) and handles HTTP requests and responses. Servlets are part of the Java EE (Jakarta EE) platform and are used to create dynamic web content, such as web pages or data responses.

In simple terms:

A servlet is like a middleman between a web browser (client) and the server-side Java application logic.

🔧 How It Works (Simplified Flow):

  1. Client sends an HTTP request (like clicking a button or submitting a form).
  2. Web server receives the request and passes it to the servlet.
  3. Servlet processes the request (e.g., fetches data from DB, does logic).
  4. Servlet generates a response (often HTML or JSON).
  5. Web server sends the response back to the browser.

📦 Servlet Lifecycle:

Managed by the Servlet container (like Tomcat):

  1. init() – Initializes the servlet (called once).
  2. service() – Called for each client request.
  3. destroy() – Called before the servlet is removed from memory.
@WebServlet("/hello")
public class HelloServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<h1>Hello, Stanley!</h1>");
    }
}

🧠 When a user visits http://yourserver/hello, this servlet is triggered and returns an HTML page with “Hello, Stanley!”

Posted in Без рубрики | Comments Off on Java.Servlet.What is a “servlet”?

Java.Reactive.Why do we need all that reactive programming ?

Because the traditional, blocking, imperative approach starts to fall apart when we build modern, scalable, high-performance, real-time systems.

Let’s unpack that:

Continue reading →
Posted in Без рубрики | Comments Off on Java.Reactive.Why do we need all that reactive programming ?

Java.Reative.What are the operators in Project Reactor and what are they used for?

🎯 In Project Reactor, operators are the core tools you use to transform, filter, merge, delay, or otherwise manipulate data as it flows through a reactive pipeline.

Think of operators as the “verbs” in your reactive code — each one defines how the data should be handled.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Reative.What are the operators in Project Reactor and what are they used for?

Java.Reactive.How to unsubscribe from a stream to prevent memory leaks?

Let’s look at how to unsubscribe from a stream in different reactive libraries to avoid memory leaks or resource hogging.


🧼 Why Unsubscribe?

Streams may emit:

  • Forever (e.g., mouse clicks, websocket events)
  • Or slow, bursty data (e.g., Kafka, sensors)

If you don’t unsubscribe, subscribers stay in memory, keep receiving events, and:

  • Memory leaks occur
  • Threads/processors are wasted
  • Resources (DB, sockets, etc.) stay open

✅ How to Unsubscribe by Library


1️⃣ RxJava

You use a Disposable object to unsubscribe.

🔧 Example:

Disposable disposable = Observable.interval(1, TimeUnit.SECONDS)
    .subscribe(i -> System.out.println("Received: " + i));

// Later, when done
disposable.dispose();

📌 Notes:

  • dispose() stops the flow and removes the subscriber.
  • Always dispose() in onDestroy() (Android) or shutdown hooks (server apps).

2️⃣ Project Reactor (Reactor Core)

You get a Disposable or use BaseSubscriber to cancel().

🔧 Example:

Disposable disposable = Flux.interval(Duration.ofSeconds(1))
    .subscribe(i -> System.out.println("Tick: " + i));

// Unsubscribe later
disposable.dispose();

Or with manual control:

BaseSubscriber<Long> subscriber = new BaseSubscriber<>() {
    @Override
    protected void hookOnSubscribe(Subscription subscription) {
        request(Long.MAX_VALUE); // or control backpressure
    }

    @Override
    protected void hookOnNext(Long value) {
        System.out.println("Got: " + value);
    }
};

// Later: unsubscribe
subscriber.cancel();

3️⃣ Spring WebFlux

Spring WebFlux auto-handles subscription lifecycle per HTTP request.

But if you’re streaming or subscribing inside a service, use .doFinally() to clean up.

🔧 Example:

Flux.interval(Duration.ofSeconds(1))
    .doOnCancel(() -> System.out.println("Stream canceled"))
    .doFinally(signal -> System.out.println("Final signal: " + signal))
    .subscribe();

Use .take(n) or .timeout(...) to auto-complete a stream.

4️⃣ Akka Streams

Streams are materialized into a Cancellable or KillSwitch.

🔧 Example:

val cancellable = Source.tick(1.second, 1.second, "tick")
  .to(Sink.foreach(println))
  .run()

// Later
cancellable.cancel()

Or with shared cancellation:

val killSwitch = KillSwitches.shared("my-switch")
val source = Source.tick(...).via(killSwitch.flow)
killSwitch.shutdown() // stop all flows

🛠 Pro Tips

TipWhy
Use .take(n) or .timeout(...)Auto-unsubscribes when data limit or time passes
Use .doFinally(...)Clean up resources (close file, release connection)
Store and manage Disposable or Subscription referencesUnsubscribe explicitly when no longer needed
Combine with lifecycle hooks (Spring, Android, etc.)Prevent leaks during shutdowns or navigation
Posted in Без рубрики | Comments Off on Java.Reactive.How to unsubscribe from a stream to prevent memory leaks?