Spring MVC的Controller是线程安全的么

如题所述

默认线程不安全。

Spring MVC默认注册bean都是单例模式,即:@Scope("singleton"),所有线程调用的都是同一个实例对象,所以线程不安全。不过可以手动指定javabean的scope为多例,即:@Scope("prototype"),每个线程调用都会重新实例化一个对象,这样就线程安全了。

1
2
3
4
5
6

@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserController {
// ...
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2017-06-16
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 package test; import java.util.HashMap; import java.util.Hashtable; import java.util.concurrent.CountDownLatch; public class HashTbAndHashMap { public static void main(String[] args) { for (int i = 0; i < 10; i++) { //testHashMap(); testHashTable(); } } public static void testHashMap() { HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); int nbthread = 1000; CountDownLatch countDownLatch = new CountDownLatch(nbthread); for (int i = 0; i < nbthread; i++) { Thread thread = new Thread(new MyThread(map, countDownLatch)); thread.start(); } try { countDownLatch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(map.size()); } public static void testHashTable() { Hashtable<Integer, Integer> table = new Hashtable<Integer, Integer>(); int nbthread = 1000; CountDownLatch countDownLatch = new CountDownLatch(nbthread); for (int i = 0; i < nbthread; i++) { Thread thread = new Thread(new MyThread(table, countDownLatch)); thread.start(); } try { countDownLatch.await(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(table.size()); } } ======================= package test; import java.util.HashMap; import java.util.Hashtable; import java.util.concurrent.CountDownLatch; public class MyThread implements Runnable { private HashMap<Integer, Integer> map; private Hashtable<Integer, Integer> table; private CountDownLatch countDownLatch; public MyThread(HashMap<Integer, Integer> map, CountDownLatch countDownLatch) { this.map = map; this.countDownLatch = countDownLatch; } public MyThread(Hashtable<Integer, Integer> table, CountDownLatch countDownLatch) { this.table = table; this.countDownLatch = countDownLatch; } @Override public void run() { for (int i = 0; i < 100; i++) { table.put(i, i); //map.put(i, i); } countDownLatch.countDown(); } } 你执行一下就看出来区别了

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网