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