banner
Onei

Onei

github
nintendo switch
discord server
steam
pixiv
bento
follow

Data Processing

🌊 IO Stream#

Input and Output

Four Major Abstract Classes#

  • By Data Type
    • Byte Stream
    • Character Stream
  • By Data Flow Direction
    • Input Stream: Input to memory
    • Output Stream: Output from memory
  • By Functionality
    • Node Stream
      Directly operates on data streams
    • Processing Stream
      Processes other streams

📥 InputStream#

FileInputStream#

  • public FileInputStream(String)
    Opens an input stream connection, requires a file path and throws an exception
  • public int read()
    Reads the next byte and returns the corresponding ASCII value; returns -1 if the end of the file is reached

📤 OutputStream#

FileOutputStream#

  • public FileOutputStream(String)
    Opens a stream connection, requires a file path and throws an exception, overwrites the file
  • public FileOutputStream(String, Boolean)
    Opens a stream connection, requires a file path and throws an exception; if true, it appends to the file
  • public void write()
    • public void write(byte[])
    • public void write(byte[], int, int)
  • public void flush()
  • public void append()

📖 Reader#

FileReader#

Character input stream that reads one character at a time, can avoid garbled Chinese characters, mainly suitable for plain text files

✍️ Writer#

FileWriter#

  • public void write()
    • public void write(char[])
    • public void write(char[], int, int)
    • public void write(String)
    • public void write(String, int, int)
  • public void flush()
  • public void append()

🔌 Node Processing Stream#

Requires a node stream (FileInputStream, FileOutputStream, FileReader, FileWriter) for processing

🧺 Buffered Stream#

BufferedReader#

BufferedWriter#

BufferedInputStream#

  • public String readLine()
    Returns the data read this time; returns null if the end of the file is reached, does not read the newline character
  • public int available()
    The number of bytes available in the file

BufferedOutputStream#

💫 Conversion Stream#

Converts byte streams to character streams

🖨️ PrintStream#

Print stream provides many printing methods for convenience, allowing users to pass data directly for printing

The standard input and output in the System class

in: Standard input, defaults to console input
out: Standard output, defaults to print to console
err

The System class provides three methods to redirect standard input/output

static void setErr(PrintStream err) Redirects the "standard" error output stream
static void setIn(PrintStream in) Redirects the "standard" input stream
static void setOut(PrintStream out) Redirects the "standard" output stream

FileOutputStream fos = new FileOutputStream("./src/test.txt");
// Wrapping the output stream makes output operations more convenient
// Byte print stream
PrintStream ps = new PrintStream(fos);
// The default out in System prints to the console, but can modify the print path
System.setOut(ps);
System.out.println("===============");

Features#

  • Print stream is the most convenient class for output
  • Includes byte print stream PrintStream and character print stream PrintWriter
  • PrintStream is a subclass of OutputStream; passing an output stream instance to the print stream allows for easier content output, effectively wrapping the output stream
  • The print() method of the PrintStream class is overloaded many times: print(int i), print(boolean b), print(char c)

PrintWriter#

Character print stream

  • public void println()

✍️ DataInputStream#

Different operating systems like Linux and Windows store data differently.
To solve the uniformity of data reading across different platforms, data streams ensure data consistency.

📁 File#

  • public boolean isFile()
    Checks if it is a file
  • public boolean isDirectory()
    Checks if it is a directory
  • public boolean exists()
    Checks if it exists
  • public String getAbsolutePath()
    Gets the full path (including file name and extension)
  • public String getName()
    Gets the file name + extension a.txt
  • public String getParent()
    Gets the parent directory
  • public File getParentFile()
    Gets the parent directory file object
  • public File[] listFiles()
    Gets child file objects

📬 Serialization and Deserialization#

Serialization: Saving an object to disk for persistent storage
Deserialization: Loading a persistently stored object into memory
Purpose: To store an object long-term for easy transmission over a network

The class must implement the Serializable interface to be serialized.

Specify version number using the serialVersionUID attribute to verify compatibility between the loaded class and the serialized object.

transient#

Keyword

Restricts the current attribute from being serialized; the attribute value will not be saved.

🧵 Multithreading#

Program: A collection of commands to accomplish a specific function; a static concept generally stored on disk.
Process: A running program; a dynamic concept that needs to be stored in memory, with the operating system allocating a corresponding PID. When we directly close a process, it will terminate.
Thread: Different execution branches within a program; when multiple threads are allowed to execute simultaneously at the same time point, we call it supporting multithreading. In Java, when the main() method starts executing, it is a thread, called the main thread.

Concurrency: One CPU executing multiple tasks simultaneously
Parallelism: Multiple CPUs executing multiple tasks simultaneously

Inheritance Method#

Inherit the Thread class and override the run() method, which is equivalent to the new thread's main() method.

Implementation Method#

Implement the Runnable interface and override the run() method.

Differences Between Inheritance and Implementation#

  • Differences
    • Inherit Thread: Thread code is stored in the run method of the Thread subclass.
    • Implement Runnable: Thread code exists in the run method of the subclass of the interface.
  • Benefits of Implementation
    • Avoids the limitations of single inheritance
    • Multiple threads can share the same interface implementation object, which is very suitable for multiple identical threads to handle the same resource.

Note

Do not directly call the run() method; otherwise, it will just be a method call and will not start a new thread.

Priority#

The default priority is 5

  • public final int getPriority()
    Gets the thread's priority value
  • public final void setPriority(int newPriority)
    Sets the thread's priority value

Methods#

  • public final synchronized void setName(String name)
    Sets the thread name
  • public final String getName()
    Gets the thread name, names are Thread-0, Thread-1, ...
  • public final native boolean isAlive()
    Checks if the thread is still "alive," i.e., whether the thread has not yet terminated.
  • public static native void sleep(long millis) throws InterruptedException
    Puts the current thread to sleep for the specified milliseconds
  • public final void stop()
    Stops the thread (not recommended), which may lead to a deadlock state, so use a flag to terminate
  • public final void join() throws InterruptedException
    Merges two threads
  • public static native void yield();
    Yields the current CPU time slice to allow other threads to execute. If it gets the CPU time slice and there are threads with the same priority, it can choose to yield.
  • public static native Thread currentThread()
    Returns a reference to the currently executing thread object.

⌛ Lifecycle#

The JDK defines several states of a thread using the Thread.state class.

Five states:

  1. New
    When an object of the Thread class or its subclass is declared and created, the newly born thread object is in the new state.
  2. Ready
    A thread in the new state enters the thread queue waiting for CPU time slice after being started with start(). At this point, it is ready to run but has not been allocated CPU resources.
  3. Running
    When a ready thread is scheduled and obtains CPU resources, it enters the running state; the run() method defines the operations and functions of the thread.
  4. Blocked
  5. In certain special cases, when it is artificially suspended or performing input/output operations, it yields the CPU and temporarily halts its execution, entering the blocked state.
  6. Death
    The thread has completed all its work, or the thread has been forcibly terminated early, or an exception has caused it to end.

🤝 Thread Synchronization#

The uncertainty of multiple threads executing leads to unstable execution results.

Thread synchronization: When multiple threads may simultaneously operate on the same data, synchronization execution is required to ensure data consistency.
Essentially, it synchronizes data and is a safety mechanism.
Asynchronous programming: Threads are completely independent and do not affect each other.
Synchronous programming: Threads are not completely independent and may affect each other.

🔒 Thread Lock#

Method Lock#

synchronized: Method locking
When a thread accesses a member method modified with synchronized in an object, all member methods modified with synchronized in that object are locked.
At this time, no thread can access the synchronized member methods; they must queue up, and only after the previous thread completes the method will the lock be released, allowing other threads to access.

Disadvantages: Low efficiency. Requires queuing for execution, and all synchronized member methods in the entire object are locked.
Advantages: Ensures data safety and consistency, avoiding data errors.

🍰 Statement Block Lock#

Class Lock#

Static methods can also be locked, called class lock.
All locked static methods and static statement blocks are locked Synchronized(ClassName.class){}.

Object Lock#

Members can also be locked, called object lock.
In that object, all locked member methods and member statement blocks are locked Synchronized(Object){} (different objects do not affect each other).

🔐 Lock#

  • Starting from JDK 5.0, Java provides a more powerful thread synchronization mechanism—achieved by explicitly defining synchronization lock objects. The synchronization lock uses the Lock object.
  • The java.util.concurrent.locks.Lock interface is a tool for controlling multiple threads' access to shared resources. The lock provides exclusive access to shared resources; only one thread can lock the Lock object at a time, and a thread must obtain the Lock object before accessing shared resources.
  • The ReentrantLock class implements Lock, which has the same concurrency and memory semantics as synchronized. In implementing thread-safe control, ReentrantLock is commonly used, allowing explicit locking and unlocking.

Lock is an explicit lock that needs to be manually opened and closed.
Synchronized is an implicit lock that opens automatically and closes automatically after execution.
Lock only supports block locks, while synchronized supports both method and block locks.
Lock requires less time from the JVM for resource scheduling, offering relatively better performance and good scalability.
Order of use: Lock --> synchronized block lock --> method lock.

⏱️ Timer Task#

Timer: Scheduled task
As long as there is a scheduled task, a thread will be started to keep time, and when the specified time is reached, that thread will complete the task.

Methods#

  • public void schedule(TimerTask task, long delay, long period)
  • public void schedule(TimerTask task, long delay)
public class MyTimerTest {
    public static void main(String[] args) {
        Timer timer = new Timer();
        timer.schedule(new MyTimer(), 1000, 500);
    }
}

class MyTimer extends TimerTask {

    @Override
    public void run() {
        System.out.println("run() method executed");
    }
}

🦸 Daemon Thread#

Every program runs with a daemon thread that starts synchronously to monitor our normal program.
When the main thread finishes execution, the daemon thread also loses its value, as there is no work to do; at this point, the JVM will shut down, and the daemon thread will terminate.
We can set a thread as a daemon thread using threadObject.setDaemon(true) (must be set before starting).

🧟‍♀️ Deadlock#

During program execution, encountering the other party entering the locked method causes methods to be inaccessible.

Principle:

  1. One thread completes execution and needs to nest locks on two objects in order, locking the first object first and then the second object.
  2. Another thread completes execution and needs to nest locks on two objects in order, locking the second object first and then the first object.
  3. In the first thread, after locking the first object, it tries to lock the second object but finds that the second object is already locked and can only wait.
  4. In the second thread, after locking the second object, it tries to lock the first object but finds that the first object is already locked and can only wait.

✉️ Thread Communication#

Methods in Object

  • wait(): Puts the thread into a waiting state (suspended state); when awakened, it enters the ready state and continues executing from where it was suspended.

No parameters or passing 0 means it will not wake up automatically and can only be awakened by (notify(), notifyAll()).

  • notify(): Randomly wakes one thread waiting on that object to let other threads execute.
  • notifyAll(): Wakes all threads waiting on that object.

You can also pass a long type milliseconds, which will automatically wake up after the specified milliseconds.
Difference between wait and sleep: sleep does not release the lock and still occupies the lock, preventing other threads from entering; wait releases the lock, allowing other threads to enter.
The above methods must be used in member methods, and that method must be locked (synchronized).

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.