java multithreading, seek death levels & brain-dead level

Many java developers are new to multi-threaded development. But even experienced developers will fall into many 多线程traps. In this part, basically a number of counter-examples, but some very low-level common. When your program does not have appropriate expectations, I hope this article will help you understand the subtleties of them.

Of course, used the interview with the loading force, also excellent.

First to 10.

I used to evaluate a level

Death-defying create a thread pool

Phenomenon: the exhaustion of system resources, process dead.

The reason: the implementation of each method are a new thread pool. Sample code.

Little sister flavor solution: to share a thread pool.

Seek death rating: five stars

Brain damage rating: five stars

void doJob(){
    ThreadPoolExecutor exe = new ThreadPoolExecutor(...);
    exe.submit(new Runnable(){...})
}
复制代码

Lock leak

Phenomenon: a thread has been held without releasing the lock, the lock causing leakage.

Cause: unknown cause abnormal or unlock logic function is not performed.

Little sister flavor Solution: Always unlock function finally put in.

Seek death Rating: Three stars

Brain-dead Rating: Four stars

private final Lock lock = new ReentrantLock();
void doJob(){
    try{
        lock.lock();
        //do. sth
        lock.unlock();
    }catch(Exception e){
    }
}
复制代码

Forget synchronous variable

Phenomenon: Under certain conditions, throws IllegalMonitorStateException.

The reason: call wait, notify, etc., forget synchronized, or sync the wrong variable.

Little sister flavor solution: before calling these functions, it is to be synchronized keyword synchronized.

Seek death Rating: two stars

Brain-dead Rating: Four stars

Object condition = new Object();

condition.wait();
复制代码

HashMap infinite loop

Phenomenon: cpu occupancy high, the occurrence of an infinite loop, use jstack view is blocked on the get method.

Reason: under certain conditions, when the rehash, form an endless chain. Some get request will come on this ring.

Little sister taste solutions: multi-threaded environment, the use of ConcurrentHashMap, do not hesitate.

Seek death Rating: Four stars

Brain-dead Rating: Four stars

Reassigned to the variable synchronization

Phenomenon: not able to achieve synchronization effect, the result is wrong.

The reason: non-basic types are reassigned, will change the lock point, lock held by different threads may be different.

Little sister flavor solution: the lock object type is declared as final.

Seek death Rating: Four stars

Brain-dead Rating: Three stars

List listeners = new ArrayList();

void add(Listener listener, boolean upsert){
    synchronized(listeners){
        List results = new ArrayList();
        for(Listener ler:listeners){
        ...
        }
        listeners = results;
    }
}
复制代码

Thread loop uncaught exception

Phenomenon: the thread job can not continue to run unknown terminated.

Reason: The abnormal cycle is not trapped, causing the thread exits.

Little sister flavor solution: habitual catch all exceptions.

Seek death Rating: Three stars

Brain-dead Rating: Three stars

volatile boolean run = true;
void loop(){
    while(run){
        //do . sth
        int a = 1/0;
    }
}
复制代码

volatile mistaken for counter

Phenomenon: Multi-thread count was made in error.

The reason: volatile to ensure the visibility, does not guarantee atomicity, multithreading and can not guarantee its accuracy.

Little sister flavor solution: direct use of Atomic class.

Seek death Rating: Three stars

Brain damage rating: two stars

volatile count = 0;
void add(){
    ++count;
}
复制代码

Error protection range

Phenomenon: Although the collection of thread-safe, but not reach the synchronization effect.

Cause: The operation to modify a set of multiple thread-safe, but the operation itself is not atoms.

Little sister flavor Solution: figure out the code to be protected logical domains.

Seek death Rating: Three stars

Brain-dead Rating: Four stars

private final ConcurrentHashMap<String,Integer> nameToNumber;
private final ConcurrentHashMap<Integer,Salary> numberToSalary;
public int geBonusFor(String name) {
    Integer serialNum = nameToNumber.get(name);
    Salary salary = numberToSalary.get(serialNum);
    return salary.getBonus();
}
复制代码

Another example is the following error code.

Map<String, String> map = Collections.synchronizedMap(new HashMap<String, String>());

if(!map.containsKey("foo"))
    map.put("foo", "bar");
复制代码

Some of the old date processing class

Phenomenon: use the global Calendar, SimpleDateFormat date handling, etc., abnormal or inaccurate data.

The reason: maybe things are not thread-safe, concurrent calls there will be problems.

Little sister flavor solution: put ThreadLocal, it is recommended to use DateTimeFormatter thread-safe.

Seek death levels: a star

Brain damage rating: one star

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

Date dododo(String str){
    return format(str);
}
复制代码

Code deadlock

Phenomenon: Code deadlock and wait for each other.

Reason: the code satisfies the following four conditions: exclusive; inalienable; request and holding; wait cycles.

Little sister flavor solution: destruction of these four conditions. Or less synchronized.

Seek death Rating: two stars

Brain damage rating: one star

Here is a simple deadlock code.

final Object lock1 = new Object();
final Object lock2 = new Object();
new Thread(new Runnable() {
    @Override
    public void run() {
        sleep(1000);
        synchronized (lock1) {
            synchronized (lock2) {
            }
        }
    }
}).start();
new Thread(new Runnable() {
    @Override
    public void run() {
        synchronized (lock2) {
            sleep(1000);
            synchronized (lock1) {
            }
        }
    }
}).start();
复制代码

long variable read an invalid value

Phenomenon: reads the value of the non-set.

The lower 32 bits of high byte and 32-bit long variable to another variable is not read atoms, may read a variable: Causes.

Little sister flavor solution: long and double variables to ensure the data is correct, you can add the volatile keyword.

Seek death levels: a star

Brain damage rating: no stars

Further reading (jdk10): docs.oracle.com/javase/spec...

End

Multithreading is its use of complex, low probability of using api error will multiply, skills requirements are also higher. Fortunately, concurrent package makes this process a lot of convenience, but problems still exist resource planning and synchronization failure. Taste a little sister here but relatively shallow comprehensive summary: JAVA multi-threaded usage scenarios and considerations simple version , but robust code also rely on your own to practice it.


More exciting articles.

"Micro service not all, only a subset of the domain-specific"

"" Sub-library sub-table "? Selection process and be careful, otherwise they will be out of control. "

So much monitoring component, there is always a right for you

"On Linux production environment, the most commonly used set of" vim "skills"

"Using Netty, in the end what we have in development? "

Five-piece like Linux.

"Linux of the" Cast Away "(a) prepare papers"

"Linux of the" Cast Away "(b) CPU articles"

"Linux of the" Cast Away "(c) Memory articles"

"Linux of the" Cast Away "(four) I / O chapter"

"Linux of the" Cast Away "(e) Network articles"

Please attention. Of course, the public may be concerned about numbers.

Guess you like

Origin juejin.im/post/5d009e4ef265da1b7152ed90