0% found this document useful (0 votes)
3 views6 pages

H Java Depth

The document provides an overview of core Java concepts, including OOP principles, key concepts like immutability and exception handling, and the Java Collections Framework. It also covers Java threads and concurrency, detailing thread creation, synchronization, and key concurrency concepts. Additionally, it discusses the Java Memory Model, garbage collection, and Java Streams introduced in Java 8, outlining their core concepts and operations.

Uploaded by

vinaythe221
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

H Java Depth

The document provides an overview of core Java concepts, including OOP principles, key concepts like immutability and exception handling, and the Java Collections Framework. It also covers Java threads and concurrency, detailing thread creation, synchronization, and key concurrency concepts. Additionally, it discusses the Java Memory Model, garbage collection, and Java Streams introduced in Java 8, outlining their core concepts and operations.

Uploaded by

vinaythe221
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Core Java

OOP Principles

Encapsulation — Bundling data + methods together, hiding internals via


access modifiers (private, protected, public)

Inheritance — Child class extends parent, reuses behavior. class Dog


extends Animal

Polymorphism — Same method name, different behavior. Compile-time


(overloading) vs runtime (overriding)

Abstraction — Hiding complexity. Abstract classes and interfaces expose


only what's needed

Key Concepts

Immutability — String is immutable. final prevents reassignment.


Immutable objects are thread-safe.

Generics — Type safety at compile time. List<String> prevents runtime


ClassCastException

Exception Handling — Checked (must handle: IOException) vs Unchecked


(NullPointerException). try-catch-finally, try-with-resources

Functional Interfaces — Single abstract method. Predicate<T>,


Function<T,R>, Consumer<T>, Supplier<T>

Lambda Expressions — Concise anonymous functions: (x) -> x * 2

Optional — Avoids null. [Link](value).orElse("default")

equals/hashCode contract — If [Link](b), then [Link]() ==


[Link](). Critical for HashMap/HashSet

Serialization — Converting object to byte stream. Serializable interface,


transient keyword skips fields

Collections Framework

Interface Implementations Use Case

List ArrayList, LinkedList Ordered, allows duplicates

Set HashSet, TreeSet, LinkedHashSet Unique elements

Map HashMap, TreeMap, LinkedHashMap, ConcurrentHashMap Key-


value pairs

Queue PriorityQueue, ArrayDeque FIFO processing

2. Java Threads & Concurrency


Thread Creation

// Way 1: Extend Thread

class MyThread extends Thread {

public void run() { [Link]("Running"); }

// Way 2: Implement Runnable

Runnable task = () -> [Link]("Running");

new Thread(task).start();

// Way 3: Callable + Future (returns result)

Callable<Integer> callable = () -> 42;

Future<Integer> future = [Link](callable);

int result = [Link](); // blocks until done

Thread Lifecycle

NEW → RUNNABLE → RUNNING → BLOCKED/WAITING/TIMED_WAITING →


TERMINATED

Synchronization

// synchronized method

public synchronized void increment() { count++; }

// synchronized block (finer control)

synchronized(lockObject) { count++; }

// ReentrantLock (more flexible)

Lock lock = new ReentrantLock();

[Link]();

try { count++; } finally { [Link](); }


Key Concurrency Concepts

volatile — Guarantees visibility across threads. No caching. Doesn't


guarantee atomicity.

Atomic classes — AtomicInteger, AtomicReference. Lock-free thread safety


via CAS (Compare-And-Swap)

ThreadLocal — Per-thread isolated variable. Each thread gets its own copy.

Deadlock — Thread A holds Lock1, waits for Lock2. Thread B holds Lock2,
waits for Lock1. Both stuck forever.

Race Condition — Multiple threads modify shared state without


synchronization. Unpredictable results.

ExecutorService

// Fixed pool - reuses threads

ExecutorService executor = [Link](4);

// Submit tasks

[Link](() -> processRequest());

// Shutdown gracefully

[Link]();

[Link](30, [Link]);

CompletableFuture (Async programming)

[Link](() -> fetchUser(id))

.thenApply(user -> [Link]())

.thenAccept(name -> [Link](name))

.exceptionally(ex -> { [Link](ex); return null; });

Concurrent Collections

Class Use Case

ConcurrentHashMap Thread-safe map, no full lock

CopyOnWriteArrayList Read-heavy, write-rare lists

BlockingQueue Producer-consumer pattern


CountDownLatch Wait for N threads to complete

CyclicBarrier N threads wait for each other at a point

Semaphore Limit concurrent access to a resource

3. Java Memory Model

Memory Structure

┌─────────────────────────────────────┐

│ JVM Memory │

├─────────────┬───────────────────────┤

│ Heap │ Stack (per thread) │

├─────────────┼───────────────────────┤

│ Young Gen │ Local variables │

│ - Eden │ Method call frames │

│ - S0, S1 │ Primitive values │

│ Old Gen │ Object references │

├─────────────┼───────────────────────┤

│ Metaspace │ (class metadata) │

└─────────────┴───────────────────────┘

Heap — Young Generation

Eden — New objects created here

Survivor Spaces (S0, S1) — Objects that survive minor GC move here

Minor GC — Cleans Eden + one Survivor. Fast, frequent.

Heap — Old Generation

Objects that survive multiple minor GCs are promoted here

Major GC / Full GC — Cleans Old Gen. Slower, causes longer pauses.

Stack (per thread)

Stores method call frames, local variables, references

StackOverflowError — too deep recursion

Thread-safe by nature (each thread has its own stack)

Metaspace (Java 8+)


Stores class metadata, method info

Replaces PermGen. Grows dynamically (native memory)

-XX:MaxMetaspaceSize to limit

Garbage Collection

GC Algorithm Description

Serial GC Single-threaded. Small apps.

Parallel GC Multi-threaded. Throughput-focused.

G1 GC (default since Java 9) Divides heap into regions. Balances


latency/throughput.

ZGC / Shenandoah Ultra-low pause (<10ms). Large heaps.

Key GC Concepts

GC Roots — Stack variables, static fields, active threads. Objects


reachable from roots are alive.

Stop-the-world — Application pauses during GC. G1/ZGC minimize this.

Memory Leaks — Objects referenced but never used (e.g., growing static
collections, unclosed resources, listener registrations)

Common JVM Flags

-Xms512m # Initial heap

-Xmx2g # Max heap

-XX:+UseG1GC # Use G1 collector

-XX:+HeapDumpOnOutOfMemoryError # Dump heap on OOM

-XX:MetaspaceSize=256m

Common Memory Issues

OutOfMemoryError: Java heap space — Objects fill the heap. Increase -


Xmx or fix leaks.

OutOfMemoryError: Metaspace — Too many classes loaded (common with


dynamic proxies/classloaders)

StackOverflowError — Infinite recursion or very deep call chains

4. Java Streams (Java 8+)

Core Concepts

Source → Intermediate ops (lazy) → Terminal op (triggers execution)


Streams don't store data — they process elements on-the-fly

Single-use: a stream can only be consumed once

Intermediate Operations (lazy, return Stream)

Operation Purpose Example

filter Keep matching elements .filter(e -> [Link]() > 18)

map Transform each element .map(Employee::getName)

flatMap Flatten nested structures .flatMap(list -> [Link]())

sorted Sort elements .sorted([Link](E::getName))

distinct Remove duplicates .distinct()

peek Debug/inspect without modifying .peek([Link]::println)

limit Take first N .limit(5)

skip Skip first N .skip(10)

Terminal Operations (trigger execution)

Operation Purpose Example

collect Gather into collection .collect([Link]())

forEach Side-effect per element .forEach([Link]::println)

reduce Combine all into one .reduce(0, Integer::sum)

count Count elements .count()

findFirst / findAny Get one element .findFirst()

anyMatch / allMatch / noneMatch Boolean check .anyMatch(e ->


[Link]())

min / max Find extremes .max([Link](E::getSalary))

toArray Convert to array .toArray(String[]::new)

You might also like