在多线程环境下,对共享资源的修改,是一定要加锁的。
但是在高并发的环境下,锁竞争的代价非常高.
一些针对共享资源的修改,过程非常短暂,可以考虑使用串行化,适当限制并发
同时也避免了死锁的风险.
实验模拟了一个场景
一个Servlet要统计访问的总数,并且访问数据库获取数据.
常规的方式如下
![](/attachment/201509/17/29254281_1442495422T2in.png)
针对共享资源的修改,可以使用串行的方式,之后访问数据库等操作,还是以多线程的方式运行。
![](/attachment/201509/17/29254281_1442495481qJB6.png)
样例代码如下:
但是在高并发的环境下,锁竞争的代价非常高.
一些针对共享资源的修改,过程非常短暂,可以考虑使用串行化,适当限制并发
同时也避免了死锁的风险.
实验模拟了一个场景
一个Servlet要统计访问的总数,并且访问数据库获取数据.
常规的方式如下
![](/attachment/201509/17/29254281_1442495422T2in.png)
针对共享资源的修改,可以使用串行的方式,之后访问数据库等操作,还是以多线程的方式运行。
![](/attachment/201509/17/29254281_1442495481qJB6.png)
样例代码如下:
- 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() {
- }
-
- }
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29254281/viewspace-1802576/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/29254281/viewspace-1802576/