|
| 1 | +/* |
| 2 | + * Copyright 2019 Google LLC |
| 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 | + |
| 17 | +// [START functions_tips_scopes] |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.io.PrintWriter; |
| 21 | +import java.util.Arrays; |
| 22 | +import javax.servlet.http.HttpServletRequest; |
| 23 | +import javax.servlet.http.HttpServletResponse; |
| 24 | + |
| 25 | +public class Scopes { |
| 26 | + // Global (instance-wide) scope |
| 27 | + // This computation runs at instance cold-start. |
| 28 | + // Warning: Class variables used in Servlet classes must be thread-safe, |
| 29 | + // or else might introduce race conditions in your code. |
| 30 | + private static final int InstanceVar = heavyComputation(); |
| 31 | + |
| 32 | + public void scopeDemo(HttpServletRequest request, HttpServletResponse response) |
| 33 | + throws IOException { |
| 34 | + // Per-function scope |
| 35 | + // This computation runs every time this function is called |
| 36 | + int functionVar = lightComputation(); |
| 37 | + |
| 38 | + PrintWriter writer = response.getWriter(); |
| 39 | + writer.write(String.format("Instance: %s; function: %s", InstanceVar, functionVar)); |
| 40 | + } |
| 41 | + |
| 42 | + private static int lightComputation() { |
| 43 | + int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; |
| 44 | + return Arrays.stream(numbers).sum(); |
| 45 | + } |
| 46 | + |
| 47 | + private static int heavyComputation() { |
| 48 | + int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; |
| 49 | + return Arrays.stream(numbers).reduce((t, x) -> t * x).getAsInt(); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +// [END functions_tips_scopes] |
0 commit comments