Face questions about the synchronized

During the interview process, we often will be investigated multi-threading problems. Although easy to use multi-threading, but if used improperly will bring a lot of concurrency issues. How to ensure the security thread is naturally not open around the topic.

Recently the company to Careers in the interview process, I found that everyone knows synchronized keyword is used to thread synchronization, thread-safe guarantee. But then it goes on to talk in depth, it is easy to fall into an embarrassing situation. I can only say "change the subject" politely, or "today to talk to here" ... (PS: I too will not be installed on 13 of it but are generally 5+ resume work experience?)

2020 is bound to be an extraordinary year. During a time when the epidemic, every interview is particularly important. So specifically taking the time to write this article, hoping to find work to help each interviewer favorite.

Introduction 1. synchronized in

synchronized understood to be locked , but not locked, thinking this will help you better understand the thread synchronization.

Use 1.1 synchronized and their respective lock objects

Here is a brief introduction, to do something to pave the way for the future of content:

  1. Common methods: the lock object is this, a so-called method of lock (lock essentially belong to the object)
public synchronized void say(){
	 System.out.println("Hello,everyone...");
}
  1. Sync block ( process ): the lock object is an object synchronized (obj), the so-called object lock
 public  void say(boolean isYou){
        synchronized (obj){
            System.out.println("Hello");
        }
    }
  1. Synchronized static method: the lock object is the current class Class object, i.e. (XXX.class), a so-called class lock
 public static synchronized void work(){
        System.out.println("Work hard...");
    }

I hope we meet again the object lock , like lock and at a loss ... sometimes encountered when the interviewer description of the problem was unclear, the interviewer must have the courage and timely communication. While there will always be wonderful to find a job interviewer, but if you encounter probability is too high, please consciously look at their ...


Questions about 1.2 synchronized code block

See above synchronized usage, you have such questions? synchronized can modify the class level (static) code block it? (PS: This is a topic I think the interim, another day to ask in the interview to see the effect ...)

Conclusion: synchronized can not be used at the class level (static) block

If you do not give in an interview compiler, most estimates are to mountain Tai Bar. Here we are given directly to my understanding:

Consider this from the load order.
Class-level code block on the loading order of priority in any of the methods which the execution order has related only with code location. No one told you to grab, nature does not require synchronization.


2. face questions involving synchronized

Here by a common interview questions - Singleton to expand, the main content of this article is to investigate the synchronized keyword, it goes straight into the DCL (Double Check Lock) and double check the lock singleton.

2.1 DCL around the topic of expansion
2.1.1 achieve DCL

If this can not step on too, embarrassing endless friends ...

public class SingleInstance {
    private volatile static SingleInstance instance = null;
    private SingleInstance(){ }
    public static SingleInstance getInstance(){
        if (instance == null){
            synchronized (SingleInstance.class){
                if (instance == null){
                    instance = new SingleInstance();
                }
            }
        }
        return instance;
    }
}
2.1.2 to talk about the role of synchronized

synchronized keyword is mainly used to solve the multi-thread synchronization problems, which can ensure that only one thread executes the code at any time it is modified. As the case may be, (the initiative) say its usage and the principle underlying implementation (using moniterenter and moniterexit instructions ...), PS: the underlying principles of synchronized implementation will start alone ...

2.1.3 role here (DCL) of the volatile

volatile variables can ensure visibility, and can not guarantee the atomicity of operations on the volatile variables.

volatile main role:

  1. Maintaining visibility of memory; so that all threads can see the latest status of shared memory.
  2. Prevent problems rearranged instructions;

By setting memory barrier to achieve. Interested can take a look in-depth understanding of the Java Virtual Machine

Personal humble opinion, to answer them to the contents of the above, the vast majority are in deeper SHOW or just press the salary ...

2.2 basis points interview

To save time you Tell me, the first conclusion to come out:

  1. If the object lock, then each object to hold a own unique lock and the lock between objects independently of each other. If the class locks, all such objects sharing the lock.
  2. A thread obtains a lock, not only lock the thread waiting;
  3. reentrant lock is synchronized, in many cases to avoid deadlock occurs.
  4. synchronized method if an exception occurs, the JVM will automatically release the lock.
  5. Lock object can not be null, or throw NPE (NullPointerException)
  6. Synchronize itself does not have inheritance: the synchronized method of the parent class, subclass overrides this method, with different situations: no synchonized modification, the sub-category method is not thread synchronization. (PS: synchronization issues related to inheritance Points)
  7. synchronized itself modified range as small as possible. After all, it is synchronous blocking. Run faster also occupied the passing lane ...

2.2.1 synchronized simultaneous access of static and non-static methods, to ensure thread safe?

Conclusion: No, the two are not the same lock object. The former class is locked (XXX.class), this latter

2.2.2 accessed simultaneously synchronized and non-synchronized method approach to ensure thread-safe?

Conclusion: You can not, because the synchronized only act on the modified method.

2.2.3 The two threads simultaneously access two objects non-static method to ensure synchronous thread-safe?

Conclusion: No, each object has a lock. Two objects have the equivalent of two locks, leading to inconsistent lock object. (PS: If the class is locked, a lock common to all of the objects)

2.2.4 If the synchronized method throws an exception, it will lead to a deadlock?

JVM will automatically release the lock, does not lead to deadlock

2.2.5 If the synchronized lock object is able to empty it? What happens?

Lock object can not be null, or throw NPE (NullPointerException)

2.2.6 If the synchronized lock object is able to empty it? What happens?

Lock object can not be null, or throw NPE (NullPointerException)


Interview 2.3 points on inheritance

2.3.1 synchronized inheritance issues involved

Synchronized method overrides the parent class is mainly divided into two cases:

  1. Subclass are not synchronized modification:

synchronized does not have inheritance. So subclass method is thread safe.

  1. Sub-category method is modified synchronized (mainly on the ownership of the pilot lock object there):

Two lock object is actually a lock, and a subclass object as a lock . This also proves that: synchronized locks are reentrant lock. Otherwise, the deadlock will occur.

2.4 hands-on experience of the interview point

2.4.1 In the development process, you synchronized method or synchronized block of code and more frequently used? and why?

About synchronized content part, I often asked during the interview and only ask the questions. I think that this can be a good study of the overall quality of the interviewer. (PS: after all, is to tighten the screws ...)

synchronized synchronous range is as small as possible. Because if the process takes a long time, and that other threads must wait until the lock holding the thread executing the order to run. (Day lily is cold all ...)
and synchronized block only part of this section are synchronized, the other can still asynchronous execution, improve operational efficiency.

2.4.2 Please write an example of a deadlock

Here to give you a reference: I have a story, you have wine?

public class DeadLock {
    String story = "故事";
    String wine = "酒";

    public  void wantWine() throws InterruptedException {
        synchronized (story){
            System.out.println("已经拥有:"+ story +"就缺:"+ wine);
            Thread.sleep(1000);
            synchronized (wine){
                System.out.println("拥有:"+ wine);
            }
        }
    }

    public void wantStory() throws InterruptedException {
        synchronized (wine){
            System.out.println("已经拥有:"+ wine +"就缺:"+ story);
            Thread.sleep(1000);
            synchronized (story){
                System.out.println("拥有:"+ story);
            }
        }
    }

    public static void main(String[] args) {
        DeadLock deadLock = new DeadLock();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    deadLock.wantWine();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    deadLock.wantStory();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

2.4.2 have not encountered problems synchronized failure?

For this question is asked, it is to investigate the interviewer experience in the actual development of whether the rich ... can truthfully answer.

Although synchronized it is easy to use, but if the lock object is inconsistent, it will fail. Troubleshoot when we must focus from whether the object is consistent lock up the judgment.

Careful readers will notice that the net XC, there's no analysis of the principle of synchronized, and when JDK1.6, Java synchronized optimized for official did not mention. Do not worry, the follow-up to add ...

Published 23 original articles · won praise 14 · views 90000 +

Guess you like

Origin blog.csdn.net/wangcheeng/article/details/104753168