Java Concurrency (D): how to ensure the security thread object

01, Introduction

Let me spit a heart and soul of it, do not say it Biechu internal injuries. "Java Concurrency in combat," This book Tete what boring, even though it is regarded as concurrent programming classic, but I can not help. Because Chapter IV "composite object" I ate a whole two weeks, eating only point out the pork.

Readers will forgive me ah. I limited myself to blame blame the ability to learn, you really can not read this book blunt boring technology. But in order to learn, to progress, to the future (shouting slogans bit bigger), only bite the bullet.

Please come with me, I try to write interesting point.

02, thread-safe class

The authors say, ah, designing a thread-safe class requires three steps:

1) identify the object that represents the state of all variables
2) the effectiveness of variables constraint
3) concurrent access policies to increase class

I do fine-tuning on the basis of the saying, read more easily understood. And how the codes are associated with, first look at a conventional counter type Counter.

public class Counter {
    private int value = 0;

    public int getValue() {
        return value;
    }

    public int increment() {
        return ++value;
    }
}

1) Counter state variable is only one, is the value.

What validity 2) value is it, it can not exceed the maximum Integer.MAX_VALUE, minimum can only be 0 (count Well, I can not remember to negative). In other words, the effective value range of 0 to Integer.MAX_VALUE.

public int increment() {
    if (value == Integer.MAX_VALUE) {
        throw new IllegalStateException("counter overflow");
    }
    return ++value;
}

3) increase concurrent access policy class directly on synchronized.

public class Counter {
    private int value = 0;

    public synchronized int getValue() {
        return value;
    }

    public synchronized int increment() {
        if (value == Integer.MAX_VALUE) {
            throw new IllegalStateException("counter overflow");
        }
        return ++value;
    }
}

03, non-thread-safe objects

Before we talk about how to design a thread-safe class. If the class is safe, then it is used as an object to use thread-safe. But if a class is not thread-safe, it is used as objects used how guaranteed to be thread safe?

Author mentions a term called "closed mechanism":

1) the object as a private member variable classes;
2) inside the object as a method of local variables;
3) Thread A Thread B to pass an object, the object is not shared with the thread B;

Look at the following code.

class StringList {
    private List<String> myList = new ArrayList<>();
    
    public synchronized void addString(String s) {
        myList.add(s);
    }
    
    public synchronized void removeString(String s) {
        myList.remove(s);
    }
}

ArrayList itself is not thread-safe, but myList is private, its two access methods addString()and removeString()have added a keyword synchronized, therefore myList when in use becomes a thread-safe objects, StringList class becomes a thread-safe class - in this way is called Java monitor mode: a state variable is encapsulated in a class, they can only be accessed by the method of adding the lock.

View source Vector, and you will find that reason it is thread-safe, the monitor mode is used

04, additional features on an existing thread-safe classes

If now there is a thread-safe class, such as the previously mentioned StringList, it contains most of the features we need, but not enough, how to make sure we do not destroy the function added to the original thread safety of it?

The most direct way is to modify the source code, if the source lies in our own hands, then.

class StringList {
    private List<String> myList = new ArrayList<>();
    
    public synchronized void addString(String s) {
        myList.add(s);
    }
    
    public synchronized void addIfNotExist(String s) {
        boolean isExist = myList.contains(s);
        if (!isExist) {
            myList.add(s);
        }
    }
}

We've added a addIfNotExist()method: If the string s has not added to the List of them, you add one.

The new method does not destroy StringList thread safety, because when two threads execute simultaneously addIfNotExist()while method, need to go through synchronizedguarded gates of this road.

But very often, we can not directly modify the source code, this time had to be modified on the basis of the original. We heard of "red chip" browser before you? On the Google browser core wrapped with layers emperor's new clothes.

class StringList {
    protected List<String> myList = new ArrayList<>();
    
    public synchronized void addString(String s) {
        myList.add(s);
    }
}

public class NewStringList extends StringList {
    public synchronized void addIfNotExist(String s) {
        boolean isExist = myList.contains(s);
        if (!isExist) {
            myList.add(s);
        }
    }
}

Create a new class NewStringList, inherited from StringList, then add a method in NewStringList in addIfNotExist(). Of course, this assumes that the parent class myList is protected rather than private. Therefore, this approach does not have universal.

05, finally

Standing in my point of view, Chapter IV "Java Concurrency in combat" and "combination of objects" written sucks. It led me to write this article when feel extreme pain. I do not want to write the next chapter so bad.

Previous: the Java Concurrent Programming (C): how to ensure the visibility of shared variables?

On Part I: the Java Concurrent Programming (2): The security thread

On the Part: the Java concurrent programming (a): Threshold

Thank you for reading, originality is not easy, like to point a praise, this will be my strongest writing power. If you think the article for your help, but also quite interesting, micro-channel search on " silent king, " replies attention after the keyword "Java Concurrency in combat", you can get an electronic version of the book (recommended buying paper books ).

Guess you like

Origin www.cnblogs.com/qing-gee/p/11802921.html