☕💻 JAVA THREADS CHEAT SHEET 🔹 🧠 What is a Thread? 👉 The smallest unit of execution in a process. Each thread runs independently but shares memory & resources with others. 🧩 Enables multitasking and parallel execution. 🔹 ⚙️ What is a Process? 👉 An executing instance of a program. Each process has its own memory space and can run multiple threads. 🧵 Types of Threads 👤 1️⃣ User Threads ✅ Created by users or apps. ✅ JVM waits for them before exit. 💡 Example: Thread t = new Thread(() -> System.out.println("User Thread")); t.start(); 👻 2️⃣ Daemon Threads ⚙️ Background threads (e.g., Garbage Collector). ❌ JVM doesn’t wait for them. 💡 Example: Thread d = new Thread(() -> {}); d.setDaemon(true); d.start(); 🚀 Creating Threads 🔸 Extending Thread: class MyThread extends Thread { public void run(){ System.out.println("Running..."); } } new MyThread().start(); 🔸 Implementing Runnable: new Thread(() -> System.out.println("Runnable running...")).start(); 🔄 Thread Lifecycle 🧩 NEW → RUNNABLE → RUNNING → WAITING/BLOCKED → TERMINATED 🕹️ Common Thread Methods 🧩 Method ⚡ Use start() Start a thread run() Thread logic sleep(ms) Pause execution join() Wait for thread interrupt() Interrupt thread setDaemon(true) Make daemon thread 🔒 Synchronization Prevents race conditions when multiple threads share data. synchronized void increment() { count++; } 💬 Thread Communication Use wait(), notify(), and notifyAll() for coordination. 🧠 Must be called inside a synchronized block. ⚡ Executor Framework (Thread Pooling) Efficient thread reuse for better performance. ExecutorService ex = Executors.newFixedThreadPool(3); ex.submit(() -> System.out.println("Task executed")); ex.shutdown(); 🏁 Pro Tips ✅ Prefer Runnable / ExecutorService ✅ Handle InterruptedException ✅ Avoid deprecated methods (stop(), suspend()) ✅ Use java.util.concurrent for safe multithreading 📢 Boost Your Skills 🚀 #Java #Threads #Multithreading #Concurrency #JavaDeveloper #JavaInterview #JavaCoding #JavaProgrammer #CodeNewbie #ProgrammingTips #DeveloperCommunity #CodingLife #LearnJava #JavaCheatSheet #ThreadPool #TechInterview #SoftwareEngineer #CodeWithMe #JavaExperts #BackendDeveloper #JavaLearning #JavaBasics #OOP #CodeDaily #CodingJourney #DevCommunity #JavaLovers #TechCareers #CodeSmarter #100DaysOfCode
Java Threads Cheat Sheet: Learn Multithreading Basics
More Relevant Posts
-
Java ke deepest secrets! 🔥 --- Post 1: Java ka "Hidden Synthetic Methods" ka raaz!🤯 ```java public class SyntheticMagic { private String secret = "Hidden"; // Java compiler internally ye method banata hai: // synthetic access$000() - private variable access ke liye } class InnerClass { void show() { SyntheticMagic obj = new SyntheticMagic(); // obj.secret - ye access karne ke liye compiler // synthetic method generate karta hai! } } ``` Secret: Java compiler private members access karne ke liye hidden synthetic methods banata hai!💀 --- Post 2: Java ka "Bridge Methods" ka internal magic!🔥 ```java class Parent<T> { public void set(T value) { } } class Child extends Parent<String> { public void set(String value) { } // Override } ``` Compile Time pe Java ye bridge method add karta hai: ```java // Synthetic bridge method public void set(Object value) { set((String) value); // Type cast karke actual method call } ``` Kyun? Type erasure ke baad bhi polymorphism maintain karne ke liye!💡 --- Post 3: Java ka "Constant Pool" ka hidden storage!🚀 ```java public class ConstantPoolSecrets { public static void main(String[] args) { String s1 = "Java"; String s2 = "Java"; int num = 100; float f = 3.14f; } } ``` .class file ke constant pool mein store hoga: ``` Constant pool: #1 = String #2 // "Java" #2 = Utf8 Java #3 = Integer 100 #4 = Float 3.14f ``` Secret: Har.class file ka apna constant pool hota hai jisme sab constants store hote hain!💪 --- Post 4: Java ka "Exception Handler" ka bytecode magic!🔮 ```java public class ExceptionSecrets { public static void main(String[] args) { try { riskyMethod(); } catch (RuntimeException e) { handleError(); } } } ``` Bytecode Level Exception Table: ``` Exception table: from to target type 0 4 7 Class java/lang/RuntimeException ``` Internal Working: · from to to → try block range · target → catch block start · type → kis exception ka handle hoga 💀 --- yeh secrets toh Java bytecode engineers ke dil mein chhupe hain! 😎
To view or add a comment, sign in
-
Java ke woh secrets jo creators ke alawa kisi ko nahi pata! 🔥 --- Post 1: Java Compiler ka "Constant Folding" magic!🤯 ```java public class ConstantMagic { public static void main(String[] args) { String result = "J" + "a" + "v" + "a"; System.out.println(result); } } ``` Compile Time pe yeh ban jata hai: ```java String result = "Java"; // ✅ Compiler ne sab combine kar diya! ``` Secret: Java compiler compile time pe constant expressions evaluate kar leta hai! 💀 --- Post 2: Java ka "String Pool" internal working!🔥 ```java String s1 = "Java"; String s2 = "Java"; String s3 = new String("Java").intern(); // ✅ Pool mein daalta hai System.out.println(s1 == s2); // true ✅ System.out.println(s1 == s3); // true ✅ ``` Internal Magic: · String s1 = "Java" → String Pool check karta hai · new String("Java") → Heap mein new object banata hai · .intern() → String Pool mein daalta hai 💡 --- Post 3: Java ka "Auto-boxing" cache secret!🚀 ```java Integer i1 = 10; Integer i2 = 10; Integer i3 = 1000; Integer i4 = 1000; System.out.println(i1 == i2); // true ✅ (-128 to 127 cache) System.out.println(i3 == i4); // false ❌ (cache range ke bahar) ``` Kya scene hai? Java-128 se +127 tak Integer values cache karta hai! Isliye== work karta hai sirf cache range mein! 💪 --- Post 4: Java ka "Static Block" execution order!🔮 ```java class Parent { static { System.out.println("Parent static block"); } } class Child extends Parent { static { System.out.println("Child static block"); } } public class Test { public static void main(String[] args) { new Child(); } } ``` Output: ``` Parent static block Child static block ``` Secret: Parent class ka static block pehle execute hota hai!💀 --- yeh secrets samajhne waala 0.0001% developers mein se ek hoga! 😎
To view or add a comment, sign in
-
☕ JVM Architecture — Behind the Scenes of Every Java Program The Java Virtual Machine (JVM) is the heart of Java — it enables platform independence by running bytecode on any system. It performs 3 key functions: 1️⃣ Loads Java bytecode (.class files) 2️⃣ Verifies and prepares memory for classes 3️⃣ Executes the program 🧩 JVM Major Components JVM ├── Class Loader Subsystem ├── Runtime Data Areas └── Execution Engine ├── Interpreter ├── JIT Compiler ├── Garbage Collector ├── Native Interface (JNI) └── Native Method Libraries 🔹 1. Class Loader Subsystem It’s the first component of the JVM, responsible for loading .class files into the JVM’s Runtime Data Areas, which reside inside the JVM process in the primary memory (RAM). Responsibilities: Loading → Linking → Initialization ✅ Loading: Loads class bytecode from disk, JARs, or remote sources using: Bootstrap ClassLoader → Core Java (<JAVA_HOME>/lib) Extension ClassLoader → Optional libs (lib/ext) Application ClassLoader → User-defined classes from classpath ✅ Linking: Verifies bytecode (security + correctness), prepares memory for static variables, and assigns default values. ✅ Initialization: Assigns actual values to statics and executes static blocks. At this stage, the class is ready for use. ☕ Java 8 vs Java 11 – Behind the Scenes Java 8 (Traditional Way) 1️⃣ Save Hello.java on disk (secondary memory) 2️⃣ Run javac Hello.java → generates Hello.class on disk 3️⃣ Run java Hello → Class Loader loads .class from disk → JVM executes it ✅ .class file exists on disk Java 11 (Single-File Execution) 1️⃣ Save Hello.java 2️⃣ Run java Hello.java → JVM compiles it internally 3️⃣ Bytecode (.class) generated temporarily in RAM 4️⃣ Class Loader loads in-memory bytecode into Method Area 5️⃣ After execution → bytecode discarded ✅ .class file lives only in memory 🧠 2. Runtime Data Areas Memory areas inside the JVM where program data lives during execution. RAM (Primary Memory) └── JVM Process ├── Method Area → class info, static vars, bytecode ├── Heap → objects ├── Stack → Method calls, local variables, references ├── PC Register → next instruction pointer └── Native Method Stack → JNI/native calls ⚙️ 3. Execution Engine Once classes are loaded into the Method Area, the Execution Engine translates bytecode into native machine code and then the CPU runs that native code. Components: * Interpreter → Reads bytecode line by line (slower) * JIT Compiler → Converts hot spots to native code for speed * Garbage Collector → Reclaims unused memory from the Heap JNI & Native Libraries: * JNI (Java Native Interface): Allows Java to call C/C++ methods. * Native Method Libraries: Actual libraries (.dll, .so) used by JNI. ☕ Loved it? Drop a coffee — let’s keep the Java vibes strong! 💻 #Java #JVM #JavaDeveloper #JVMArchitecture #CoreJava #Programming #Developers #SoftwareEngineering #JavaCommunity #TechLearning #BackendDevelopment #LearnJava #CodeWithMohan
To view or add a comment, sign in
-
Quick Java 8 Streams Refresh — From Revisiting to Refining: Sometimes, going back to the basics helps you rediscover how powerful simple concepts can be. I recently took some time to refresh my Java 8 Stream skills I’ve attached the complete Java file — hoping it can serve as a handy reference for anyone revisiting Streams or learning them in depth. Here’s what’s inside. 🔹 Grouping and aggregation 🔹 Calculating totals using both Collectors.summingLong() and reduce() 🔹 Word and character frequency analysis 🔹 Merging and transforming multiple lists into one stream 🔹 Detecting duplicates, unique elements, and even the second-highest transaction 🔹 Sorting complex objects with Comparator.comparing() 🔹 Reversing words, removing nulls, partitioning data, and more Each snippet reminded me how Streams simplify Java code — making it more declarative, expressive, and concise. Here’s a small example ________________________________________________________________________ // Find second highest credit transaction List<Transaction> transactions2 = new ArrayList<>(); transactions2.add(new Transaction(transactionType.CREDIT, 10)); transactions2.add(new Transaction(transactionType.CREDIT, 50)); transactions2.add(new Transaction(transactionType.DEBIT, 100)); transactions2.add(new Transaction(transactionType.DEBIT, 20)); transactions2.add(new Transaction(transactionType.CREDIT, 30)); Transaction secondHighest = transactions2.stream() .filter(t -> t.getType() == transactionType.CREDIT) .sorted(Comparator.comparingInt(Transaction::getAmount).reversed()) .skip(1) .findFirst() .get(); System.out.println(secondHighest); ________________________________________________________________________ Full code attached below — feel free to explore and reuse! Let’s keep learning, refining, and sharing knowledge together. #Java #Java8 #Streams #FunctionalProgramming #CleanCode #CodingPractice #DeveloperCommunity #LearningInPublic
To view or add a comment, sign in
-
In Java, there are several ways to create and run threads, Spring Boot also have @Async annotation to run method code as thread. 1. Extending the Thread class You can create a subclass of Thread and override the run() method. ✅ Example: class MyThread extends Thread { @Override public void run() { System.out.println("Thread running " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); } } 🧩 2. Implementing the Runnable interface ✅ Example: class MyRunnable implements Runnable { @Override public void run() { System.out.println("Thread running using Runnable interface: " + Thread.currentThread().getName()); } } public class Main { public static void main(String[] args) { Thread t1 = new Thread(new MyRunnable()); t1.start(); } } 🟢 Why preferred: Allows you to extend another class (since Java supports only single inheritance). ⚡ 3. Using Anonymous Class You can create and start a thread in one line using an anonymous inner class. ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(new Runnable() { @Override public void run() { System.out.println("Thread running using Anonymous class"); } }); t1.start(); } } 💡 4. Using Lambda Expression (Java 8+) ✅ Example: public class Main { public static void main(String[] args) { Thread t1 = new Thread(() -> { System.out.println("Thread running using Lambda expression"); }); t1.start(); } } ⚙️ 5. Using ExecutorService (Thread Pool) For multiple or managed threads, use an Executor Service. ✅ Example: import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Main { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> System.out.println("Thread 1 using ExecutorService")); executor.submit(() -> System.out.println("Thread 2 using ExecutorService")); executor.shutdown(); } } 🟢 Advantages: Reuses threads (avoids overhead of creating new threads repeatedly) Supports async tasks and better error handling 🧠 6. Using Callable and Future (for return values) Callable is like Runnable, but can return a value and throw exceptions. ✅ Example: import java.util.concurrent.*; public class Main { public static void main(String[] args) throws Exception { ExecutorService executor = Executors.newSingleThreadExecutor(); Callable<String> task = () -> { return "Result from thread: " + Thread.currentThread().getName(); }; Future<String> future = executor.submit(task); System.out.println(future.get()); executor.shutdown(); } }
To view or add a comment, sign in
-
Java ke parallel universe ke secrets! 🔥 --- Post 1: Java ka "Hidden Class" API - Java 15+ ka best kept secret!🤯 ```java import java.lang.invoke.*; public class HiddenClassMagic { public static void main(String[] args) throws Throwable { MethodHandles.Lookup lookup = MethodHandles.lookup(); byte[] classBytes = getClassBytes(); // Bytecode bytes // Hidden class banayi jo reflection mein visible nahi hogi! Class<?> hiddenClass = lookup.defineHiddenClass(classBytes, true).lookupClass(); MethodHandle mh = lookup.findStatic(hiddenClass, "secretMethod", MethodType.methodType(void.class)); mh.invoke(); // ✅ Chalega but Class.forName() se nahi milegi! } } ``` Secret: Hidden classes reflection mein visible nahi hoti, par perfectly work karti hain!💀 --- Post 2: Java ka "Thread Local Handshakes" ka JVM level magic!🔥 ```java public class ThreadHandshake { static { // JVM internally sab threads ko pause kiye bina // single thread ko stop kar sakta hai! // Ye Java 9+ mein aaya for better profiling // -XX:ThreadLocalHandshakes=true } } ``` Internal Use Cases: · Stack sampling without stopping all threads · Lightweight performance monitoring · Better garbage collection Secret: JVM ab single thread ko individually manipulate kar sakta hai! 💡 --- Post 3: Java ka "Contended" annotation for false sharing prevention!🚀 ```java import jdk.internal.vm.annotation.Contended; public class FalseSharingFix { // Ye do variables different cache lines mein store honge! @Contended public long value1 = 0L; @Contended public long value2 = 0L; } ``` JVM Option Required: ``` -XX:-RestrictContended ``` Performance Impact: Multi-threaded apps mein 30-40%performance improvement! 💪 --- Post 4: Java ka "CDS Archives" - Application startup 10x faster!🔮 ```java // Kuch nahi karna - bas JVM options use karo: // Dump CDS archive: // -Xshare:dump -XX:SharedArchiveFile=app.jsa // Use CDS archive: // -Xshare:on -XX:SharedArchiveFile=app.jsa ``` Internal Magic: · Pre-loaded classes shared memory mein · Startup time dramatically kam · Memory footprint reduce Result: Spring Boot apps 3-4 seconds se 400-500ms startup!💀 ---
To view or add a comment, sign in
-
Java ke atomic level ke secrets! 🔥 --- Post 1: Java ka "Multi-Release JAR" ka hidden feature!🤯 ```java // Java 8 version - base code public class TimeUtils { public static String getTime() { return "Legacy time: " + new Date(); } } // Java 11 version - META-INF/versions/11/TimeUtils.java public class TimeUtils { public static String getTime() { return "Modern time: " + Instant.now(); } } ``` Secret: Ek hi JAR mein multiple Java versions ke liye alag-alag class files ho sakti hain!💀 --- Post 2: Java ka "ConstantDynamic" - invokedynamic for constants!🔥 ```java public class ConstantDynamic { // Java 11+ mein constants bhi dynamically resolve ho sakte hain public static final String DYNAMIC_CONSTANT = ConstantDescs.of("Dynamically resolved constant"); // Bytecode level par invokedynamic use karta hai // instead of constant pool entry! } ``` Internal Magic: · Traditional: Constant Pool → LDC instruction · New: ConstantDynamic → invokedynamic instruction · Dynamic constant resolution at runtime! 💡 --- Post 3: Java ka "Vector API" - SIMD operations ka raaz!🚀 ```java import jdk.incubator.vector.*; public class VectorMagic { public static void main(String[] args) { IntVector a = IntVector.fromArray(IntVector.SPECIES_256, new int[]{1,2,3,4,5,6,7,8}, 0); IntVector b = IntVector.fromArray(IntVector.SPECIES_256, new int[]{8,7,6,5,4,3,2,1}, 0); IntVector result = a.add(b); // ✅ 8 operations ek saath! // CPU level par SIMD instructions use karta hai } } ``` Performance: 10x faster for mathematical operations!💪 --- Post 4: Java ka "Heap Allocation" ka hidden alternative!🔮 ```java import java.lang.foreign.*; public class OffHeapMagic { public static void main(String[] args) { // Heap se bahar memory allocate karo! try (Arena arena = Arena.ofConfined()) { MemorySegment segment = arena.allocate(100); // Direct OS memory access - no GC overhead! segment.set(ValueLayout.JAVA_INT, 0, 42); int value = segment.get(ValueLayout.JAVA_INT, 0); } } } ``` Benefits: · Zero GC pressure · Direct memory access · C-like performance 💀 --- Bhai, yeh features toh aane wali Java generations ke liye hain! 😎
To view or add a comment, sign in
-
Java ke woh secrets jo documentation mein bhi nahi hain! 🔥 --- Post 1: Java Compiler ka "Negative Array Size" bug!🤯 ```java public class NegativeArray { public static void main(String[] args) { try { int[] arr = new int[-5]; // ❌ Negative size } catch (NegativeArraySizeException e) { // Ye exception JVM ke internal memory allocation se aati hai // Java specification ke according, yeh error compulsory hai! } } } ``` Secret: Java specification page 329: "Array creation with negative size must throw NegativeArraySizeException" - ye rule JVM implementers ko follow karna compulsory hai! 💀 --- Post 2: Java ka "Floating-Point Non-Associativity" paradox!🔥 ```java public class FloatingParadox { public static void main(String[] args) { double a = 1.0e308; // Very large number double b = -1.0e308; // Very large negative double c = 1.0; double result1 = (a + b) + c; // (0) + 1 = 1 double result2 = a + (b + c); // Infinity + (-Infinity) = NaN System.out.println(result1); // 1.0 System.out.println(result2); // NaN } } ``` Mathematical Paradox: Java floating-point arithmetic associative nahi hai! IEEE 754 standard ka hidden rule! 💡 --- Post 3: Java ka "Class File Magic Number" ka raaz!🚀 ```java // Har .class file ke start mein ye 4 bytes hote hain: // CA FE BA BE - "Coffee Baby"! // Ye Java creators ne randomly choose kiya tha 1995 mein! public class MagicNumber { public static void main(String[] args) throws Exception { byte[] classBytes = java.nio.file.Files.readAllBytes( java.nio.file.Paths.get("MagicNumber.class") ); // First 4 bytes check karo System.out.printf("%02X %02X %02X %02X", classBytes[0], classBytes[1], classBytes[2], classBytes[3]); // Output: CA FE BA BE } } ``` Historical Secret: James Gosling team ne ye magic number randomly rakha tha! 💪 --- Post 4: Java ka "Null Type" ka compiler-level existence!🔮 ```java public class NullType { public static void main(String[] args) { // Java compiler internally null ka ek special type maintain karta hai // called "the null type" - jiska koi name nahi hota! String s = null; Integer i = null; // Compiler null ko kisi bhi reference type assign kar sakta hai // kyunki uska apna alag "null type" hai! } } ``` Language Theory: Java Language Specification §4.1: "There is also a special null type, the type of the expression null" - ye type sirf compiler internally use karta hai! 💀
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development