但是在高并发的环境下,锁竞争的代价非常高.
一些针对共享资源的修改,过程非常短暂,可以考虑使用串行化,适当限制并发
同时也避免了死锁的风险.
实验模拟了一个场景
一个Servlet要统计访问的总数,并且访问数据库获取数据.
常规的方式如下
针对共享资源的修改,可以使用串行的方式,之后访问数据库等操作,还是以多线程的方式运行。
样例代码如下:
-
import java.io.IOException;
-
import java.util.concurrent.Callable;
-
import java.util.concurrent.ExecutionException;
-
import java.util.concurrent.Executors;
-
import java.util.concurrent.Future;
-
import java.util.concurrent.FutureTask;
-
import java.util.concurrent.LinkedBlockingQueue;
-
-
import javax.servlet.ServletException;
-
import javax.servlet.annotation.WebServlet;
-
import javax.servlet.http.HttpServlet;
-
import javax.servlet.http.HttpServletRequest;
-
import javax.servlet.http.HttpServletResponse;
-
-
/**
-
* Servlet implementation class CharsetTest
-
*/
-
@WebServlet("/CharsetTest")
-
public class CharsetTest extends HttpServlet {
-
-
int count = 0;
-
private LinkedBlockingQueue<FutureTask<Integer>> q = new LinkedBlockingQueue<FutureTask<Integer>>();
-
-
{
-
Executors.newSingleThreadExecutor().submit(new Runnable() {
-
-
@Override
-
public void run() {
-
FutureTask futureTask;
-
try {
-
while ((futureTask = q.take()) != null) {
-
futureTask.run();
-
}
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
}
-
-
}
-
-
});
-
}
-
-
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
-
int current = -1;
-
Callable<Integer> c = new Callable<Integer>() {
-
@Override
-
public Integer call() throws Exception {
-
count++;
-
return count;
-
}
-
};
-
FutureTask<Integer> f = new FutureTask<Integer>(c);
-
try {
-
q.put(f);
-
current = f.get();
-
} catch (InterruptedException e) {
-
e.printStackTrace();
-
} catch (ExecutionException e) {
-
e.printStackTrace();
-
}
-
dbSelect();
-
System.out.println(current);
-
}
-
-
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
-
IOException {
-
doGet(request, response);
-
}
-
-
private void dbSelect() {
-
}
-
- }