Skip to content

Java Spring

Background

Language: Java

Usages:

Description

  • A dependency injection framework for Java that has many web and backend plugins

Types

Reactive

  • Spring WebFlux (Reactive)
  • Asynchronous threads, non-blocking, event loop
  • Event-Driven Architecture
  • Netty
  • Request gets assigned to thread
  • Functional Programming / Reactive Programming
  • Complex to code, but more thread efficient
  • HTTP Client: WebClient

Servlet

  • Spring MVC
  • Synchronous threads (blocking)
  • Thread per request
  • Imperative Programming
  • Simpler to code, but less efficient
  • HTTP Client: RestTemplate (deprecated)

Examples

  • Restaurant
    • Reactive:
      1. server takes queue of orders (events)
      2. cook "subscribes" to queue of meals to prepare
      3. cook "publishes" to waiters queue to serve once meal is done
      • each threads are optimally used
    • Servlet:
      1. server takes order
      2. cook prepares (30min)
      3. serve food
      4. repeat
      • each order is a new thread

SpringBoot

SpringBoot is a bootstrap for Spring

Spring Security

OAuth implementation built in to Spring

Classes

Thread Safety

https://stackoverflow.com/questions/43314831/spring-boot-class-behaviour

  • When using @Bean @Autowired or any method of creating a singleton class, one instance will be created and shared for the entire application (unless @Scope is defined)
  • Each request to the application is a on its own thread
  • Static variables by nature are shared amongst all instances, so it is shared amongst all threads
  • Class-level variables will be shared amongst all threads for a singleton, since it's one shared instance of the class used for all requests
  • For data that should not be shared, create a new instance of that non singleton class every time (not a bean)
  • @Scope(value="request")
  • If the data needs to be shared but thread safe: https://www.baeldung.com/java-thread-safety
    • Stateless static methods (just takes an input)
    • Atomic objects, like AtomicInteger
    • Immutable variables (private final and use a getter)