diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 6457ad05ad..0006c7e041 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -24,6 +24,10 @@ updates: directory: examples/hibernate schedule: interval: daily + - package-ecosystem: gradle + directory: examples/resilience-failsafe + schedule: + interval: daily - package-ecosystem: gradle directory: examples/graal-native schedule: diff --git a/.github/workflows/examples.yml b/.github/workflows/examples.yml index d60c383461..a0d138269e 100644 --- a/.github/workflows/examples.yml +++ b/.github/workflows/examples.yml @@ -101,9 +101,12 @@ jobs: - name: Coalescing Bulkloader working-directory: examples/coalescing-bulkloader run: ./mvnw test - - name: Hibernate JCache + - name: Hibernate (jcache) working-directory: examples/hibernate run: ./gradlew build + - name: Resilience (failsafe) + working-directory: examples/resilience-failsafe + run: ./gradlew build - name: Prepare for Graal Native Image uses: ./.github/actions/run-gradle with: diff --git a/examples/graal-native/build.gradle.kts b/examples/graal-native/build.gradle.kts index a64c524b1f..8db5079265 100644 --- a/examples/graal-native/build.gradle.kts +++ b/examples/graal-native/build.gradle.kts @@ -15,8 +15,10 @@ application { mainClass = "com.github.benmanes.caffeine.examples.graalnative.Application" } -tasks.test { - useJUnitPlatform() +testing.suites { + val test by getting(JvmTestSuite::class) { + useJUnitJupiter() + } } graalvmNative { diff --git a/examples/graal-native/settings.gradle.kts b/examples/graal-native/settings.gradle.kts index ed9066c37a..5821f00348 100644 --- a/examples/graal-native/settings.gradle.kts +++ b/examples/graal-native/settings.gradle.kts @@ -4,6 +4,10 @@ pluginManagement { gradlePluginPortal() } } +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.6.0" +} + dependencyResolutionManagement { repositories { mavenCentral() diff --git a/examples/hibernate/README.md b/examples/hibernate/README.md index 1d5fcf4b3b..081cddd7a7 100644 --- a/examples/hibernate/README.md +++ b/examples/hibernate/README.md @@ -1,4 +1,4 @@ -The [Hibernate ORM] can be configured to use a [second-level cache] to reduce the number of accesses +[Hibernate] can be configured to use a [second-level cache] to reduce the number of accesses to the database by caching data in memory to be shared between sessions. In [hibernate.conf](src/main/resources/hibernate.properties) specify the JCache provider and enable @@ -29,6 +29,14 @@ caffeine.jcache { } ``` +Enable caching on the entity. + +```java +@Entity +@Cache(usage = READ_WRITE) +public class User { ... } +``` + Hibernate will then manage the cache to transparently avoid database calls. ```java @@ -41,5 +49,5 @@ sessionFactory.fromSession(session -> session.get(User.class, id)); assertThat(sessionFactory.getStatistics().getSecondLevelCacheHitCount()).isEqualTo(1); ``` -[Hibernate ORM]: https://hibernate.org/orm/ +[Hibernate]: https://hibernate.org/orm/ [second-level cache]: https://docs.jboss.org/hibernate/orm/6.3/introduction/html_single/Hibernate_Introduction.html#second-level-cache-configuration diff --git a/examples/hibernate/build.gradle.kts b/examples/hibernate/build.gradle.kts index 6409325724..d1b591a776 100644 --- a/examples/hibernate/build.gradle.kts +++ b/examples/hibernate/build.gradle.kts @@ -5,16 +5,18 @@ plugins { dependencies { implementation(libs.bundles.hibernate) + implementation(libs.bundles.log4j2) implementation(libs.caffeine) - implementation(libs.slf4j) runtimeOnly(libs.h2) testImplementation(libs.junit) testImplementation(libs.truth) } -tasks.test { - useJUnitPlatform() +testing.suites { + val test by getting(JvmTestSuite::class) { + useJUnitJupiter() + } } java.toolchain.languageVersion = JavaLanguageVersion.of( diff --git a/examples/hibernate/gradle/libs.versions.toml b/examples/hibernate/gradle/libs.versions.toml index dea1dcfdbf..0c8368b34f 100644 --- a/examples/hibernate/gradle/libs.versions.toml +++ b/examples/hibernate/gradle/libs.versions.toml @@ -3,6 +3,7 @@ caffeine = "3.1.7" h2 = "2.2.220" hibernate = "6.3.0.CR1" junit = "5.10.0" +log4j2 = "2.20.0" slf4j = "2.0.7" truth = "1.1.5" versions = "0.47.0" @@ -14,11 +15,13 @@ hibernate-core = { module = "org.hibernate.orm:hibernate-core", version.ref = "h hibernate-jcache = { module = "org.hibernate.orm:hibernate-jcache", version.ref = "hibernate" } hibernate-hikaricp = { module = "org.hibernate.orm:hibernate-hikaricp", version.ref = "hibernate" } junit = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" } -slf4j = { module = "org.slf4j:slf4j-jdk14", version.ref = "slf4j" } +log4j2-core = { module = "org.apache.logging.log4j:log4j-core", version.ref = "log4j2" } +log4j2-slf4j = { module = "org.apache.logging.log4j:log4j-slf4j-impl", version.ref = "log4j2" } truth = { module = "com.google.truth:truth", version.ref = "truth" } [bundles] hibernate = ["hibernate-core", "hibernate-jcache", "hibernate-hikaricp"] +log4j2 = ["log4j2-core", "log4j2-slf4j"] [plugins] versions = { id = "com.github.ben-manes.versions", version.ref = "versions" } diff --git a/examples/hibernate/settings.gradle.kts b/examples/hibernate/settings.gradle.kts index 643e6ce49f..6a274506d4 100644 --- a/examples/hibernate/settings.gradle.kts +++ b/examples/hibernate/settings.gradle.kts @@ -1,3 +1,7 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.6.0" +} + dependencyResolutionManagement { repositories { mavenCentral() diff --git a/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Project.java b/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Project.java index dddb42164f..83e44d7522 100644 --- a/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Project.java +++ b/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Project.java @@ -15,13 +15,10 @@ */ package com.github.benmanes.caffeine.examples.hibernate; -import static jakarta.persistence.AccessType.FIELD; import static org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE; import org.hibernate.annotations.Cache; -import jakarta.persistence.Access; -import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -31,8 +28,6 @@ * @author ben.manes@gmail.com (Ben Manes) */ @Entity -@Cacheable -@Access(FIELD) @Cache(usage = READ_WRITE) public class Project { diff --git a/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Skill.java b/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Skill.java index 4ca78ad19b..2a204d074b 100644 --- a/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Skill.java +++ b/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/Skill.java @@ -15,13 +15,10 @@ */ package com.github.benmanes.caffeine.examples.hibernate; -import static jakarta.persistence.AccessType.FIELD; import static org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE; import org.hibernate.annotations.Cache; -import jakarta.persistence.Access; -import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -30,8 +27,6 @@ * @author ben.manes@gmail.com (Ben Manes) */ @Entity -@Cacheable -@Access(FIELD) @Cache(usage = READ_WRITE) public class Skill { @Id diff --git a/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/User.java b/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/User.java index 268f873f87..417c2850e8 100644 --- a/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/User.java +++ b/examples/hibernate/src/main/java/com/github/benmanes/caffeine/examples/hibernate/User.java @@ -15,7 +15,6 @@ */ package com.github.benmanes.caffeine.examples.hibernate; -import static jakarta.persistence.AccessType.FIELD; import static org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE; import java.util.ArrayList; @@ -23,8 +22,6 @@ import org.hibernate.annotations.Cache; -import jakarta.persistence.Access; -import jakarta.persistence.Cacheable; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.Id; @@ -35,8 +32,6 @@ * @author ben.manes@gmail.com (Ben Manes) */ @Entity -@Cacheable -@Access(FIELD) @Cache(usage = READ_WRITE) public class User { @Id diff --git a/examples/hibernate/src/main/resources/hibernate.properties b/examples/hibernate/src/main/resources/hibernate.properties index a2f35caee9..d9183803b3 100644 --- a/examples/hibernate/src/main/resources/hibernate.properties +++ b/examples/hibernate/src/main/resources/hibernate.properties @@ -1,12 +1,9 @@ -hibernate.dialect=org.hibernate.dialect.H2Dialect - -hibernate.connection.provider_class=org.hibernate.hikaricp.internal.HikariCPConnectionProvider -hibernate.connection.driver_class=org.h2.Driver hibernate.connection.url=jdbc:h2:mem:test hibernate.connection.username=sa hibernate.show_sql=false -hibernate.format_sql=true +hibernate.format_sql=false +hibernate.highlight_sql=true hibernate.globally_quoted_identifiers=true hibernate.hbm2ddl.auto=create-drop diff --git a/examples/hibernate/src/main/resources/log4j2.properties b/examples/hibernate/src/main/resources/log4j2.properties new file mode 100644 index 0000000000..01f1ea7d92 --- /dev/null +++ b/examples/hibernate/src/main/resources/log4j2.properties @@ -0,0 +1,14 @@ +rootLogger.level = info +rootLogger.appenderRefs = console +rootLogger.appenderRef.console.ref = console + +logger.hibernate.name = org.hibernate +logger.hibernate.level = warn + +logger.hikaricp.name = com.zaxxer.hikari +logger.hikaricp.level = warn + +appender.console.name = console +appender.console.type = Console +appender.console.layout.type = PatternLayout +appender.console.layout.pattern = %highlight{[%p]} %c %m%n diff --git a/examples/hibernate/src/test/java/com/github/benmanes/caffeine/examples/hibernate/HibernateCacheTest.java b/examples/hibernate/src/test/java/com/github/benmanes/caffeine/examples/hibernate/HibernateCacheTest.java index 6ec67a8770..37a371998e 100644 --- a/examples/hibernate/src/test/java/com/github/benmanes/caffeine/examples/hibernate/HibernateCacheTest.java +++ b/examples/hibernate/src/test/java/com/github/benmanes/caffeine/examples/hibernate/HibernateCacheTest.java @@ -17,9 +17,6 @@ import static com.github.benmanes.caffeine.examples.hibernate.HibernateSubject.assertThat; -import java.util.logging.Level; -import java.util.logging.Logger; - import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; @@ -36,7 +33,6 @@ public final class HibernateCacheTest { @BeforeEach public void beforeEach() { - Logger.getLogger("").setLevel(Level.WARNING); sessionFactory = new Configuration().addAnnotatedClass(User.class) .addAnnotatedClass(Skill.class).addAnnotatedClass(Project.class) .buildSessionFactory(new StandardServiceRegistryBuilder().build()); diff --git a/examples/resilience-failsafe/README.md b/examples/resilience-failsafe/README.md new file mode 100644 index 0000000000..073cafe0c3 --- /dev/null +++ b/examples/resilience-failsafe/README.md @@ -0,0 +1,57 @@ +[Failsafe's][failsafe] retry, timeout, and fallback strategies can be used to make the cache +operations resiliant to intermittent failures. + +### Retry +A [retry policy][retry] will retry failed executions a certain number of times, with an optional +delay between attempts. + +```java +var retryPolicy = RetryPolicy.builder() + .withDelay(Duration.ofSeconds(1)) + .withMaxAttempts(3) + .build(); +var failsafe = Failsafe.with(retryPolicy); + +// Retry outside of the cache loader for synchronous calls +Cache cache = Caffeine.newBuilder().build(); +failsafe.get(() -> cache.get(key, key -> /* intermittent failures */ )); + +// Optionally, retry inside the cache load for asynchronous calls +AsyncCache asyncCache = Caffeine.newBuilder().buildAsync(); +asyncCache.get(key, (key, executor) -> failsafe.getAsync(() -> /* intermittent failure */)); +``` + +### Timeout +A [timeout policy][timeout] will cancel the execution if it takes too long to complete. + +```java +var retryPolicy = RetryPolicy.builder() + .withDelay(Duration.ofSeconds(1)) + .withMaxAttempts(3) + .build(); +var timeout = Timeout.builder(Duration.ofSeconds(1)).withInterrupt().build(); +var failsafe = Failsafe.with(timeout, retryPolicy); + +Cache cache = Caffeine.newBuilder().build(); +failsafe.get(() -> cache.get(key, key -> /* timeout */ )); +``` + +### Fallback +A [fallback policy][fallback] will provide an alternative result for a failed execution. + +```java +var retryPolicy = RetryPolicy.builder() + .withDelay(Duration.ofSeconds(1)) + .withMaxAttempts(3) + .build(); +var fallback = Fallback.of(/* fallback */); +var failsafe = Failsafe.with(fallback, retryPolicy); + +Cache cache = Caffeine.newBuilder().build(); +failsafe.get(() -> cache.get(key, key -> /* failure */ )); +``` + +[failsafe]: https://failsafe.dev +[retry]: https://failsafe.dev/retry +[timeout]: https://failsafe.dev/timeout +[fallback]: https://failsafe.dev/fallback diff --git a/examples/resilience-failsafe/build.gradle.kts b/examples/resilience-failsafe/build.gradle.kts new file mode 100644 index 0000000000..4c3bcd1adc --- /dev/null +++ b/examples/resilience-failsafe/build.gradle.kts @@ -0,0 +1,27 @@ +plugins { + `java-library` + alias(libs.plugins.versions) +} + +dependencies { + implementation(libs.caffeine) + implementation(libs.failsafe) + + testImplementation(libs.junit) + testImplementation(libs.truth) +} + +testing.suites { + val test by getting(JvmTestSuite::class) { + useJUnitJupiter() + } +} + +java.toolchain.languageVersion = JavaLanguageVersion.of( + System.getenv("JAVA_VERSION")?.toIntOrNull() ?: 11) + +tasks.withType().configureEach { + javaCompiler = javaToolchains.compilerFor { + languageVersion = java.toolchain.languageVersion + } +} diff --git a/examples/resilience-failsafe/gradle/libs.versions.toml b/examples/resilience-failsafe/gradle/libs.versions.toml new file mode 100644 index 0000000000..4d50e41ffc --- /dev/null +++ b/examples/resilience-failsafe/gradle/libs.versions.toml @@ -0,0 +1,15 @@ +[versions] +caffeine = "3.1.7" +failsafe = "3.3.2" +junit = "5.10.0" +truth = "1.1.5" +versions = "0.47.0" + +[libraries] +caffeine = { module = "com.github.ben-manes.caffeine:caffeine", version.ref = "caffeine" } +failsafe = { module = "dev.failsafe:failsafe", version.ref = "failsafe" } +junit = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit" } +truth = { module = "com.google.truth:truth", version.ref = "truth" } + +[plugins] +versions = { id = "com.github.ben-manes.versions", version.ref = "versions" } diff --git a/examples/resilience-failsafe/gradle/wrapper/gradle-wrapper.jar b/examples/resilience-failsafe/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000..7f93135c49 Binary files /dev/null and b/examples/resilience-failsafe/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/resilience-failsafe/gradle/wrapper/gradle-wrapper.properties b/examples/resilience-failsafe/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000000..0fb2837297 --- /dev/null +++ b/examples/resilience-failsafe/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.3-rc-3-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/examples/resilience-failsafe/gradlew b/examples/resilience-failsafe/gradlew new file mode 100755 index 0000000000..0adc8e1a53 --- /dev/null +++ b/examples/resilience-failsafe/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# 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 +# +# https://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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/examples/resilience-failsafe/gradlew.bat b/examples/resilience-failsafe/gradlew.bat new file mode 100644 index 0000000000..93e3f59f13 --- /dev/null +++ b/examples/resilience-failsafe/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/resilience-failsafe/settings.gradle.kts b/examples/resilience-failsafe/settings.gradle.kts new file mode 100644 index 0000000000..feca31d3d6 --- /dev/null +++ b/examples/resilience-failsafe/settings.gradle.kts @@ -0,0 +1,11 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.6.0" +} + +dependencyResolutionManagement { + repositories { + mavenCentral() + } +} + +rootProject.name = "resilience-failsafe" diff --git a/examples/resilience-failsafe/src/test/java/com/github/benmanes/caffeine/examples/resilience/ResilienceTest.java b/examples/resilience-failsafe/src/test/java/com/github/benmanes/caffeine/examples/resilience/ResilienceTest.java new file mode 100644 index 0000000000..46b6a163e9 --- /dev/null +++ b/examples/resilience-failsafe/src/test/java/com/github/benmanes/caffeine/examples/resilience/ResilienceTest.java @@ -0,0 +1,200 @@ +/* + * Copyright 2023 Ben Manes. All Rights Reserved. + * + * 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. + */ +package com.github.benmanes.caffeine.examples.resilience; + +import static com.google.common.truth.Truth.assertThat; +import static org.junit.jupiter.api.Assertions.fail; + +import java.time.Duration; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +import org.junit.jupiter.api.Test; + +import com.github.benmanes.caffeine.cache.AsyncCache; +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; + +import dev.failsafe.Failsafe; +import dev.failsafe.Fallback; +import dev.failsafe.RetryPolicy; +import dev.failsafe.Timeout; +import dev.failsafe.TimeoutExceededException; + +/** + * @author ben.manes@gmail.com (Ben Manes) + */ +public final class ResilienceTest { + + /* + * Synchronous: + * ------------ + * A synchronous cache performs the load while holding the hash table's lock, which may block + * writes to other entries within the same hash bin. To avoid long hold times, prefer performing + * the retry strategy outside of the cache load. + */ + + @Test + public void retry_sync() { + // Given the resilience policy + Cache cache = Caffeine.newBuilder().build(); + var retryPolicy = RetryPolicy.builder() + .onFailedAttempt(event -> System.err.println("Failure #" + event.getAttemptCount())) + .withJitter(Duration.ofMillis(250)) + .withDelay(Duration.ofSeconds(1)) + .withMaxAttempts(3) + .build(); + var failsafe = Failsafe.with(retryPolicy); + + // When the work is performed with intermittent failures + var result = failsafe.get(context -> { + return cache.get(1, key -> { + if (context.getAttemptCount() < (retryPolicy.getConfig().getMaxAttempts() - 1)) { + throw new IllegalStateException("failed"); + } + return "success"; + }); + }); + + // Then complete successfully + assertThat(result).isEqualTo("success"); + System.out.println("Completed with " + result); + } + + @Test + public void fallback_sync() { + // Given the resilience policy + Cache cache = Caffeine.newBuilder().build(); + var retryPolicy = RetryPolicy.builder() + .onFailedAttempt(event -> System.err.println("Failure #" + event.getAttemptCount())) + .withMaxAttempts(3) + .build(); + var fallback = Fallback.of("fallback"); + var failsafe = Failsafe.with(fallback, retryPolicy); + + // When the work fails + var result = failsafe.get(context -> + cache.get(1, key -> { throw new IllegalStateException("failed"); })); + + // Then complete with the fallback + assertThat(result).isEqualTo("fallback"); + System.out.println("Completed with " + result); + } + + @Test + public void timeout_sync() { + // Given the resilience policy + Cache cache = Caffeine.newBuilder().build(); + var retryPolicy = RetryPolicy.builder() + .onFailedAttempt(event -> System.err.println("Failure #" + event.getAttemptCount())) + .withMaxAttempts(3) + .build(); + var timeout = Timeout.builder(Duration.ofSeconds(1)).withInterrupt().build(); + var failsafe = Failsafe.with(timeout, retryPolicy); + + try { + // When the work exceeds a threshold + failsafe.get(context -> cache.get(1, key -> { + try { + TimeUnit.SECONDS.sleep(10); + return null; + } catch (InterruptedException e) { + throw new RuntimeException(e); + } + })); + fail("Should have timed out"); + } catch (TimeoutExceededException e) { + // Then complete with a timeout + System.out.println("Completed with timeout"); + } + } + + /* + * Asynchronous: + * ------------ + * An asynchronous cache performs the load within the future's lock after the mapping has been + * established. The retry strategy can be performed by the future task without penalizing other + * writes, allowing the policy to be placed closer to where the problems might occur. + */ + + @Test + public void retry_async() { + // Given the resilience policy + AsyncCache cache = Caffeine.newBuilder().buildAsync(); + var result = cache.get(1, (key, executor) -> { + var retryPolicy = RetryPolicy.builder() + .onFailedAttempt(event -> System.err.println("Failure #" + event.getAttemptCount())) + .withJitter(Duration.ofMillis(250)) + .withDelay(Duration.ofSeconds(1)) + .withMaxAttempts(3) + .build(); + var failsafe = Failsafe.with(retryPolicy); + + // When the work is performed with intermittent failures + return failsafe.getAsync(context -> { + if (context.getAttemptCount() < (retryPolicy.getConfig().getMaxAttempts() - 1)) { + throw new IllegalStateException("failed"); + } + return "success"; + }); + }); + + // Then complete successfully + assertThat(result.join()).isEqualTo("success"); + System.out.println("Completed with " + result.join()); + } + + @Test + public void fallback_async() { + AsyncCache cache = Caffeine.newBuilder().buildAsync(); + var result = cache.get(1, (key, executor) -> { + // Given the resilience policy + var retryPolicy = RetryPolicy.builder() + .onFailedAttempt(event -> System.err.println("Failure #" + event.getAttemptCount())) + .withMaxAttempts(3) + .build(); + var fallback = Fallback.of("fallback"); + var failsafe = Failsafe.with(fallback, retryPolicy); + + // When the work fails + return failsafe.getAsync(context -> { throw new IllegalStateException("failed"); }); + }); + + // Then complete with the fallback + assertThat(result.join()).isEqualTo("fallback"); + System.out.println("Completed with " + result.join()); + } + + @Test + public void timeout_async() { + // Given the resilience policy + AsyncCache cache = Caffeine.newBuilder().buildAsync(); + var result = cache.get(1, (key, executor) -> + new CompletableFuture().orTimeout(1, TimeUnit.SECONDS)); + + try { + // When the work fails + result.join(); + fail("Should have timed out"); + } catch (CompletionException e) { + // Then complete with a timeout + assertThat(e).hasCauseThat().isInstanceOf(TimeoutException.class); + System.out.println("Completed with timeout"); + } + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml index 2e20a0db4c..a875295f68 100644 --- a/gradle/libs.versions.toml +++ b/gradle/libs.versions.toml @@ -22,7 +22,7 @@ coveralls = "2.12.2" dependency-check = "8.3.1" eclipse-collections = "12.0.0.M2" ehcache3 = "3.10.8" -errorprone-core = "2.21.0" +errorprone-core = "2.21.1" errorprone-plugin = "3.1.0" errorprone-support = "0.12.0" expiring-map = "0.5.10" @@ -77,7 +77,7 @@ pmd = "7.0.0-rc3" protobuf = "3.23.4" slf4j = "2.0.7" slf4j-test = "3.0.1" -snakeyaml = "2.0" +snakeyaml = "2.1" sonarqube = "4.3.0.3225" spotbugs-contrib = "7.6.0" spotbugs-core = "4.7.3" @@ -165,6 +165,7 @@ jsoup = { module = "org.jsoup:jsoup", version.ref = "jsoup" } junit4 = { module = "junit:junit", version.ref = "junit4" } junit5 = { module = "org.junit.jupiter:junit-jupiter", version.ref = "junit5" } junit5-bom = { module = "org.junit:junit-bom", version.ref = "junit5" } +junit5-launcher = { module = "org.junit.platform:junit-platform-launcher" } junit5-testng = { module = "org.junit.support:testng-engine", version.ref = "junit-testng" } junit5-vintage = { module = "org.junit.vintage:junit-vintage-engine", version.ref = "junit5" } kotlin-bom = { module = "org.jetbrains.kotlin:kotlin-bom", version.ref = "kotlin" } diff --git a/gradle/plugins/src/main/kotlin/lifecycle/testing-caffeine-conventions.gradle.kts b/gradle/plugins/src/main/kotlin/lifecycle/testing-caffeine-conventions.gradle.kts index 9bca18abfa..345e877cc9 100644 --- a/gradle/plugins/src/main/kotlin/lifecycle/testing-caffeine-conventions.gradle.kts +++ b/gradle/plugins/src/main/kotlin/lifecycle/testing-caffeine-conventions.gradle.kts @@ -27,6 +27,7 @@ dependencies { testImplementation(platform(libs.kotlin.bom)) testImplementation(platform(libs.junit5.bom)) + testRuntimeOnly(libs.junit5.launcher) testRuntimeOnly(libs.bundles.junit.engines) testRuntimeOnly(libs.bundles.osgi.test.runtime) }