Java serialization and NIO

Four ways to create objects

  • New Object
    Open up memory space for storage in heap
  • Clone Copy Create Object
  • Deserialize
    Restore the byte sequence to the original Java object
  • reflex

Serializable and Deserialize

Serialization: A Java object is "transformed" into a sequence of bytes. This facilitates persistent storage to disk, avoids the disappearance of objects from memory after the program runs, and facilitates network transportation and propagation by converting them to byte sequences.

Deserialization: Restores the byte sequence to the original Java object.

Interface for serialization: Serializable

Serializable is a markup interface that does not implement anything but tells the JVM that the current object needs to be serialized.
(The Cloneable interface is also a markup interface and has nothing but tells the JVM that the object needs cloning)

SerialVersionUID is the unique identifier before and after serialization. If no SerialVersionUID has been defined artificially, the compiler will automatically declare one. Generally, no human processing is required.

  • Note:
    static modifiers will not be serialized
    transient modifiers will not be serialized

Demo

Car.java

package com.wdy.stream;
import java.io.Serializable;
public class Car implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L; //Version information, automatically declared by the compiler. No artificial modification is generally required
	private int id;
	private String brand;
	private String color;
	private double price;

	public Car()  {

	}

	public Car (int id, String brand, String color, double price) {
		this.id = id;
		this.brand = brand;
		this.color = color;
		this.price = price;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getBrand() {
		return brand;
	}

	public void setBrand(String brand) {
		this.brand = brand;
	}

	public String getColor() {
		return color;
	}

	public void setColor(String color) {
		this.color = color;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Car [id=" + id + ", brand=" + brand + ", color=" + color + ", price=" + price + "]";
	}
}

Output stream writes properties of Car object

package com.wdy.stream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/*
 * Output stream writes properties of Car object
 */
public class ObjectOutputStreamDemo {
	public static void main(String[] args) throws Exception {
		
		ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("D:\\car.dat")); //Create Input Stream Object Byte Stream Object
		Car c = new Car(1, "bmw", "black", 1200000.00);
		out.writeObject(c);//Write property
		out.close();
		
		
	}
}

Execution results:

package com.wdy.stream;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/*
 * Output stream reads out the contents of a file
 */
public class ObjectInputStreamDemo {
public static void main(String[] args) throws Exception {
		
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("D:\\car.dat"));
		
		Car  car = (Car) in.readObject();//The method by which.readObject() reads the object reads the Car object. Turn Strongly
		
		System.out.println(car);

	}
}

Execution results:

NIO

Java. The full name of nio, java non-blocking 10 - (actually new io), refers to the new api (New IO) provided in JDK version 1.4 and above that provides caching support for all original types except boolean types: data containers that provide non-blocking, highly scalable networks.

Composition of NIO

  • Channel
    A channel represents an open connection to an IO device (for example, a file, a socket). If you need to use a NIO system, you need to get the channels used to connect the IO devices and the buffers used to hold the data. Then the buffer is manipulated to process the data.
    Channel is more efficient than Stream in IO. Channel can transmit in both directions asynchronously, but must be used with buffer.

  • Buffer (Cache)
    Buffers are essentially a block of data that can be written to and then read from
    Memory for fetching data. This block of memory is packaged as a NIO Buffer object and provides a set of methods for accessing it easily.

  • Selector
    Allow single-threaded processing of multiple Channel s if your application has multiple connections open
    Connect (channel), but each connection has a low traffic, so using the Selector method is easy
    Yes.
    Selector can detect multiple NIO Channel s to see if read or write events are ready.
    Multiple Chanel s can be registered as events to the same Seletor, making it possible to process multiple requests with one thread.

Demo

nio can read and write simultaneously to achieve non-blocking synchronization compared with normal input and output streams. Ordinary streams can block write (read) threads when performing read (write) tasks.

package com.wdy.stream;
import java.io.FileNotFoundException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class NIODemo {
	public static void main(String[] args) throws Exception {
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		System.out.println(path);
		path =path.substring(0, path.length()-4);
		System.out.println(path);
		String fileName = path+"src/io/file/FileDemo02.java";
		
		RandomAccessFile raf = new RandomAccessFile(fileName, "rw");//Create a NIO read object "rw" to represent readable and writable
		
		FileChannel inChannel = raf.getChannel(); //Open Channel, Open Channel (nio) can read and write simultaneously, non-blocking synchronization compared with normal input and output streams. Normal streams block write threads when performing read (write) tasks
		
		ByteBuffer buffer = ByteBuffer.allocate(64);//Create cache space. Size is confirmed as appropriate
		
		int n = 0;
		
		while((n=inChannel.read(buffer))!=-1) { //Read the contents of the cache through a channel
			buffer.flip();//Move to the first location of the cache
			while(buffer.hasRemaining()) {//Determine if the cache has data
				System.out.print((char)buffer.get()); //Read in bytes. Strong to char
			}
			buffer.clear();
		}		
		raf.close();	
	}
}


Keywords: Java Back-end

Added by krraleigh on Fri, 04 Feb 2022 19:07:50 +0200