线程局部变量
Java中用hashtable实现
<figcaption></figcaption>
<figcaption></figcaption>
ThreadLocal<T>
initialValue
set
get
remove
复制代码
<figcaption></figcaption>
<figcaption></figcaption>
<figcaption></figcaption>
<figcaption></figcaption>
并发测试
ab -n 10000 -c 100 url
Java
synchronized 排队,解决线程安全问题 排队操作很危险,可能导致队列崩了,大大减少了吞吐量 用ThreadLocal很快,但是要考虑数据收集的问题
一个例子
package com.example.demo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashSet;
@RestController
public class StatController {
static HashSet<Val<Integer>> set = new HashSet<>();
static synchronized void addSet(Val<Integer> v) {
set.add(v);
}
static ThreadLocal<Val<Integer>> c = new ThreadLocal<>() {
@Override
protected Val<Integer> initialValue() {
Val<Integer> v = new Val<>();
v.set(0);
addSet(v);
return v;
}
};
void __add() {
Val<Integer> v = c.get();
v.set(v.get()+1);
}
@RequestMapping("/")
public Integer get() {
return set.stream().map(x -> x.get()).reduce((a,b) -> a+b).get();
}
@RequestMapping("/add")
public Integer add() {
__add();
return 1;
}
}
复制代码
网友评论