# # # introduction

I know that deli group has campus recruitment in some training institutions yesterday. So I came here today and listened to the presentation. Discover deli group just set up research institute in Wuhan in August, mainly to do cloud services, from 0, now the team size is about 20 people. At the beginning, I preached HR, and then I was the technical director. I felt that the technical director gave people a strong feeling.

However, the salary is really too low, 4.5K to 5.5K, and the floating 1K depends on the degree. The main temptation for me is that the cloud service project starts from 0 and can make a big improvement. I really moved, thought to go to the interview first, to see how their skills.


At the beginning of the # # #

  • The interviewer is a very beautifulHRLittle sister. First let me introduce myself and then ask me the following questions.
    • What are your career plans?
    • How do you study?
    • What do you think of Deli Group?

I answered very neatly, and then entered the second interview. The second interview was conducted by an HR and technical director. To my surprise, I was so confused by the questions asked by the technical director that I could not give a complete answer.

At the end of the interview, the technical director asked me if I had anything to say, so I asked about the salary increase standard. Then the HR immediately turned black and told me a lot impatiently. I know from what she said that the minimum salary increase is 10% and the maximum salary increase is 30%. I suddenly felt hopeless, the assessment standard was still one year, and the internship did not pay. Finally, HR asked me if I failed, and I said THAT I failed SCM.

HR turned black again and snapped impatiently. I did not have good impression completely to effective group now, but technical director stumble my problem, I still need reply dish analysis one wave, study is oneself after all.


### About the second interview

#### Observer Pattern This pattern is familiar to me and the implementation of EventBus is based on this pattern. But it’s worth mentioning the pattern.

  • The observer pattern is used when an object has a one-to-many relationship. For example, when an object is modified, its dependent objects are automatically notified. The observer model is a behavioral model.

  • In plain English, the observer pattern defines a one-to-many dependency that allows multiple observer objects to listen on a subject object at the same time. When the topic object changes in its state, all observer objects are notified so that they can update themselves automatically.

  • Composition of the observer model:

    • Abstract subject roles: Store all references to observer objects in a collection, typically using an ArrayList. Each abstract theme role can have any number of observers. Abstract themes can provide an interface to add and remove observers. It is typically implemented with an abstract class and interface.

    • Abstract Observer roles: Define an interface for all concrete observers to update themselves when notified of a topic.

    • Specific topic roles: Notifies all registered observers of changes in the internal state of a specific topic.

    • Concrete observer role: Implements the update interface in the abstract observer to coordinate its own state with the state of the topic.

  • Handwritten observer mode Demo.

    • To define aSubjectClass, that is, observed.
public class Subject {

    private List<Observer> observers = new ArrayList<Observer>();
    private int state;

    public int getState() {
        return state;
    }

    public void setState(int state) {
        this.state = state;
        notifyAllObservers();
    }

    public void attach(Observer observer) {
        observers.add(observer);
    }

    public void notifyAllObservers() {
        for(Observer observer : observers) { observer.update(); }}}Copy the code
  • Define an abstractObServerClass, which is the abstract observer class.
public abstract class Observer {

    protected Subject subject;

    public abstract void update();
}
Copy the code
  • Define a concreteBinaryObserverClass, which inheritsObServerClass.
 public class BinaryObserver extends Observer {

    public BinaryObserver(Subject subject) {
        this.subject = subject;
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println("binary="+ Integer.toBinaryString(subject.getState())); }}Copy the code
  • Define a concreteOctalObserverClass, which inherits fromObServerClass.
 public class OctalObserver extends Observer {

    public OctalObserver(Subject subject) {
        this.subject = subject;
        this.subject.attach(this);
    }

    @Override
    public void update() {
        System.out.println("octal:"+ Integer.toOctalString(subject.getState())); }}Copy the code
  • Write test casesObserverPatternDemoAnd run.
public class ObserverPatternDemo { public static void main(String[] args) { Subject subject = new Subject(); new BinaryObserver(subject); new OctalObserver(subject); subject.setState(15); subject.setState(10); }}Copy the code

  • Advantages and disadvantages of observer mode:

    • The observer and the observed are abstractly coupled.
    • Establish a trigger mechanism.

    Disadvantages:

    • If an observed object has many direct and indirect observers, it can take a long time to notify all of them.

    • If there are cyclic dependencies between the observer and the observed, the observed will trigger cyclic calls between them, possibly causing the system to crash.

    • The observer mode has no corresponding mechanism to let the observer know how the observed object has changed, but only that the observed object has changed.


#### The difference between POST and GET When I was interviewing for a job, I was misled by some blogs on the Internet about the difference between POST and GET. The correction must now begin.

  • GET and POST are essentially TCP links and are no different. Most browsers typically limit url length to 2K bytes, while most servers handle urls with a maximum size of 64K. Due to HTTP regulations and browser/server restrictions, they are applied differently.

  • For GET requests, the browser sends HTTP headers along with data, and the server responds with 200 (return data). For POST, the browser sends a header, the server responds with 100 continue, the browser sends data, and the server responds with 200 (returns data). So GET produces one TCP packet and POST produces two packets. Not all browsers send a packet twice in POST, Firefox only sends it once.

  • GET contains parameters in the URL, and POST passes parameters through the Request body.

  • Idempotent is used to handle repeated requests, such as losing the connection before the request responds. If the method is idempotent, it can safely resend the request again. GET, PUT, and DELETE are idempotent, but POST is not idempotent, which is why the browser notifies the user of a POST request when it is backlogged or refreshed. Repeated requests can cause unexpected results.


#### What is idempotent?

  • Idempotence is a mathematical or computer concept. Often used in abstract algebra. For unary operators, if an operation is performed multiple times on all numbers in the range, the result is the same as if the operation were performed once. Then we say the operation is idempotent. One example is absolute value calculation. In the real set, we have abs(a) = abs(abs(a)). For binocular operation, it is required that when the two values involved in the operation are equal, if the operation result is equal to the two values involved in the operation, then the operation can be called idempotent. So Max (x,x) = x.

  • Idempotent means that executing the same request method multiple times has exactly the same effect as executing it only once.


# # # # for SpringMVC annotation

  • For SpringMVC annotations, see one of my previous articles. MyBatis-Spring official documentation study notes

  • The interviewer asked me for the notes for automatic bag scanning, but I forgot how to read them.


# # # # Java serialization

  • Serialization is the process of converting an object into a sequence of bytes.

  • Deserialization is the process of restoring a sequence of bytes to an object. ,

  • Both Parcelable and Serializable can be serialized. Serializable is a serialization interface in Java, which is simple but expensive to use. Serialization and deserialization processes require a lot of I/O operations. On the other hand, Parcelable is the serialization method in Android, so it works better on The Android platform. The drawback is that it’s a little bit more cumbersome to use, but it’s very efficient. It’s the recommended serialization method on Android, so we’ll go with Parcelable. Parcelable is mainly used for memory serialization, while Serializable is mainly used for serializing objects to storage devices or transferring objects over the network after serialization.

  • We need to specify the value of serialVersionUID. If the current class changes during deserialization, such as adding or deleting member variables, the system recalculates the hash value of the current class and assigns it to the serialVersionUID. The serialVersionUID of the current class does not match the serialVersionUID of the serialized data, and deserialization fails.

The interviewer asked me about the poor Serializable performance of Java and how to serialize it efficiently. I didn’t know what to do. In retrospect, the answer should have been to use a third-party serialization tool, namely Fastjson.

  • Replacing all the other JSON libraries, there is no other JSON library in the Java world that comes close to FastJSON.

  • Use fastJSON serialization and deserialization to replace Java Serializable, which is both slow and bulky.

  • Replace Hessian with Fastjson (a binary-RPC based remote communication library that uses binary data transfer). The JSON protocol is about the same size as Hessian, and Fastjson performs 10 times better than Hessian.

  • Use Fastjson to cache object data in memcached(a high-performance distributed in-memory object caching object system for dynamic Web applications to reduce database load).

While writing, I suddenly thought of the Externalizable interface. This is an alternative serialization mechanism provided by Java that is entirely up to the programmer to store and restore object data. To achieve this, Java classes must implement the Externalizable interface. So let’s write a Demo.

  • To define aPersonClass, implementedjava.io.ExternalizableInterface.PersonClass must be implementedreadExternal().writeExternal()Two methods.
public class Person implements Externalizable {

    private String name;
    private int age;

    public Person(String name, int age) {
        System.out.println("Constructor with parameters");
        this.name = name;
        this.age = age;
    }

    public Person() {
        System.out.println("Constructor with no arguments");
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(new StringBuffer(name).reverse());
        out.writeInt(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        this.name = ((StringBuffer) in.readObject()).reverse().toString();
        this.age = in.readInt();
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]"; }}Copy the code
  • Let’s write a test case.
public class ExternalizableDemo {

    public static void main(String[] args) throws IOException {
        File fileName = new File("externalizable.txt");
        FileOutputStream fos = new FileOutputStream(fileName);
        FileInputStream fis = new FileInputStream(fileName);
        ObjectOutputStream os = new ObjectOutputStream(fos);
        ObjectInputStream is = new ObjectInputStream(fis);

        try {
            Person person = new Person("cmazxiaoma", 21);
            os.writeObject(person);
            os.writeObject(person);

            Person newPerson = (Person) is.readObject();
            System.out.println(newPerson);
            System.out.println("Are two person object references equal :" + person == newPerson + "");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            close(is);
            close(os);
            close(fis);
            close(fos);
        }
    }

    public static void close(Closeable closeable) {
        try {
            if(closeable ! = null) { closeable.close(); } } catch (IOException e) { e.printStackTrace(); }}}Copy the code
  • Run the test case and see the console output. We found that deserialization reads the data in the Java object and then calls the no-argument constructor to do the necessary initialization of the object. We will also see that the Person object before serialization is not the same object as the Person object generated after unserialization. The conclusion: the antisequence will regenerate an object.

  • One can assume that deserialization using Externalizable calls the no-argument constructor. What happens if we remove the no-argument constructor for the Person class and run it again? The line “no valid constructor” is printed, which obviously requires a no-argument constructor.

There are a few other things to note about object serialization.

  • The object’s class name, instance variables (including primitive types, arrays, and references to other objects) are serialized; Methods, class variables, and transient instance variables (transient real column variables) are not serialized.

  • Classes implementing the Serializable interface that want to unserialize an instance variable can prefix it with the TRANSIENT modifier instead of the static keyword. The static keyword can also do this, but it cannot be used this way.

  • To deserialize an object, you must have a class file for the serialized object.

  • When serialized objects are read from a file or network, they must be read in the order in which they are actually written.

  • The Serializable deserialization mechanism restores Java objects without calling a constructor to initialize them, while the Externalizable deserialization mechanism requires a no-argument constructor.

It should also be noted that the Java serialization mechanism uses a special serialization algorithm, as follows:

  • All objects saved to disk have a serialization number.

  • When the program attempts to serialize an object, the program first checks whether the object has been serialized. Only if the object has never been serialized in this virtual machine, the system will convert the object into a byte sequence and output it.

  • If an object has already been serialized, the program outputs only a serialization number, rather than re-serializing the object.


#### What is NIO? The concept of NIO is one of the things THAT I forgot about when I learned about Java. When I read the blog before, I read it sporadically and didn’t care about it at that time. Remember yesterday the technical director asked me what NIO was? I didn’t hear his answer and asked what NIO was. He told me that NIO stands for Asynchronous IO. I didn’t know what to do. Today, I searched the article about NIO above the nuggets and summarized a wave.

  • BIO(Blocking I/O) : Synchronous Blocking I/O mode, data reads and writes must be blocked in a thread waiting for it to complete.

  • NIO(New I/O) : Supports both blocking and non-blocking modes. Taking synchronous non-blocking IO mode as an example, NIO starts a thread constantly polling for the state of the kettle if it’s boiling water.

  • Asynchronous I/O (AIO) : Asynchronous non-blocking I/O mode. The difference between asynchronous non-blocking and synchronous non-blocking is that there is no need to start a thread to poll the kettle. When the kettle is boiling, the system will notify the corresponding thread to handle it.

So we need to talk about the difference between synchronous and asynchronous.

  • Synchronization: Such as sending a request and waiting for a return before sending the next request, with a waiting process in between.

  • Asynchronous: A request can be sent at any time without waiting for a response.

  • Scenario Requirement: Synchronization prevents dirty data from being read. Generally, it is used when sharing A resource. If everyone has the modification permission, when A deletes A file, B accesses the file again, an error will occur, and A synchronization mechanism should be used. For example, the transfer system of the bank, the preservation of the database operation needs to be synchronized.

So what’s the difference between NIO and IO

  • IO can only implement blocking network communication, while NIO can implement non-blocking network communication.

  • While standard IO operates on a byte or character stream, NIO operates on a Channel.

  • Reads and writes to streams are usually one-way, either input or output. A Channel is bidirectional, and data can be written to or read from a Channel.

The difference said, then began the NIO journey.

  • NIO uses a different approach to input IO. NIO handles input/output as a memory-mapped file. NIO maps a file, or a portion of a file, into memory so that files can be accessed as if they were in memory.

  • The main difference between a Channel and a traditional InputStream is that OutputStream provides a map() method that maps a block of data directly into memory. If traditional I/O systems are stream-oriented processing, NIO is block-oriented processing.

  • A Buffer can be understood as a container, which is essentially an array. All objects sent to a Channel must be put into Buffer first, and data read from a Channel must also be put into Buffer first.

  • NIO also provides a Charset class for mapping Unicode strings to byte sequences and reverse mapping operations, as well as a Selector class for non-blocking input/output.

There are three important concepts in Buffer: capacity, limit, and position.

  • Capacity: Capacity of the Buffer Indicates the maximum data capacity of the Buffer.

  • Limit: Data after limit cannot be read or written.

  • Position: Index used to indicate the next buffer position that can be read or written (similar to a record pointer in an IO stream).

Then there are the flip() and clear() methods in Buffer.

  • When Buffer finishes loading the data, the flip() method of Buffer is called, which sets limit to position and position to 0, causing the read/write pointer to Buffer to move its starting position again. In short, filp() is ready to fetch data from Buffer.

  • When the Buffer output is finished, Buffer calls the clear() method. Instead of clearing the Buffer, the clear() method simply sets position to 0 and limit to Capacity, ready to load the Buffer again.

The theory summarizes a lot, so start writing code by hand.

  • We are inNIODemoWrote a3All of these methods are from reading"nio_read.txt"The contents of the file are then written"nio_write.txt"File.
public class NIODemo {

    public static void main(String[] args) throws IOException {
        // methodOne();
        // methodTwo();
        methodThree();
    }

    public static void methodOne() throws IOException {
        String rFile = "nio_read.txt";
        String wFile = "nio_write.txt";
        FileChannel rFileChannel = new FileInputStream(rFile).getChannel();
        FileChannel wFileChannel = new FileOutputStream(wFile).getChannel();
        ByteBuffer buff = ByteBuffer.allocate(1024);

        while (rFileChannel.read(buff) > 0) {
            buff.flip();
            wFileChannel.write(buff);
            buff.clear();
        }

        close(wFileChannel);
        close(rFileChannel);
    }

    public static void methodTwo() throws IOException {
        String rFile = "nio_read.txt";
        String wFile = "nio_write.txt";
        FileChannel rFileChannel = new FileInputStream(rFile).getChannel();
        FileChannel wFileChannel = new FileOutputStream(wFile).getChannel();

        rFileChannel.transferTo(0, rFileChannel.size(), wFileChannel);

        close(wFileChannel);
        close(rFileChannel);
    }

    public static void methodThree() throws IOException {
        String rFile = "nio_read.txt";
        String wFile = "nio_write.txt";
        RandomAccessFile raf = new RandomAccessFile(rFile, "rw"); FileChannel randomChannel = raf.getChannel(); FileChannel wFileChannel = new FileOutputStream(wFile).getChannel(); ByteBuffer buff = randomchannel.map (filechannel.mapmode.read_only, 0, raf.length()); // Move the pointer to Channel to the last randomChannel.position(raf.length()); wFileChannel.write(buff); close(wFileChannel); close(randomChannel); } public static void close(Closeable closeable) { try {if(closeable ! = null) { closeable.close(); } } catch (IOException e) { e.printStackTrace(); }}}Copy the code
  • Now that methodThree() uses RandomAccessFile. Just a quick usage note: RandomAccessFile still can’t insert content into the specified location of the file. If you move the file record pointer to one of the middle positions and start output, the new output will overwrite the original content of the file. If you want to insert content into the specified location, the program needs to read the location after the insertion point into the buffer, and write the data to the file before appending the content of the buffer to the file. ### References

  • 99% of people GET the difference between GET and POST in HTTP wrong

  • Get and POST

  • Observer model

  • Observer mode (Subscribe and publish mode)

  • Discussion on the difference between Get and Post in HTTP

  • Inside Fastjson technology

  • Read Java NIO

  • Let’s just say NIO is simple. It’s actually a great IO

  • What are the differences between BIO, NIO and AIO from a Java perspective?


### Note

  • If the first reference link opens with a parameter error, So please copy the link through QQ or WeChat open https://mp.weixin.qq.com/s?sn=71f6c214f3833d9ca20b9f7dcd9d33e4&__biz=MzI3NzIzMzg3Mw%3D%3D&mid=100000054 &idx=1#rd

  • If the last reference link opens with an error parameter, Then please copy the link and open it through QQ or wechat https://mp.weixin.qq.com/s?__biz=MzIzMzgxOTQ5NA==&mid=100000199&idx=1&sn=1e9006f2289cdfb612f22e9f6b7b44cb&chksm=68fe9dce 5f8914d8ba791b26ae6de6742686dc660db0f38a67c41ed87c942cbe679f26a4b24c#rd


# # # tail

What the heart wants, it never does. Living like a rear-guard, a reed sails. One day, has been refined, then into steel.