DoPrivilegedBenchmark.java revision 5a7833b406bb2716b057d3ed923f22f1f86b2a20
1/*
2 * Copyright (C) 2010 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 */
16
17package benchmarks.regression;
18
19import com.google.caliper.Param;
20import com.google.caliper.Runner;
21import com.google.caliper.SimpleBenchmark;
22import java.security.AccessController;
23import java.security.PrivilegedAction;
24
25public class DoPrivilegedBenchmark extends SimpleBenchmark {
26    public void timeDirect(int reps) throws Exception {
27        for (int i = 0; i < reps; ++i) {
28            String lineSeparator = System.getProperty("line.separator");
29        }
30    }
31
32    public void timeFastAndSlow(int reps) throws Exception {
33        for (int i = 0; i < reps; ++i) {
34            String lineSeparator;
35            if (System.getSecurityManager() == null) {
36                lineSeparator = System.getProperty("line.separator");
37            } else {
38                lineSeparator = AccessController.doPrivileged(new PrivilegedAction<String>() {
39                    public String run() {
40                        return System.getProperty("line.separator");
41                    }
42                });
43            }
44        }
45    }
46
47    public void timeNewAction(int reps) throws Exception {
48        for (int i = 0; i < reps; ++i) {
49            String lineSeparator = AccessController.doPrivileged(new PrivilegedAction<String>() {
50                public String run() {
51                    return System.getProperty("line.separator");
52                }
53            });
54        }
55    }
56
57    public void timeReusedAction(int reps) throws Exception {
58        final PrivilegedAction<String> action = new ReusableAction("line.separator");
59        for (int i = 0; i < reps; ++i) {
60            String lineSeparator = AccessController.doPrivileged(action);
61        }
62    }
63
64    private static final class ReusableAction implements PrivilegedAction<String> {
65        private final String propertyName;
66
67        public ReusableAction(String propertyName) {
68            this.propertyName = propertyName;
69        }
70
71        public String run() {
72            return System.getProperty(propertyName);
73        }
74    }
75}
76