diff --git a/multithreading1/src/main/java/cn/bunny/jmh/JMHExample16.java b/multithreading1/src/main/java/cn/bunny/jmh/JMHExample16.java new file mode 100644 index 0000000..1a5d4c4 --- /dev/null +++ b/multithreading1/src/main/java/cn/bunny/jmh/JMHExample16.java @@ -0,0 +1,66 @@ +package cn.bunny.jmh; + +import org.openjdk.jmh.annotations.*; +import org.openjdk.jmh.runner.Runner; +import org.openjdk.jmh.runner.RunnerException; +import org.openjdk.jmh.runner.options.Options; +import org.openjdk.jmh.runner.options.OptionsBuilder; + +import java.util.*; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentSkipListMap; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.AverageTime) +@Fork(1) +@Warmup(iterations = 5) +@Measurement(iterations = 5) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@State(Scope.Group) +public class JMHExample16 { + // 为type提供了4中可配置的参数值 + @Param({"1", "2", "3", "4"}) + private int type; + + private Map map; + + public static void main(String[] args) throws RunnerException { + Options options = new OptionsBuilder() + .include(JMHExample16.class.getSimpleName()) + .build(); + new Runner(options).run(); + } + + @Setup + public void setup() { + switch (type) { + case 1: + this.map = new ConcurrentHashMap<>(); + break; + case 2: + this.map = new ConcurrentSkipListMap<>(); + break; + case 3: + this.map = new Hashtable<>(); + break; + case 4: + this.map = Collections.synchronizedMap(new HashMap<>()); + break; + default: + throw new IllegalArgumentException("Illegal map type"); + } + } + + @Group("g") + @GroupThreads(5) + @Benchmark + public void put() { + int num = new Random().nextInt(); + this.map.put(num, num); + } + + public Integer get() { + int num = new Random().nextInt(); + return this.map.get(num); + } +}