Skip to content
AL-406 · Java Lab/Quick Revision Short Notes

Java Lab (AL-406) - Unit 5 Short Notes

UNIT 5: ADVANCED JAVA & ENTERPRISE TECHNOLOGIES


1. Core Java Advanced Concepts

Multithreading & Concurrency
  • Thread Lifecycle & States:

    • NEW: Thread created but not started.

    • RUNNABLE: Executing or ready to execute in JVM.

    • BLOCKED: Waiting to acquire a monitor lock.

    • WAITING: Waiting indefinitely for another thread (e.g., Object.wait(), Thread.join()).

    • TIMED_WAITING: Waiting for a specified time (e.g., Thread.sleep(ms), Object.wait(timeout)).

    • TERMINATED: Completed execution.

  • Creating Threads:

    | Method | Pros | Cons | | :--- | :--- | :--- | | Extend Thread | Simple, start() available. | Java doesn't support multiple inheritance. | | Implement Runnable | Allows class to extend another class. Shared instance among threads. | No direct return value or checked exception handling. | | Callable + ExecutorService | Returns a value (Future), can throw checked exceptions. | Requires ExecutorService to manage. |

  • Thread Synchronization:

    • synchronized keyword: Ensures only one thread executes a synchronized block/method at a time.

    • Intrinsic Lock (Monitor): Every object has one. synchronized uses it.

    • Static Synchronization: Locks on the Class object.

    [!TIP] Synchronization Scope: Prefer synchronizing smallest possible block to reduce contention.

  • java.util.concurrent Package:

    • ExecutorService: Manages a pool of threads.

      
      ExecutorService pool = Executors.newFixedThreadPool(4);
      
      Future<?> future = pool.submit(() -> { /* task */ });
      
      pool.shutdown();
      
      
    • Callable<V> & Future<V>: Callable returns V; Future.get() retrieves result (blocks).

    • ThreadPoolExecutor: Core executor with configurable pool size, queue, etc.

    • Concurrent Collections: ConcurrentHashMap (segment-based locking), CopyOnWriteArrayList (copy-on-write, good for reads).

    • Atomic Variables: AtomicInteger, AtomicReference use CAS (Compare-And-Swap) for lock-free thread safety.

      CAS Logic: if (value == expected) value = newValue;

    • ReentrantLock: Explicit lock with tryLock(), fairness, and Condition interface for fine-grained control.

    • ReadWriteLock: Separate locks for read (shared) and write (exclusive) operations.

  • Common Concurrency Problems:

    • Race Condition: Multiple threads access shared data without proper synchronization.

    • Deadlock: Two+ threads wait forever for locks held by each other. (Circular wait).

    • Starvation: A thread is perpetually denied access to resources.

    • Livelock: Threads constantly change state in response to each other but make no progress.

Advanced I/O (NIO.2 - java.nio.file)
  • Path, Paths, Files:

    • Path represents a file path (platform-independent).

    • Paths.get("file.txt") creates a Path.

    • Files class: Static utility methods for file operations.

      
      // Read all bytes
      
      byte[] data = Files.readAllBytes(Paths.get("file.txt"));
      
      // Write string
      
      Files.write(Paths.get("out.txt"), "content".getBytes(), StandardOpenOption.CREATE);
      
      // Copy
      
      Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
      
      // Delete
      
      Files.delete(Paths.get("temp.txt"));
      
      
  • File Attributes:

    • BasicFileAttributes: size, creation time, last modified time.

    • DosFileAttributes (Windows): read-only, hidden, system, archive.

    
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    
    long size = attr.size();
    
    
  • Walking the File Tree:

    • Implement FileVisitor<T> (override visitFile, preVisitDirectory, visitFileFailed).

    • Use Files.walkFileTree(startPath, visitor).

    • Extend SimpleFileVisitor<T> for default (no-op) implementations.

  • Asynchronous I/O:

    • AsynchronousFileChannel for non-blocking read/write.

    • Uses Future or CompletionHandler for result/notification.

  • Memory-Mapped Files:

    • MappedByteBuffer maps a file directly into memory.

    • Fast I/O for large files; changes may not be immediately persisted to disk.

    
    try (RandomAccessFile file = new RandomAccessFile("data.bin", "rw")) {
    
        MappedByteBuffer buffer = file.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, 1024);
    
        buffer.putInt(0, 12345); // Write directly to memory
    
    }
    
    

2. Java Database Connectivity (JDBC)

  • JDBC Architecture & Driver Types:

    | Type | Description | Example | | :--- | :--- | :--- | | Type 1 | JDBC-ODBC Bridge (deprecated). | sun.jdbc.odbc.JdbcOdbcDriver | | Type 2 | Native API/Part Java driver (uses vendor's client library). | Oracle OCI driver | | Type 3 | Network Protocol/All Java driver (middle-tier). | Pure Connect for Oracle | | Type 4 | Thin driver (pure Java, connects directly). | com.mysql.cj.jdbc.Driver |

  • Core Interfaces & Classes Flow:

    DriverManager → Connection → Statement/PreparedStatement/CallableStatement → ResultSet

    
    // 1. Load Driver (Type 4 often auto-registered via SPI)
    
    Class.forName("com.mysql.cj.jdbc.Driver");
    
    // 2. Get Connection
    
    Connection conn = DriverManager.getConnection(url, user, pass);
    
    // 3. Create Statement
    
    PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM users WHERE id = ?");
    
    pstmt.setInt(1, 101);
    
    // 4. Execute & Get ResultSet
    
    ResultSet rs = pstmt.executeQuery();
    
    while(rs.next()) { String name = rs.getString("name"); }
    
    // 5. Close resources (in reverse order)
    
    rs.close(); pstmt.close(); conn.close();
    
    
  • CRUD Operations:

    • Create/Update/Delete: executeUpdate() returns int (number of rows affected).

    • Read: executeQuery() returns ResultSet.

  • Transaction Management:

    
    conn.setAutoCommit(false); // Start transaction
    
    try {
    
        // ... multiple DML statements
    
        conn.commit(); // Success
    
    } catch (SQLException e) {
    
        conn.rollback(); // Failure
    
    } finally {
    
        conn.setAutoCommit(true);
    
    }
    
    
  • Batch Processing:

    
    pstmt = conn.prepareStatement("INSERT INTO users(name) VALUES(?)");
    
    pstmt.setString(1, "Alice"); pstmt.addBatch();
    
    pstmt.setString(1, "Bob"); pstmt.addBatch();
    
    int[] counts = pstmt.executeBatch(); // Returns update counts per command
    
    
  • SQLWarning & SQLException:

    • SQLWarning (subclass of SQLException) for non-fatal database warnings.

    • Access via conn.getWarnings() or stmt.getWarnings().

  • RowSet:

    • Connected (JdbcRowSet): Always connected to DB, like a scrollable ResultSet.

    • Disconnected (CachedRowSet): Can disconnect, data stored in memory. Serializable, can be sent over network.

  • Metadata:

    • DatabaseMetaData: About DB (product name, version, supported features).

    • ResultSetMetaData: About ResultSet (column count, names, types).


3. Java Networking

  • Basics: IP (address), Port (logical endpoint), TCP (reliable, connection-oriented), UDP (unreliable, connectionless, faster).

  • java.net Key Classes:

    • InetAddress: Represents IP address (getByName(), getLocalHost()).

    • TCP Socket Programming:

      • Server: ServerSocket server = new ServerSocket(port); Socket client = server.accept();

      • Client: Socket socket = new Socket(host, port);

      • I/O: socket.getInputStream(), socket.getOutputStream().

    • UDP Datagram:

      • DatagramSocket + DatagramPacket.

      • No connection; send/receive packets.

    
    // Server (TCP)
    
    ServerSocket ss = new ServerSocket(5000);
    
    Socket s = ss.accept();
    
    BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    
    PrintWriter out = new PrintWriter(s.getOutputStream(), true);
    
    // Client (TCP)
    
    Socket s = new Socket("localhost", 5000);
    
    
  • URL & HttpURLConnection:

    
    URL url = new URL("http://example.com");
    
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    
    conn.setRequestMethod("GET"); // or "POST"
    
    int code = conn.getResponseCode(); // 200 OK
    
    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    
    

4. Java Web Technologies (Servlets & JSP)

  • Web App Architecture: 3-Tier (Client/Presentation, Business/Logic, Data).

  • Servlet Lifecycle:

    1. init(): Called once on servlet instantiation.

    2. service(): Called for each request (dispatches to doGet(), doPost()).

    3. destroy(): Called before removal from service.

  • Request Handling:

    • request.getParameter("name"): Single value.

    • request.getParameterValues("hobby"): Multiple values (checkboxes).

    • RequestDispatcher:

      • forward(req, res): Server-side transfer, same request/response.

      • include(req, res): Includes resource's output in current response.

    • response.sendRedirect(url):` Client-side redirect (new request, URL changes).

  • Session Management:

    • Cookies: response.addCookie(new Cookie("name", "value")).

    • HttpSession: request.getSession() (creates if absent), session.setAttribute().

    • URL Rewriting: response.encodeURL("page.jsp") appends session ID.

  • JSP Lifecycle: Translation → Compilation → Execution.

  • JSP Elements:

    | Element | Syntax | Purpose | | :--- | :--- | :--- | | Scriptlet | <% java code %> | Embed Java logic (avoid). | | Expression | <%= expression %> | Evaluates and prints. | | Declaration | <%! declaration %> | Declares methods/variables (class level). | | Directive | <%@ directive %> | Page info (page), include (include), taglib (taglib). | | Action | <jsp:useBean ...> | Use JavaBean, forward, include. |

  • JSP Implicit Objects: request, response, session, application (ServletContext), out (JspWriter), pageContext, config, page, exception.

  • JSTL Core Tags: <c:forEach>, <c:if>, <c:choose>.

  • Deployment:

    • web.xml: Deployment descriptor (servlet mapping, filters, listeners).

    • Annotations: @WebServlet("/path"), @WebFilter, @WebListener.

  • Filters & Listeners:

    • Filter: Pre-process request/post-process response. Chain via FilterChain.doFilter().

    • ServletContextListener: App startup/shutdown events.

    • HttpSessionListener: Session creation/destruction events.


5. Introduction to Java Frameworks

Spring Framework Core (IoC & DI)
  • IoC: Control of object creation/management inverted from application to Spring Container.

  • DI: Container injects dependencies into beans.

  • Containers:

    • BeanFactory: Basic container, lazy loading.

    • ApplicationContext: Advanced, eager singleton loading, internationalization, event propagation.

  • Bean Configuration:

    • XML: <bean id="..." class="..."/>.

    • Annotations: @Component (generic), @Service, @Repository, @Controller. @Configuration + @Bean for Java config.

    • Java Config: @Configuration class with @Bean methods.

  • DI Types:

    • Constructor Injection: Dependencies via constructor. (Recommended for mandatory deps).

    • Setter/Property Injection: Via setter methods.

  • Bean Scopes:

    | Scope | Description | | :--- | :--- | | singleton | (Default) One shared instance per container. | | prototype | New instance each request. | | request | One per HTTP request (Web context). | | session | One per HTTP session. | | application | One per ServletContext. |

  • Autowiring:

    • byName, byType, constructor.

    • Annotations: @Autowired (by type), @Qualifier("beanName") (disambiguate).

Spring MVC
  • Architecture: DispatcherServlet (Front Controller) → Handler Mapping → Controller → View Resolver → View.

  • Controllers: @Controller (returns view name), @RestController (returns data, @ResponseBody implied).

  • Request Mapping: @RequestMapping, @GetMapping, @PostMapping.

  • Model & View:

    • Model, ModelMap: Add attributes.

    • ModelAndView: Holds both model and view name.

    • InternalResourceViewResolver: Resolves view names to JSPs (/WEB-INF/views/**.jsp).

  • Form Handling: @ModelAttribute binds form fields to object. @Valid + BindingResult for validation.

  • Exception Handling: @ExceptionHandler in controller, @ControllerAdvice for global.

Hibernate ORM
  • ORM Maps: Java Class ↔ Database Table, Object Fields ↔ Table Columns.

  • Architecture:

    • Configuration: Loads config/mappings.

    • SessionFactory: Heavyweight, immutable, built from Configuration.

    • Session: Lightweight, single-threaded, main interface for persistence ops.

    • Transaction: session.beginTransaction(), tx.commit(), tx.rollback().

  • Entity Mapping Annotations:

    • @Entity, @Table(name="...").

    • @Id, @GeneratedValue(strategy=...).

    • @Column(name="...", nullable=false, length=50).

    • Associations:

      • @OneToOne, @ManyToOne (owning side usually has @JoinColumn).

      • @OneToMany(mappedBy="...") (inverse side).

      • @ManyToMany (with mappedBy on one side, join table via @JoinTable).

  • HQL: Object-oriented query language (operates on entities).

    
    List<User> users = session.createQuery("FROM User WHERE age > :age", User.class)
    
                              .setParameter("age", 18)
    
                              .list();
    
    
  • Session Operations:

    • save(), update(), delete(): State transitions.

    • get() vs load(): get() returns null if not found; load() throws ObjectNotFoundException (proxy).

    • merge(): Returns persistent copy of detached object.

  • Caching:

    • First-Level (Session): On by default, per session.

    • Second-Level (SessionFactory): Optional, shared across sessions.

    • Query Cache: Caches query results (requires second-level cache).

  • Fetching: FetchType.LAZY (default for @OneToMany, @ManyToMany) vs FetchType.EAGER (default for @ManyToOne, @OneToOne).

Spring Boot
  • Advantages: Auto-configuration, Starter dependencies (spring-boot-starter-web), Embedded servers (Tomcat/Jetty), No XML.

  • Entry Point: @SpringBootApplication (combines @Configuration, @EnableAutoConfiguration, @ComponentScan).

    
    SpringApplication.run(Application.class, args);
    
    
  • Properties: application.properties or application.yml.

    
    server.port=8081
    
    spring.datasource.url=jdbc:mysql://localhost:3306/db
    
    
  • RESTful Services: @RestController, @RequestMapping("/api").

  • Spring Data JPA: JpaRepository<T, ID> interface provides CRUD, paging, sorting methods automatically.


6. Build Tools & Project Management

  • Apache Maven:

    • POM.xml: groupId (project group), artifactId (project name), version.

    • Dependencies: <dependency> with groupId, artifactId, version.

    • Build Lifecycle:

      validate → compile → test → package → install → deploy.

    • Common Plugins: maven-compiler-plugin, maven-surefire-plugin (tests), maven-war-plugin.

  • Gradle (Brief):

    • Build Script: build.gradle (Groovy/Kotlin DSL).

    • Dependencies: dependencies { implementation 'group:artifact:version' }.

    • Tasks: gradle build, gradle test.


7. Testing in Java

  • JUnit 5 (Jupiter):

    • Lifecycle: @BeforeEach, @AfterEach, @BeforeAll, @AfterAll (static).

    • Assertions: assertEquals(expected, actual), assertTrue(), assertThrows().

    • Disable: @Disabled.

  • Spring Testing:

    • @SpringBootTest: Full application context.

    • @WebMvcTest: Slice test for MVC layer (controllers).

    • Mockito: @Mock (create mock), @InjectMocks (inject mocks), when(mock.method()).thenReturn(value).


8. Design Patterns in Java (Relevant to Frameworks)

Pattern Category Framework Example
Singleton Creational Spring Beans (default singleton scope).
Factory Creational BeanFactory, ApplicationContext.
Proxy Structural Spring AOP (creates proxy objects for advice).
Decorator Structural Java I/O (BufferedInputStream, GZIPInputStream).
Observer Behavioral Servlet listeners, Spring ApplicationEvent.
Strategy Behavioral @Qualifier to choose between implementations.
Template Method Behavioral JdbcTemplate, HibernateTemplate (fixed algorithm, customizable steps).
Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in