1. Concurrency security issues in JDK

If you are in a traditional industry, you may not be concerned about concurrency security. If you are developing OA, CRM, etc., these systems may not have a lot of traffic, and even if your code has a concurrency vulnerability, you may not find it.

So, the best way to talk about concurrency security is not to start with a solution, but to start over

2. Re-enact the scene


Before we discuss the concurrency security solution, let’s re-create the problem

Looking at the diagram above, to create concurrency security issues, several things should happen at the same time:

  1. There are many users (concurrent scenario)

  2. Perform operations on the same shared resource

2.1. Concurrent recurrence

OrderNumGenerator generates the order ID, while FileID. nextId writes to a file, fetches the latest number in the file, and then +1 writes to the original file and returns the data.

Here are the test classes

Simulate 50 concurrent orders, generate order ids at the same time, sort and see the output result

You can see that there is a lot of duplication in the end result, which could be a serious problem in a real project

3. Use the Synchronized solution

3.1. Solution principle


3.2. Resolution code

package cn.enjoy.syn;

import java.text.SimpleDateFormat;

import java.util.Date;

public class OrderNumGenerator {

// Global order ID

public static int count = 0;

public static Object lock = new Object();

public String getNumber(a) {

synchronized(lock){

SimpleDateFormat simpt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

return simpt.format(new Date()) + "-" + ++count/+"_"+Thread.currentThread().getId()/; }}}Copy the code

Lock solutions

4.1. Solution principle

4.2. Resolution code

package cn.enjoy.lock;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.concurrent.locks.ReentrantLock;

public class OrderNumGenerator {

// Global order ID

public static int count = 0;

private java.util.concurrent.locks.Lock lock = new ReentrantLock();

// Solve the problem in lock mode

public String getNumber(a) {

try {

lock.lock();

SimpleDateFormat simpt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

String s = simpt.format(new Date()) + "-" + ++count;

return s;

}finally{ lock.unlock(); }}}Copy the code

5. Talk about an interview question

Synchronized and Lock both address concurrency security issues, but what are the differences?

The Lock interface provides a more extensible locking operation than synchronized methods and synchronized blocks.

They allow for more flexible structures that can have radically different properties, and can support conditional objects of multiple related classes.

It has the following advantages: it can make locks fairer, it can make threads respond to interrupts while waiting for locks, it can make threads try to acquire locks and immediately return or wait for a period of time when the locks cannot be acquired, and it can acquire and release locks in different ranges and in different sequences.

Lock is generally an extension of synchronized, Lock provides unconditional, pollable (tryLock method), timed (tryLock parameterized method), interruptibly (lockInterruptibly), and multi-conditional queued (newCondition method) Lock operations. In addition, Lock implementation classes basically support unfair Lock (default) and fair Lock, synchronized only supports unfair Lock, of course, in most cases, unfair Lock is an efficient choice.

Through these descriptions, the differences are summarized as follows:

  1. Lock provides more flexibility

  2. Lock implements the function of fair Lock, as shown in the following figure

6. Summary

In fact, concurrency security is not complicated to solve, the problem is difficult to find this problem, if you do not pay attention to this problem, it may be correct in most cases during the project operation, but if there is a concurrency security problem, it may be a great loss.

Now we’re talking about concurrency security under a single node (a SINGLE JVM), but new issues can arise in distributed scenarios. What are the issues here?