Skip to content

feat: Add GCF Java Tips #1550

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions functions/snippets/src/main/java/Tips.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// [START functions_tips_scopes]
// [START run_tips_global_scope]

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Tips {
// Global (instance-wide) scope
// This computation runs at instance cold-start
public static final int INSTANCE_VAR = heavyComputation();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Class variables should be declared at the top of the class.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also, this might not be the way we want to showcase this. Normally, global variables aren't used with servlets due to issues with thread-safety. This example is probably okay because it's a final variable, but we probably either want to add a warning or (better yet) update the example to us a ServletContextListener for creating start up resources.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved to the very top. Not sure if we need the context listener.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It should be updated to either use a ContextListener, or include a warning that global values in Servlets are not threadsafe, and a ContextListener is preferred for mutable variables.

I'm not really sure if/how a ContextListener would work with functions, so this snippet might be a good example to showcase that pattern as well.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really know how to proceed. Do you think that GCF will use multiple threads per Function invocation?

This example is probably okay because it's a final variable

Since this is a final variable, isn't it safe to access across multiple threads?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Most servlet environments will use multiple threads to handle requests, so

Do you think that GCF will use multiple threads per Function invocation?

I don't know how GCF handles things, but it would be idiomatic to Java to remain threadsafe when using Servlets since other runtimes may use multiple threads.

Since this is a final variable, isn't it safe to access across multiple threads?

I should have been more clear - since this is a final and a primitive it's immutable, and thus thread-safe. However, we should either point out why this is okay, or show the user how to handle these properly. If the user tried to do this with an object that isn't thread-safe (even if it's final), they'll run into issues.


public void scopesDemo(HttpServletRequest request, HttpServletResponse response)
throws IOException, InterruptedException {
// Per-function scope
// This computation runs every time this function is called
final int functionVar = lightComputation();
PrintWriter writer = response.getWriter();
writer.write(String.format("Per instance: %d, per function: %d", INSTANCE_VAR, functionVar));
}
// [END functions_tips_scopes]
// [END run_tips_global_scope]

private static int lightComputation() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These functions are still excluded, which means that this snippet isn't copy-paste-runnable (see the Sample Format Guidelines). Older samples might not be following the format, but we are trying to keep all new samples following the guidelines.

Also, both functions are exactly the same, which makes it a bit confusing to understand when reading. Perhaps it would be better to replace this with something like this:

   // This function represents a heavy computation, which is only called when the instance starts.
   private static int heavyComputation() {
    TimeUnit.SECONDS.sleep(3);
    return System.currentTimeMillis();
  }

   // This function represents a light computation, which might be called on every incoming request.
   private static int lightComputation() {
    TimeUnit.SECONDS.sleep(0);
    return System.currentTimeMillis();
  }

Copy link
Contributor Author

@grant grant Sep 6, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • These functions are excluded like they are in the Node sample.

Also, both functions are exactly the same

  • These functions are not exactly the same. They are modeled after Node.

https://github.com/GoogleCloudPlatform/nodejs-docs-samples/blob/4b2629e759eba9cf7d89aed3302bcf2795e1eecf/functions/tips/index.js#L18

What would you like us to do?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • These functions are excluded like they are in the Node sample.

I believe that the node repo has a similar policy regarding copy-paste-runnable (since it's borrowed from the overarching Code Snippets Rubric). It looks like these samples probably predate this policy, but I don't know how the node repo is enforcing those rules.

Currently, the java-docs-samples policy is that new samples should follow the guidelines, while minor updates to existing samples can be grandfathered in. Since these samples are new, they need to follow the guidelines and include these functions so that users can copy them, paste them, and run them without having to fill out these functions.

  • These functions are not exactly the same.

This is my bad, the version I was looking at shows them both using addition, but I can see at HEAD they are different.

At the very least, this version of the sample should contain the comments I posted above. (My two cents is still that the intent of the sample is significantly more clear when using sleep, because the user can see that the difference between running those functions is non-trivial. However if you strongly prefer to remain consistent with the Node version, I'm satisfied with the comments clarifying above)

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
return numbers.stream().reduce((t, x) -> t + x).get();
}

private static int heavyComputation() {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
return numbers.stream().reduce((t, x) -> t * x).get();
}

// [START functions_tips_scopes]
// [START run_tips_global_scope]
}

// [END functions_tips_scopes]
// [END run_tips_global_scope]

8 changes: 7 additions & 1 deletion functions/snippets/src/test/java/SnippetsTests.java
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,13 @@ public void helloBackgroundTest() throws IOException {
when(request.getReader()).thenReturn(bodyReader);

new HelloBackground().helloBackground(request, response);
assertThat(responseOut.toString(), containsString("Hello John!"));
assertThat(responseOut.toString(), containsString("Hello John!"));
}

@Test
public void scopesDemoTest() throws IOException, InterruptedException {
new Tips().scopesDemo(request, response);
assertThat(responseOut.toString(), containsString("Per instance: 362880, per function: 45"));
}

@Test
Expand Down