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. | | ImplementRunnable| 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. | RequiresExecutorServiceto manage. | -
Thread Synchronization:
-
synchronizedkeyword: Ensures only one thread executes a synchronized block/method at a time. -
Intrinsic Lock (Monitor): Every object has one.
synchronizeduses it. -
Static Synchronization: Locks on the
Classobject.
[!TIP] Synchronization Scope: Prefer synchronizing smallest possible block to reduce contention.
-
-
java.util.concurrentPackage:-
ExecutorService: Manages a pool of threads.ExecutorService pool = Executors.newFixedThreadPool(4); Future<?> future = pool.submit(() -> { /* task */ }); pool.shutdown(); -
Callable<V>&Future<V>:CallablereturnsV;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,AtomicReferenceuse CAS (Compare-And-Swap) for lock-free thread safety.CAS Logic:
if (value == expected) value = newValue; -
ReentrantLock: Explicit lock with tryLock(), fairness, andConditioninterface 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:-
Pathrepresents a file path (platform-independent). -
Paths.get("file.txt")creates aPath. -
Filesclass: 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>(overridevisitFile,preVisitDirectory,visitFileFailed). -
Use
Files.walkFileTree(startPath, visitor). -
Extend
SimpleFileVisitor<T>for default (no-op) implementations.
-
-
Asynchronous I/O:
-
AsynchronousFileChannelfor non-blocking read/write. -
Uses
FutureorCompletionHandlerfor result/notification.
-
-
Memory-Mapped Files:
-
MappedByteBuffermaps 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()returnsResultSet.
-
-
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 ofSQLException) for non-fatal database warnings. -
Access via
conn.getWarnings()orstmt.getWarnings().
-
-
RowSet:
-
Connected (
JdbcRowSet): Always connected to DB, like a scrollableResultSet. -
Disconnected (
CachedRowSet): Can disconnect, data stored in memory. Serializable, can be sent over network.
-
-
Metadata:
-
DatabaseMetaData: About DB (product name, version, supported features). -
ResultSetMetaData: AboutResultSet(column count, names, types).
-
3. Java Networking
-
Basics: IP (address), Port (logical endpoint), TCP (reliable, connection-oriented), UDP (unreliable, connectionless, faster).
-
java.netKey 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:
-
init(): Called once on servlet instantiation. -
service(): Called for each request (dispatches todoGet(),doPost()). -
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 viaFilterChain.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+@Beanfor Java config. -
Java Config:
@Configurationclass with@Beanmethods.
-
-
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 perServletContext. | -
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,@ResponseBodyimplied). -
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:
@ModelAttributebinds form fields to object.@Valid+BindingResultfor validation. -
Exception Handling:
@ExceptionHandlerin controller,@ControllerAdvicefor global.
Hibernate ORM
-
ORM Maps: Java Class ↔ Database Table, Object Fields ↔ Table Columns.
-
Architecture:
-
Configuration: Loads config/mappings. -
SessionFactory: Heavyweight, immutable, built fromConfiguration. -
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(withmappedByon 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()vsload():get()returnsnullif not found;load()throwsObjectNotFoundException(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) vsFetchType.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.propertiesorapplication.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>withgroupId,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). |