blob: 96fe5e174bd2acea4dfe02c0000cf85556c1528d [file] [log] [blame]
Paul Duffine2363012015-11-30 16:20:41 +00001/*
2 * Copyright (C) 2013 Google Inc.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package com.google.caliper.worker;
17
18import static com.google.common.base.Preconditions.checkState;
19
20import com.google.monitoring.runtime.instrumentation.Sampler;
21
22import java.util.concurrent.atomic.AtomicInteger;
23import java.util.concurrent.atomic.AtomicLong;
24
25import javax.inject.Inject;
26
27/**
28 * An {@link AllocationRecorder} that records the number and cumulative size of allocation.
29 */
30final class AggregateAllocationsRecorder extends AllocationRecorder {
31 private final AtomicInteger allocationCount = new AtomicInteger();
32 private final AtomicLong allocationSize = new AtomicLong();
33 private volatile boolean recording = false;
34
35 private final Sampler sampler = new Sampler() {
36 @Override public void sampleAllocation(int arrayCount, String desc, Object newObj,
37 long size) {
38 if (recording) {
39 allocationCount.getAndIncrement();
40 allocationSize.getAndAdd(size);
41 }
42 }
43 };
44
45 @Inject AggregateAllocationsRecorder() {
46 com.google.monitoring.runtime.instrumentation.AllocationRecorder.addSampler(sampler);
47 }
48
49 @Override protected void doStartRecording() {
50 checkState(!recording, "startRecording called, but we were already recording.");
51 allocationCount.set(0);
52 allocationSize.set(0);
53 recording = true;
54 }
55
56 @Override public AllocationStats stopRecording(int reps) {
57 checkState(recording, "stopRecording called, but we were not recording.");
58 recording = false;
59 return new AllocationStats(allocationCount.get(), allocationSize.get(), reps);
60 }
61}