Java File I/O (NIO.
2), Serialization, Concurrency, and Synchronization
## 1. File I/O (NIO.2)
### Introduction to NIO.2
Java NIO (New I/O) was introduced in JDK 1.4 and enhanced in JDK 7 with NIO.2 to address
limitations in standard I/O (java.io package). NIO provides efficient buffer-oriented,
channel-based I/O operations.
### Key Concepts
- **Path:** Represents the location of a file or directory.
- **Files:** Utility class with methods to operate on files and directories.
- **FileChannel:** Used for reading, writing, mapping, and manipulating files.
- **AsynchronousFileChannel:** Supports asynchronous reading and writing.
### More Detailed Theory
- **Blocking vs Non-blocking I/O:** Traditional I/O blocks the thread until operation is
complete, whereas NIO uses channels and buffers to enable non-blocking I/O.
- **Channel and Buffer:** Channels read/write data, while buffers hold the data
temporarily.
### Working with Paths
```java
import java.nio.file.*;
public class PathExample {
public static void main(String[] args) {
Path path = Paths.get("C:/example/test.txt");
System.out.println("File name: " + path.getFileName());
}
}
```
## 2. Serialization and Deserialization
### Definition
- **Serialization:** Process of converting an object into a byte stream.
- **Deserialization:** Process of converting a byte stream back to an object.
### Key Concepts
- **Serializable Interface:** Marks a class as capable of being serialized.
- **ObjectOutputStream:** Writes serialized objects to a file.
- **ObjectInputStream:** Reads serialized objects from a file.
- **serialVersionUID:** Ensures that a deserialized object is compatible with the class
definition.
## 3. Concurrency and Multithreading
### Definition
- **Concurrency:** Ability to run multiple threads simultaneously.
- **Multithreading:** Multiple threads executing different parts of a program concurrently.
### Key Concepts
- **Thread:** Represents a lightweight process.
- **Runnable:** Provides a way to define tasks to be executed by threads.
- **ExecutorService:** Manages thread pools and schedules tasks.
## 4. Synchronization and Locks
### Definition
- **Synchronization:** Mechanism to ensure that multiple threads access shared resources
in a thread-safe manner.
- **Lock:** Provides more control over synchronization.
### Types of Synchronization
- **Synchronized Methods:** Synchronize access to critical sections.
- **Synchronized Blocks:** Provide finer control over object locks.
- **ReentrantLock:** Allows fine-grained lock control with explicit locking and unlocking.