From aa1a5797e60390159de864d169b7f095c2d5fa04 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 16 Jul 2014 11:43:42 -0700 Subject: [PATCH 001/779] Created Home (asciidoc) --- Home.asciidoc | 1 + 1 file changed, 1 insertion(+) create mode 100644 Home.asciidoc diff --git a/Home.asciidoc b/Home.asciidoc new file mode 100644 index 0000000000..a76cb355cf --- /dev/null +++ b/Home.asciidoc @@ -0,0 +1 @@ +Welcome to the ehcache3 wiki! From d6f04c293b8edf9f5d2d4d28c3612be1d34a9a86 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 16 Jul 2014 15:44:07 -0400 Subject: [PATCH 002/779] Some base layout for the doc wiki --- design.bootstrapping.asciidoc | 9 +++++++++ module.api.asciidoc | 0 module.core.asciidoc | 0 module.impl.asciidoc | 0 4 files changed, 9 insertions(+) create mode 100644 design.bootstrapping.asciidoc create mode 100644 module.api.asciidoc create mode 100644 module.core.asciidoc create mode 100644 module.impl.asciidoc diff --git a/design.bootstrapping.asciidoc b/design.bootstrapping.asciidoc new file mode 100644 index 0000000000..8d9c9741a9 --- /dev/null +++ b/design.bootstrapping.asciidoc @@ -0,0 +1,9 @@ += Bootstrapping design doc + +:toc: + +== Configuration + +=== Extending the config + +== Services diff --git a/module.api.asciidoc b/module.api.asciidoc new file mode 100644 index 0000000000..e69de29bb2 diff --git a/module.core.asciidoc b/module.core.asciidoc new file mode 100644 index 0000000000..e69de29bb2 diff --git a/module.impl.asciidoc b/module.impl.asciidoc new file mode 100644 index 0000000000..e69de29bb2 From f04aaef337e976f44ffcc9a65f9c2530c9adead7 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 16 Jul 2014 15:45:37 -0400 Subject: [PATCH 003/779] Some base layout for the doc wiki --- Home.asciidoc | 41 ++++++++++++++++++++++++++++++++++++++++- module.api.asciidoc | 6 ++++++ module.core.asciidoc | 6 ++++++ module.impl.asciidoc | 6 ++++++ 4 files changed, 58 insertions(+), 1 deletion(-) diff --git a/Home.asciidoc b/Home.asciidoc index a76cb355cf..34c7069ff9 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -1 +1,40 @@ -Welcome to the ehcache3 wiki! += Ehcache 3 developer wiki + +:toc: + +== Developer, be welcome! + +This wiki contains all design documents and other related material to doing development on Ehcache, not _using_ Ehcache! If you are a developer that wants to get involved in developing new features, fixing bugs, extend the existing or implement a new module based on the Ehcache3 SPIs, this is the place you've been looking for. Be welcome! + +== How to contribute? + +=== Process + +=== Code layout + +The code core of Ehcache is split in three core modules: + + . the link:module.api[API module], which ... ; + . the link:module.core[Core module], that ... ; and + . the link:module.impl[Implementation module], containing ... . + +=== Contributor agreement + +== How to extend? + +=== SPIs ++org.ehcache.spi.service+, +org.ehcache.spi.cache+ + +=== Extension points + +== Fundamental concepts + +=== Modular approach + ++org.ehcache.spi.ServiceProvider+, +org.ehcache.spi.service.Service+ + +=== Configuration + ++org.ehcache.config.CacheConfiguration+, +org.ehcache.spi.service.ServiceConfiguration+, +org.ehcache.config.xml.XmlConfigurationParser+ + +NOTE: For more information on how the configuration is parsed, resolved and services are then bootstrapped, please read the link:design.bootstrapping[Bootstrapping design doc]. diff --git a/module.api.asciidoc b/module.api.asciidoc index e69de29bb2..59d5b31df0 100644 --- a/module.api.asciidoc +++ b/module.api.asciidoc @@ -0,0 +1,6 @@ += API Module + +:toc: + +== API Module + diff --git a/module.core.asciidoc b/module.core.asciidoc index e69de29bb2..030c7b25c4 100644 --- a/module.core.asciidoc +++ b/module.core.asciidoc @@ -0,0 +1,6 @@ += Core Module + +:toc: + +== Core Module + diff --git a/module.impl.asciidoc b/module.impl.asciidoc index e69de29bb2..a7d474e705 100644 --- a/module.impl.asciidoc +++ b/module.impl.asciidoc @@ -0,0 +1,6 @@ += Implementation Module + +:toc: + +== Implementation Module + From 45618b0f5331c12d5196b122e1e717f48f98b60e Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Tue, 5 Aug 2014 10:26:38 -0400 Subject: [PATCH 004/779] Filled out the contributor and code layout part --- Home.asciidoc | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/Home.asciidoc b/Home.asciidoc index 34c7069ff9..f49810ef22 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -8,24 +8,33 @@ This wiki contains all design documents and other related material to doing deve == How to contribute? + + === Process -=== Code layout +On paper (or on this screen), it's pretty straight forward: -The code core of Ehcache is split in three core modules: + . Join the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] and say hello! + . Check the https://github.com/ehcache/ehcache3/issues[issues] and verify what you want isn't yet planned or could even already being worked on by someone; + . If the task exists already and isn't assigned: drop us an email on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] about it and we'll make sure we help you getting started and we'll assign the task/issue to you; + . If nothing matches in the existing issue list, create a bug as such; or, if we're talking about a larger task or feature, https://groups.google.com/forum/#!forum/ehcache-dev[drop us a message] first, and we'll see how to tackle it; + . https://github.com/ehcache/ehcache3/fork[Fork] the project to your own repository and get started (you probably want to work on a dedicated branch); + . Rebase your fork and do a pull request. We'll use that to code review it; + . Be rich and famous! - . the link:module.api[API module], which ... ; - . the link:module.core[Core module], that ... ; and - . the link:module.impl[Implementation module], containing ... . +Now, the doing the work part might be a little more challenging, and we don't provide any guarantees as to becoming rich... but you'll be famous to us! === Contributor agreement -== How to extend? +In order to accept any contribution, we will need you to fill out and mail https://confluence.terracotta.org/download/attachments/27918462/Terracotta%20Individual%20Contributor%20Agreement%20v3.pdf?version=1&modificationDate=1393442245216&api=v2[the Individual Contributor Agreement] at contributors@terracotta.org. -=== SPIs -+org.ehcache.spi.service+, +org.ehcache.spi.cache+ +=== Code layout -=== Extension points +The code core of Ehcache is split in three core modules: + + . the link:module.api[API module], which contains mainly interfaces. They are the core API to Ehcache (e.g. +Cache+, +CacheManager+) that users depend on. It also contains the entry points in terms of SPI (e.g. +Service+, +Store+, +AuthoritativeTier+ & +CachingTier+), that are used by other modules that in turn provide their implementations; + . the link:module.core[Core module], that is composed of the plumbery that wires the API used by users with the SPI implementations present in packaged modules; and + . the link:module.impl[Implementation module], containing the default implementation of +Cache+ and +CacheManager+, as well as implementations of core SPIs, such as +HeapResource+ that lets you create on-heap +Cache+ and +CachingTier+ instances. == Fundamental concepts @@ -38,3 +47,10 @@ The code core of Ehcache is split in three core modules: +org.ehcache.config.CacheConfiguration+, +org.ehcache.spi.service.ServiceConfiguration+, +org.ehcache.config.xml.XmlConfigurationParser+ NOTE: For more information on how the configuration is parsed, resolved and services are then bootstrapped, please read the link:design.bootstrapping[Bootstrapping design doc]. + +== How to extend? + +=== SPIs ++org.ehcache.spi.service+, +org.ehcache.spi.cache+ + +=== Extension points From 1310e9d46d32bf6fbe4a9b16a991453359350518 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 13 Aug 2014 15:56:59 -0400 Subject: [PATCH 005/779] Added git workflow --- Home.asciidoc | 2 +- dev.git.asciidoc | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) create mode 100644 dev.git.asciidoc diff --git a/Home.asciidoc b/Home.asciidoc index f49810ef22..a2251ac698 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -46,7 +46,7 @@ The code core of Ehcache is split in three core modules: +org.ehcache.config.CacheConfiguration+, +org.ehcache.spi.service.ServiceConfiguration+, +org.ehcache.config.xml.XmlConfigurationParser+ -NOTE: For more information on how the configuration is parsed, resolved and services are then bootstrapped, please read the link:design.bootstrapping[Bootstrapping design doc]. +NOTE: For more information on how the configuration is parsed, resolved and services are then bootstrapped, please read the link:design.bootstrapping#configuration[Bootstrapping design doc]. == How to extend? diff --git a/dev.git.asciidoc b/dev.git.asciidoc new file mode 100644 index 0000000000..bb88050873 --- /dev/null +++ b/dev.git.asciidoc @@ -0,0 +1,38 @@ += Git usage + +:toc: + +== Fork on me GitHub! + + . If you don't have an account on github, create one now and fork your own copy of Ehcache to your account; + . +git clone+ that to your computer; + . +git remote add+ the ehcache/ehcache3 repository as +upstream+; + . You'll have to keep your (both on your computer and the one on your github, which defaults to +origin+) +master+ branch in sync with the one from +upstream+ (see below) + . +git branch+ to start working on some issue. We recommend you name the branch after the issue you work on. You can have multiple branches for different issues you maybe working on. Commit as you see fit on each of these branches (we recommend small commits often); + . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~n+ where +n+ is how many commits you'd be ahead when done; + +== Pull request + + . Right before sharing your changes, make sure you +git pull upstream+ and +git rebase+ both your +master+ and your working branch; + . Finally, +git push origin+ your branch to your copy on github. + . You then need to create a pull request, using the UI on github; + . Someone from our team is then going to review your change set. + +== Review + + . The pull request will be reviewed for: + .. 'Code style': Needs to match the style of the project; + .. 'Correctness of the fix/implementation': the changeset should only be about the issue addressed; + .. 'Test coverage': all changes need to have appropriate test coverage. + . The could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +upstream/master+ may drift, you'd then need to +git pull upstream+ and +git rebase upstream/master+ your master, and +git rebase master+ your branch. Finally +git push --force origin+ your branch. + +== Merging a pull request + +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo) to someone else's pull request, don't use the github UI to merge + + . +git remote add+ the contributor's ehcache3 repository to your local copy; + . +git pull+ the branch from there; + . +git cherry-pick+ or +git rebase+ +upstream/master+ with the changes from that branch; + . +git push upstream master+ to the main repository. + +That way we keep a single timeline (where everything as a single 'parent', à la subversion). From b79797e059d6a8f4a3cfe1a5105063a541099ae4 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 13 Aug 2014 16:01:47 -0400 Subject: [PATCH 006/779] More git workflow --- Home.asciidoc | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/Home.asciidoc b/Home.asciidoc index a2251ac698..13aaa93ab1 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -8,8 +8,6 @@ This wiki contains all design documents and other related material to doing deve == How to contribute? - - === Process On paper (or on this screen), it's pretty straight forward: @@ -19,7 +17,7 @@ On paper (or on this screen), it's pretty straight forward: . If the task exists already and isn't assigned: drop us an email on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] about it and we'll make sure we help you getting started and we'll assign the task/issue to you; . If nothing matches in the existing issue list, create a bug as such; or, if we're talking about a larger task or feature, https://groups.google.com/forum/#!forum/ehcache-dev[drop us a message] first, and we'll see how to tackle it; . https://github.com/ehcache/ehcache3/fork[Fork] the project to your own repository and get started (you probably want to work on a dedicated branch); - . Rebase your fork and do a pull request. We'll use that to code review it; + . Rebase your fork and do a pull request. We'll use that to code review it (see link:dev.git[git usage page]) . Be rich and famous! Now, the doing the work part might be a little more challenging, and we don't provide any guarantees as to becoming rich... but you'll be famous to us! From e500f72b7b5402dcae890f0788e737f9bc4db83c Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 13 Aug 2014 16:03:47 -0400 Subject: [PATCH 007/779] More git workflow part 2 --- dev.git.asciidoc | 53 ++++++++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index bb88050873..7ba07b8d83 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -4,35 +4,44 @@ == Fork on me GitHub! - . If you don't have an account on github, create one now and fork your own copy of Ehcache to your account; - . +git clone+ that to your computer; - . +git remote add+ the ehcache/ehcache3 repository as +upstream+; - . You'll have to keep your (both on your computer and the one on your github, which defaults to +origin+) +master+ branch in sync with the one from +upstream+ (see below) - . +git branch+ to start working on some issue. We recommend you name the branch after the issue you work on. You can have multiple branches for different issues you maybe working on. Commit as you see fit on each of these branches (we recommend small commits often); - . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~n+ where +n+ is how many commits you'd be ahead when done; + . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; + . +git clone+ that fork to your computer, by default that remote's name will be +origin+; + . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; + . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) + . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; + . You can have as many parallel branches as issues you might be working on; + . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; -== Pull request +== Initiate a pull request - . Right before sharing your changes, make sure you +git pull upstream+ and +git rebase+ both your +master+ and your working branch; - . Finally, +git push origin+ your branch to your copy on github. - . You then need to create a pull request, using the UI on github; - . Someone from our team is then going to review your change set. + . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: -== Review + git pull ehcache + git checkout master + git rebase ehcache/master + git checkout issue- + git rebase master + + . Finally, +git push origin issue-''+ to push your branch to your account; + . You then need to create a pull request, using the UI on GitHub; + . Someone from our team is then going to review it. + +== Have it reviewed . The pull request will be reviewed for: - .. 'Code style': Needs to match the style of the project; - .. 'Correctness of the fix/implementation': the changeset should only be about the issue addressed; - .. 'Test coverage': all changes need to have appropriate test coverage. - . The could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +upstream/master+ may drift, you'd then need to +git pull upstream+ and +git rebase upstream/master+ your master, and +git rebase master+ your branch. Finally +git push --force origin+ your branch. + .. 'Correctness': the pull request should wholly and only be about the related issue; + .. 'Style': which needs to match the style of the project; + .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. + . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. == Merging a pull request -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo) to someone else's pull request, don't use the github UI to merge +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*, instead: - . +git remote add+ the contributor's ehcache3 repository to your local copy; - . +git pull+ the branch from there; - . +git cherry-pick+ or +git rebase+ +upstream/master+ with the changes from that branch; - . +git push upstream master+ to the main repository. + . +git remote add ''+ the contributor's ehcache3 repository; + . +git pull ''/issue-''+; + . 'do the actual review'; + . +git cherry-pick+ or +git rebase issue-''+ onto +master+ with the changes; + . +git push ehcache master+ to the main repository. -That way we keep a single timeline (where everything as a single 'parent', à la subversion). +That way we keep a linear timeline (where commits have a single parent, à la subversion). From 0aa2232c1906e3af7b84a69e3cb2adf17c94bca3 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 21 Aug 2014 09:53:51 -0400 Subject: [PATCH 008/779] Added meeting page --- Home.asciidoc | 4 +++- design.bootstrapping.asciidoc | 2 ++ dev.meetings.asciidoc | 33 +++++++++++++++++++++++++++++++++ module.api.asciidoc | 9 +++++++++ module.core.asciidoc | 13 +++++++++++++ module.impl.asciidoc | 17 +++++++++++++++++ 6 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 dev.meetings.asciidoc diff --git a/Home.asciidoc b/Home.asciidoc index 13aaa93ab1..755022e3ed 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -38,7 +38,9 @@ The code core of Ehcache is split in three core modules: === Modular approach -+org.ehcache.spi.ServiceProvider+, +org.ehcache.spi.service.Service+ ++org.ehcache.spi.service.ServiceFactory+ are used to create +org.ehcache.spi.service.Service+, configured through +org.ehcache.spi.service.ServiceConfiguration+. Each of those services can be about anything. + +A special kind of +Service+ is the +org.ehcache.spi.cache.CacheProvider+, which is used by the +CacheManager+ to create all caches. === Configuration diff --git a/design.bootstrapping.asciidoc b/design.bootstrapping.asciidoc index 8d9c9741a9..a0623020b3 100644 --- a/design.bootstrapping.asciidoc +++ b/design.bootstrapping.asciidoc @@ -7,3 +7,5 @@ === Extending the config == Services + +The +CacheManager+ will create a +org.ehcache.spi.ServiceProvider+. The +ServiceProvider+ will use Java's +java.util.ServiceLoader+ to find all +ServiceFactory+ on the classpath. diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc new file mode 100644 index 0000000000..29e0333f82 --- /dev/null +++ b/dev.meetings.asciidoc @@ -0,0 +1,33 @@ += Meet up notes + +:toc: + +== Aug 21, 2014 - Hangout on Air + +=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ + +Both those interfaces exist today. Yet what is each's concerns aren't well identified. + +==== +Cache+ backed by a +Store>+ ? + + . Rename +Element+ ? + . +Store>+ vs. +Store>+ ? + +==== Roles + +How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? + + . +Cache+ Roles + .. Store by Value vs. Ref. + .. Expiry ? + .. Cache lifecycle + .. +BootstrapCacheLoader+ + .. CacheLoaders + .. CacheWriters + .. Listeners ? +.. Stats ? + . +Store+ Roles + .. Eviction + .. Expiry ? + .. Listeners ? + .. Stats ? diff --git a/module.api.asciidoc b/module.api.asciidoc index 59d5b31df0..939c6147f9 100644 --- a/module.api.asciidoc +++ b/module.api.asciidoc @@ -4,3 +4,12 @@ == API Module +Contains all the interfaces, as well as exceptions, an Ehcache user would use explicitly. This includes: + + . Core types + .. +CacheManager+ + .. +Cache+ + . Configuration types + .. +CacheConfiguration+ + .. +ServiceConfiguration+ + . Exceptions diff --git a/module.core.asciidoc b/module.core.asciidoc index 030c7b25c4..174bbf935e 100644 --- a/module.core.asciidoc +++ b/module.core.asciidoc @@ -4,3 +4,16 @@ == Core Module +Contains the +ServiceLocator+, as well as core SPI interfaces. + +=== Services + +==== ServiceProvider + +=== SPI's + +==== CacheProvider + +==== Cache Store + +==== Tiering interfaces diff --git a/module.impl.asciidoc b/module.impl.asciidoc index a7d474e705..8927b0b887 100644 --- a/module.impl.asciidoc +++ b/module.impl.asciidoc @@ -4,3 +4,20 @@ == Implementation Module +=== Configuration + ++Configuration+ and +CacheConfiguration+ aren't used to create +CacheManager+ and +Cache+ instances, respectively. Instead they are used to reflect the configuration currently in use by a given +CacheManager+ or +Cache+. + +To instantiate new +CacheManager+ or +Cache+, you should use +CacheManagerBuilder+ or +CacheBuilder+ instances instead. + +==== Builders + +==== Mutability of 'configuration' instance + +=== Internals + +==== Store + +==== Tiering + +==== Serialization From be2aed7587c6585d2d27857274b2b41f75425ba7 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 21 Aug 2014 11:36:55 -0700 Subject: [PATCH 009/779] Sorted Roles --- dev.meetings.asciidoc | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 29e0333f82..28524ac5c4 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -18,16 +18,12 @@ Both those interfaces exist today. Yet what is each's concerns aren't well ident How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? . +Cache+ Roles - .. Store by Value vs. Ref. - .. Expiry ? + .. Expiry + .. Public EntryListeners .. Cache lifecycle - .. +BootstrapCacheLoader+ .. CacheLoaders .. CacheWriters - .. Listeners ? -.. Stats ? . +Store+ Roles - .. Eviction - .. Expiry ? - .. Listeners ? - .. Stats ? + .. Store by Value vs. Ref. + .. Eviction & (private) EvictionListeners + From 48e19f1588bfaab18e077f306df3ae0a23cd80aa Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 21 Aug 2014 16:02:02 -0400 Subject: [PATCH 010/779] Added conclusions of today's meeting, as well as link to next week's --- dev.meetings.asciidoc | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 28524ac5c4..406a493289 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,16 +2,20 @@ :toc: +== Aug 28, 2014 - Hangout on Air + +Public on https://plus.google.com/u/0/events/c77o4t7tvm6nb4j120f1lcrr4t8[Google plus Hangout] at 8pm CET / 2pm EST / 11am PST + == Aug 21, 2014 - Hangout on Air -=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ +Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] -Both those interfaces exist today. Yet what is each's concerns aren't well identified. +=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ -==== +Cache+ backed by a +Store>+ ? +==== +Cache+ backed by a +Store>+ - . Rename +Element+ ? - . +Store>+ vs. +Store>+ ? + . Rename +Element+ + . Try +Store>+ for now ==== Roles @@ -27,3 +31,15 @@ How much can be solved by having the +Cache+ call into some +Store.process(K, En .. Store by Value vs. Ref. .. Eviction & (private) EvictionListeners +=== Other items + +==== Integrate 107 TCK + +Created issue #21 + +==== What's with the sizeof modules ? + + . *Hibernate* to be integrated within the h2lc module there + . *Groovy*, either: + .. @candrews takes ownership, or + .. we find someone within TC/SAG to do so (unidentified yet though) From b601284273d7170afaccf42ea04e49ec5dbf9d8e Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Fri, 22 Aug 2014 11:20:33 -0400 Subject: [PATCH 011/779] Fixed PR handling --- dev.git.asciidoc | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 7ba07b8d83..ff0280ffe9 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -38,10 +38,12 @@ If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*, instead: - . +git remote add ''+ the contributor's ehcache3 repository; - . +git pull ''/issue-''+; + . +git remote add '' '+ the contributor's ehcache3 repository; + . +git fetch '' issue-''+; + . +git checkout -b ''/issue-''+; . 'do the actual review'; - . +git cherry-pick+ or +git rebase issue-''+ onto +master+ with the changes; + . +git checkout master+; + . +git cherry-pick ..issue-''+; . +git push ehcache master+ to the main repository. That way we keep a linear timeline (where commits have a single parent, à la subversion). From b4eb067a1bd028a51ed9cf4da113debbfe4eefa0 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Fri, 22 Aug 2014 11:52:57 -0400 Subject: [PATCH 012/779] Some explanation around author vs. committer --- dev.git.asciidoc | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index ff0280ffe9..dc5a00f385 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -36,7 +36,12 @@ == Merging a pull request -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*, instead: +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*. The way we are looking at this is: + + - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; + - When you are code reviewing someone else's contribution, you do have commit rights. + +As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: . +git remote add '' '+ the contributor's ehcache3 repository; . +git fetch '' issue-''+; @@ -46,4 +51,4 @@ If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *d . +git cherry-pick ..issue-''+; . +git push ehcache master+ to the main repository. -That way we keep a linear timeline (where commits have a single parent, à la subversion). +The changes are now recorded as authored by the contributor, but committed by the reviewer. That way we also keep a linear timeline on master (where commits have a single parent, à la subversion). From 87980770f47761005138684f0d334b40ca589a10 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 28 Aug 2014 13:35:22 -0400 Subject: [PATCH 013/779] Agenda for meeting --- dev.meetings.asciidoc | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 406a493289..8ec38efb64 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -6,6 +6,11 @@ Public on https://plus.google.com/u/0/events/c77o4t7tvm6nb4j120f1lcrr4t8[Google plus Hangout] at 8pm CET / 2pm EST / 11am PST +=== Agenda + + . +CacheManagerBuilder+ and +CacheBuilder+ + . +CacheManager+-less +Cache+ instances + == Aug 21, 2014 - Hangout on Air Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] From 4b6dd2d0d0feef75aaa99bd6884a0a56f3a5b921 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 28 Aug 2014 22:16:24 -0400 Subject: [PATCH 014/779] Added initial notes from today's meeting --- dev.meetings.asciidoc | 46 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 42 insertions(+), 4 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 8ec38efb64..f65f280549 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,14 +2,52 @@ :toc: -== Aug 28, 2014 - Hangout on Air +== Sep 4, 2014 - Hangout on Air -Public on https://plus.google.com/u/0/events/c77o4t7tvm6nb4j120f1lcrr4t8[Google plus Hangout] at 8pm CET / 2pm EST / 11am PST +Next public meeting on https://plus.google.com/u/0/events/ccupvimv7vg6pkark9a4t4bbul4[G+ Hangout on Air] at 11:30 IST / 8pm CET / 2pm EST / 11am PST === Agenda - . +CacheManagerBuilder+ and +CacheBuilder+ - . +CacheManager+-less +Cache+ instances +'*to be defined* —' visit https://groups.google.com/forum/#!forum/ehcache-dev[the ehcache developer mailing list] to provide input by next Wednesday – Sep 3, 2014. + +== Aug 28, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== +CacheManagerBuilder+ and +CacheBuilder+ + +Let's try to introduce a type hierarchy for both +Cache+ and +CacheManager+ that the builder would actually build, narrowing the type down à la Quartz 2.0 builders. + +---- +PersistentCache cache = newCacheBuilder() // <1> + .diskPersistent( + cfg // <3> + ) // <2> + .build(); // <4> +---- + +<1> static method that creates a builder: +Builder+ +<2> narrows to the builder's type down to +Builder+ +<3> +cfg+ actually defines the mode to use for persistence, eg: expect data on disk; expect none; use data if there; wipe data if there; wipe data on +Cache.close()+ +<4> actually builds the +PersistentCache+ + +Alex to make an actual proposal by next week. + +=== +CacheManager+-less +Cache+ instances + + - Keep these, where the user is actually responsible to provide services + - Only these +Cache+'s type would expose +.close()+ + - +CacheManager+ managed +Cache+ instances would be 'closed' through the +CacheManager+ + - To further lifecycle +PersistentCache+ instance, managed by a +CacheManager+, the latter could expose some method to retrieve +DiskPersisted+ (interface with minimal lifecycle methods) instances; e.g. + +---- +Iterable> it = cacheManager.getManaged(DiskPersisted.class); +it.next().value() // <1> + .deleteOnDiskFiles(); // <2> +---- + +<1> +DiskPersisted+ could expose methods around lifecycling the data on disk only. No +Cache+ methods +<2> Implies +Cache.close()+, i.e. clear all 'VM transient' data and delete data from disk. == Aug 21, 2014 - Hangout on Air From 0806ca8e3a771e2227243eac23b1ba1a9bab3d67 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 3 Sep 2014 17:30:54 -0400 Subject: [PATCH 015/779] Added agenda for next meeting --- dev.meetings.asciidoc | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index f65f280549..ad7650f3f1 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -8,7 +8,28 @@ Next public meeting on https://plus.google.com/u/0/events/ccupvimv7vg6pkark9a4t4 === Agenda -'*to be defined* —' visit https://groups.google.com/forum/#!forum/ehcache-dev[the ehcache developer mailing list] to provide input by next Wednesday – Sep 3, 2014. +==== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ + +---- + final CacheManager cacheManager = newCacheManagerBuilder().build(); + + final PersistentCacheManager pCacheManager = newCacheManagerBuilder() + .as( + diskPersistent(OVERRIDING) + .persistTo(File.createTempFile("ehcache", ".data")) + ) + .build(); + + final PersistentCache pCache = newCacheBuilder(String.class, Object.class) + .as( + persistent(String.class, Object.class) + ) + .build(); +---- + +==== Initial API issue break down + +See link:../../issues[issues] as well as https://waffle.io/ehcache/ehcache3[waffle.io]. == Aug 28, 2014 - Hangout on Air From a8a4958c54ba3111a6bdfd0890332f9b3b877134 Mon Sep 17 00:00:00 2001 From: alexsnaps Date: Wed, 3 Sep 2014 17:55:02 -0700 Subject: [PATCH 016/779] Updated dev.meetings (asciidoc) --- dev.meetings.asciidoc | 220 +++++++++++++++++++++--------------------- 1 file changed, 111 insertions(+), 109 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index ad7650f3f1..f6af780ec0 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -1,109 +1,111 @@ -= Meet up notes - -:toc: - -== Sep 4, 2014 - Hangout on Air - -Next public meeting on https://plus.google.com/u/0/events/ccupvimv7vg6pkark9a4t4bbul4[G+ Hangout on Air] at 11:30 IST / 8pm CET / 2pm EST / 11am PST - -=== Agenda - -==== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ - ----- - final CacheManager cacheManager = newCacheManagerBuilder().build(); - - final PersistentCacheManager pCacheManager = newCacheManagerBuilder() - .as( - diskPersistent(OVERRIDING) - .persistTo(File.createTempFile("ehcache", ".data")) - ) - .build(); - - final PersistentCache pCache = newCacheBuilder(String.class, Object.class) - .as( - persistent(String.class, Object.class) - ) - .build(); ----- - -==== Initial API issue break down - -See link:../../issues[issues] as well as https://waffle.io/ehcache/ehcache3[waffle.io]. - -== Aug 28, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== +CacheManagerBuilder+ and +CacheBuilder+ - -Let's try to introduce a type hierarchy for both +Cache+ and +CacheManager+ that the builder would actually build, narrowing the type down à la Quartz 2.0 builders. - ----- -PersistentCache cache = newCacheBuilder() // <1> - .diskPersistent( - cfg // <3> - ) // <2> - .build(); // <4> ----- - -<1> static method that creates a builder: +Builder+ -<2> narrows to the builder's type down to +Builder+ -<3> +cfg+ actually defines the mode to use for persistence, eg: expect data on disk; expect none; use data if there; wipe data if there; wipe data on +Cache.close()+ -<4> actually builds the +PersistentCache+ - -Alex to make an actual proposal by next week. - -=== +CacheManager+-less +Cache+ instances - - - Keep these, where the user is actually responsible to provide services - - Only these +Cache+'s type would expose +.close()+ - - +CacheManager+ managed +Cache+ instances would be 'closed' through the +CacheManager+ - - To further lifecycle +PersistentCache+ instance, managed by a +CacheManager+, the latter could expose some method to retrieve +DiskPersisted+ (interface with minimal lifecycle methods) instances; e.g. - ----- -Iterable> it = cacheManager.getManaged(DiskPersisted.class); -it.next().value() // <1> - .deleteOnDiskFiles(); // <2> ----- - -<1> +DiskPersisted+ could expose methods around lifecycling the data on disk only. No +Cache+ methods -<2> Implies +Cache.close()+, i.e. clear all 'VM transient' data and delete data from disk. - -== Aug 21, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] - -=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ - -==== +Cache+ backed by a +Store>+ - - . Rename +Element+ - . Try +Store>+ for now - -==== Roles - -How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? - - . +Cache+ Roles - .. Expiry - .. Public EntryListeners - .. Cache lifecycle - .. CacheLoaders - .. CacheWriters - . +Store+ Roles - .. Store by Value vs. Ref. - .. Eviction & (private) EvictionListeners - -=== Other items - -==== Integrate 107 TCK - -Created issue #21 - -==== What's with the sizeof modules ? - - . *Hibernate* to be integrated within the h2lc module there - . *Groovy*, either: - .. @candrews takes ownership, or - .. we find someone within TC/SAG to do so (unidentified yet though) += Meet up notes + +:toc: + +== Sep 4, 2014 - Hangout on Air + +Next public meeting on https://plus.google.com/u/0/events/ccupvimv7vg6pkark9a4t4bbul4[G+ Hangout on Air] at 11:30 IST / 8pm CET / 2pm EST / 11am PST + +=== Agenda + +==== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ + +[source,java] +---- +final CacheManager cacheManager = newCacheManagerBuilder().build(); + +final PersistentCacheManager pCacheManager = newCacheManagerBuilder() + .as( + diskPersistent(OVERRIDING) + .persistTo(File.createTempFile("ehcache", ".data")) + ) + .build(); + +final PersistentCache pCache = newCacheBuilder(String.class, Object.class) + .as( + persistent(String.class, Object.class) + ) + .build(); +---- + +==== Initial API issue break down + +See link:../../issues[issues] as well as https://waffle.io/ehcache/ehcache3[waffle.io]. + +== Aug 28, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== +CacheManagerBuilder+ and +CacheBuilder+ + +Let's try to introduce a type hierarchy for both +Cache+ and +CacheManager+ that the builder would actually build, narrowing the type down à la Quartz 2.0 builders. + +[source,java] +---- +PersistentCache cache = newCacheBuilder() // <1> + .diskPersistent( + cfg // <3> + ) // <2> + .build(); // <4> +---- + +<1> static method that creates a builder: +Builder+ +<2> narrows to the builder's type down to +Builder+ +<3> +cfg+ actually defines the mode to use for persistence, eg: expect data on disk; expect none; use data if there; wipe data if there; wipe data on +Cache.close()+ +<4> actually builds the +PersistentCache+ + +Alex to make an actual proposal by next week. + +=== +CacheManager+-less +Cache+ instances + + - Keep these, where the user is actually responsible to provide services + - Only these +Cache+'s type would expose +.close()+ + - +CacheManager+ managed +Cache+ instances would be 'closed' through the +CacheManager+ + - To further lifecycle +PersistentCache+ instance, managed by a +CacheManager+, the latter could expose some method to retrieve +DiskPersisted+ (interface with minimal lifecycle methods) instances; e.g. + +---- +Iterable> it = cacheManager.getManaged(DiskPersisted.class); +it.next().value() // <1> + .deleteOnDiskFiles(); // <2> +---- + +<1> +DiskPersisted+ could expose methods around lifecycling the data on disk only. No +Cache+ methods +<2> Implies +Cache.close()+, i.e. clear all 'VM transient' data and delete data from disk. + +== Aug 21, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] + +=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ + +==== +Cache+ backed by a +Store>+ + + . Rename +Element+ + . Try +Store>+ for now + +==== Roles + +How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? + + . +Cache+ Roles + .. Expiry + .. Public EntryListeners + .. Cache lifecycle + .. CacheLoaders + .. CacheWriters + . +Store+ Roles + .. Store by Value vs. Ref. + .. Eviction & (private) EvictionListeners + +=== Other items + +==== Integrate 107 TCK + +Created issue #21 + +==== What's with the sizeof modules ? + + . *Hibernate* to be integrated within the h2lc module there + . *Groovy*, either: + .. @candrews takes ownership, or + .. we find someone within TC/SAG to do so (unidentified yet though) \ No newline at end of file From 4380128ee0ec8ee49d0355e2f1db59aa2a761155 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 3 Sep 2014 21:52:21 -0400 Subject: [PATCH 017/779] Added CIaaS to agenda --- dev.meetings.asciidoc | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index f6af780ec0..15aad454d9 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -32,6 +32,13 @@ final PersistentCache pCache = newCacheBuilder(String.class, Obj See link:../../issues[issues] as well as https://waffle.io/ehcache/ehcache3[waffle.io]. +==== CIaaS + + . drone.io 'failed' + . codeship.io 'failed' + . travis-ci.org 'testing...' + . cloudbees.com 'todo' + == Aug 28, 2014 - Hangout on Air Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] @@ -108,4 +115,4 @@ Created issue #21 . *Hibernate* to be integrated within the h2lc module there . *Groovy*, either: .. @candrews takes ownership, or - .. we find someone within TC/SAG to do so (unidentified yet though) \ No newline at end of file + .. we find someone within TC/SAG to do so (unidentified yet though) From 81614566f8f7438da883057a9caae7eaa55212f5 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 4 Sep 2014 16:56:08 -0400 Subject: [PATCH 018/779] Initial notes from today's meeting and a link to next week's --- dev.meetings.asciidoc | 56 +++++++++++++++++++++++++------------------ 1 file changed, 33 insertions(+), 23 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 15aad454d9..af7753c80c 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,37 +2,47 @@ :toc: -== Sep 4, 2014 - Hangout on Air +== Sep 11, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/ccupvimv7vg6pkark9a4t4bbul4[G+ Hangout on Air] at 11:30 IST / 8pm CET / 2pm EST / 11am PST +Next public meeting on https://plus.google.com/events/cmnhmhlsrini6s3380tqopa5jdo[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST === Agenda -==== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ +*to be defined* — send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[Google groups] -[source,java] ----- -final CacheManager cacheManager = newCacheManagerBuilder().build(); - -final PersistentCacheManager pCacheManager = newCacheManagerBuilder() - .as( - diskPersistent(OVERRIDING) - .persistTo(File.createTempFile("ehcache", ".data")) - ) - .build(); - -final PersistentCache pCache = newCacheBuilder(String.class, Object.class) - .as( - persistent(String.class, Object.class) - ) - .build(); ----- +== Sep 4, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=iehQ9Wxx204&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ + +We want +CacheBuilder+ to create instances of types: + + . +Unmanaged(ShortLived)Cache+ + . +UnmanagedLongLivedCache+ + +While +CacheManagerBuilder+ create: + + . +(ShortLived)CacheManager+ + . +LongLivedCacheManager+ + +which manages +Cache+, i.e. not +Unmanaged+ ones. +LongLived+ exposes the methods to delete 'persistent' data (i.e. that outlives the life of the JVM). A +Cache+ is closed or destroyed through the +CacheManager+. + +=== Initial API issue break down -==== Initial API issue break down +Issues are now ordered on https://waffle.io/ehcache/ehcache3[waffle.io]: -See link:../../issues[issues] as well as https://waffle.io/ehcache/ehcache3[waffle.io]. + . 'API' labeled issues for public API require + .. JavaDoc + . 'API' labeled issues that are about SPI, require + .. JavaDoc + .. Tester of some kind, that + . 'Enhancement' labeled issues require + .. JavaDoc, as required + .. Unit tests + .. If ported from the 2.x line, best is to have decent coverage on the responsibilities the class will keep, prior to refactoring it; then refactor and add/tweak tests as required -==== CIaaS +=== CIaaS . drone.io 'failed' . codeship.io 'failed' From 76a6b497941ac23b273a3911ef853210c8462754 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 11 Sep 2014 10:02:51 -0400 Subject: [PATCH 019/779] Added agenda --- dev.meetings.asciidoc | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index af7753c80c..0c88f667d7 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -8,7 +8,12 @@ Next public meeting on https://plus.google.com/events/cmnhmhlsrini6s3380tqopa5jd === Agenda -*to be defined* — send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[Google groups] + . CRUD operations & 107 + . Resilient +Cache+ ? + . CIaaS: travis-ci + . Eclipse & Gradle + +Use the https://plus.google.com/events/cmnhmhlsrini6s3380tqopa5jdo[Q&A app] on the Hangout on Air for additional ideas or thoughts... == Sep 4, 2014 - Hangout on Air From 65872022a2d960471d60f7b123a649ad15453ac3 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 11 Sep 2014 17:00:17 -0400 Subject: [PATCH 020/779] Updated notes & link to next meeting --- dev.meetings.asciidoc | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 0c88f667d7..7895bc8a3c 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,18 +2,40 @@ :toc: -== Sep 11, 2014 - Hangout on Air +== Sep 18, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/events/cmnhmhlsrini6s3380tqopa5jdo[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Next public meeting on https://plus.google.com/u/0/events/cst4usni73q4qkd315qtm8p6rm8[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST === Agenda - . CRUD operations & 107 - . Resilient +Cache+ ? - . CIaaS: travis-ci - . Eclipse & Gradle +*To be defined* + +== Sep 11, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=PPiS6Y9Fzh4&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== CRUD operations + + - Let's implement the void ones (e.g. +remove(K): void+) for now, we may do more later. It's a cache, no real reason to wanting the old value ever... + +=== Resilience of +Ehcache+ + + - Stick to +ResilienceStrategy+ and have +Ehcache+ be resilient: + * No issues for on-heap +Store+ implementations + * Persistent ones will cope just fine (i.e. recover) + * Distributed ones will force some +.dealWithUnconsistentCache()+ cases + - Have a checked, do it all yourself, interface of some kind + - Postponing the work until all CRUD operations are implemented + +=== Travis CI + + - Lacks archiving, more work for us to do, but that's the work we'd want to be part of the _S_ in CIaaS + - Louis to take ownership and most probably move to cloudbees... + +=== Eclipse & Gradle -Use the https://plus.google.com/events/cmnhmhlsrini6s3380tqopa5jdo[Q&A app] on the Hangout on Air for additional ideas or thoughts... + - Hung to check the Gradle plugin + - Eclipse plugin in gradle build is on master now == Sep 4, 2014 - Hangout on Air From 6a5fa75e512a0c03d5a04362dac225fa5a19ab64 Mon Sep 17 00:00:00 2001 From: alexsnaps Date: Fri, 12 Sep 2014 11:31:45 -0700 Subject: [PATCH 021/779] Updated dev.git (asciidoc) --- dev.git.asciidoc | 108 +++++++++++++++++++++++------------------------ 1 file changed, 54 insertions(+), 54 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index dc5a00f385..62719eb2cc 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -1,54 +1,54 @@ -= Git usage - -:toc: - -== Fork on me GitHub! - - . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; - . +git clone+ that fork to your computer, by default that remote's name will be +origin+; - . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; - . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) - . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; - . You can have as many parallel branches as issues you might be working on; - . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; - -== Initiate a pull request - - . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: - - git pull ehcache - git checkout master - git rebase ehcache/master - git checkout issue- - git rebase master - - . Finally, +git push origin issue-''+ to push your branch to your account; - . You then need to create a pull request, using the UI on GitHub; - . Someone from our team is then going to review it. - -== Have it reviewed - - . The pull request will be reviewed for: - .. 'Correctness': the pull request should wholly and only be about the related issue; - .. 'Style': which needs to match the style of the project; - .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. - . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. - -== Merging a pull request - -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*. The way we are looking at this is: - - - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; - - When you are code reviewing someone else's contribution, you do have commit rights. - -As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: - - . +git remote add '' '+ the contributor's ehcache3 repository; - . +git fetch '' issue-''+; - . +git checkout -b ''/issue-''+; - . 'do the actual review'; - . +git checkout master+; - . +git cherry-pick ..issue-''+; - . +git push ehcache master+ to the main repository. - -The changes are now recorded as authored by the contributor, but committed by the reviewer. That way we also keep a linear timeline on master (where commits have a single parent, à la subversion). += Git usage + +:toc: + +== Fork on me GitHub! + + . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; + . +git clone+ that fork to your computer, by default that remote's name will be +origin+; + . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; + . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) + . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; + . You can have as many parallel branches as issues you might be working on; + . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; + +== Initiate a pull request + + . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: + + git pull ehcache + git checkout master + git rebase ehcache/master + git checkout issue- + git rebase master + + . Finally, +git push origin issue-''+ to push your branch to your account; + . You then need to create a pull request, using the UI on GitHub; + . Someone from our team is then going to review it. + +== Have it reviewed + + . The pull request will be reviewed for: + .. 'Correctness': the pull request should wholly and only be about the related issue; + .. 'Style': which needs to match the style of the project; + .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. + . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. + +== Merging a pull request + +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*. The way we are looking at this is: + + - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; + - When you are code reviewing someone else's contribution, you do have commit rights. + +As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: + + . +git remote add '' '+ the contributor's ehcache3 repository; + . +git fetch '' issue-''+; + . +git checkout -b issue-'' ''/issue-''+; + . 'do the actual review'; + . +git checkout master+; + . +git cherry-pick ..issue-''+; + . +git push ehcache master+ to the main repository. + +The changes are now recorded as authored by the contributor, but committed by the reviewer. That way we also keep a linear timeline on master (where commits have a single parent, à la subversion). From 9520e34c8654e664c3280b6b4ce2b1488534a448 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 16 Sep 2014 14:23:31 +0200 Subject: [PATCH 022/779] Editing merge process --- dev.git.asciidoc | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 62719eb2cc..9f9ec783ef 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -36,19 +36,32 @@ == Merging a pull request -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*. The way we are looking at this is: +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), the way we are looking at this is: - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; - When you are code reviewing someone else's contribution, you do have commit rights. +As a reviewer, you are expected to verify the following: + + . Branch to be merged is up-to-date with master + . Branch to be merged is pristine - it has not been used in a previous pull request + As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: . +git remote add '' '+ the contributor's ehcache3 repository; . +git fetch '' issue-''+; . +git checkout -b issue-'' ''/issue-''+; . 'do the actual review'; + +-- THEN -- +[start=5] + . Use the GitHub UI to do the merge + +-- OR -- +[start=5] . +git checkout master+; - . +git cherry-pick ..issue-''+; + . +git merge --no-ff --ff-only issue-''+; . +git push ehcache master+ to the main repository. -The changes are now recorded as authored by the contributor, but committed by the reviewer. That way we also keep a linear timeline on master (where commits have a single parent, à la subversion). +Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. +Always use a reference to the issue id in the commit message of the merge. From 5cfc701533124fae3779199d4e2ce4b930f639e7 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Tue, 16 Sep 2014 14:05:58 -0400 Subject: [PATCH 023/779] Added link to waffle board --- Home.asciidoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Home.asciidoc b/Home.asciidoc index 755022e3ed..4abd4a98ca 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -13,7 +13,7 @@ This wiki contains all design documents and other related material to doing deve On paper (or on this screen), it's pretty straight forward: . Join the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] and say hello! - . Check the https://github.com/ehcache/ehcache3/issues[issues] and verify what you want isn't yet planned or could even already being worked on by someone; + . Check the https://github.com/ehcache/ehcache3/issues[issues] and verify what you want isn't yet planned or could even already being worked on by someone; We're also using a board on https://waffle.io/ehcache/ehcache3[waffle.io], where work for the current milestone is prioritized; . If the task exists already and isn't assigned: drop us an email on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] about it and we'll make sure we help you getting started and we'll assign the task/issue to you; . If nothing matches in the existing issue list, create a bug as such; or, if we're talking about a larger task or feature, https://groups.google.com/forum/#!forum/ehcache-dev[drop us a message] first, and we'll see how to tackle it; . https://github.com/ehcache/ehcache3/fork[Fork] the project to your own repository and get started (you probably want to work on a dedicated branch); @@ -40,7 +40,7 @@ The code core of Ehcache is split in three core modules: +org.ehcache.spi.service.ServiceFactory+ are used to create +org.ehcache.spi.service.Service+, configured through +org.ehcache.spi.service.ServiceConfiguration+. Each of those services can be about anything. -A special kind of +Service+ is the +org.ehcache.spi.cache.CacheProvider+, which is used by the +CacheManager+ to create all caches. +A special kind of +Service+ is the +org.ehcache.spi.cache.CacheProvider+, which is used by the +CacheManager+ to create all caches. === Configuration From 5b41ad068db877b3c5f3179dced5efa546032b0d Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 17 Sep 2014 17:34:21 +0200 Subject: [PATCH 024/779] Fix merge instructions --- dev.git.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 9f9ec783ef..2334298ad3 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -60,7 +60,7 @@ As such, every contribution gets reviewed by a committer, that effectively commi -- OR -- [start=5] . +git checkout master+; - . +git merge --no-ff --ff-only issue-''+; + . +git merge --no-ff issue-''+; . +git push ehcache master+ to the main repository. Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. From e20a767188e254e5db200098df6cdea3c83cdfce Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 17 Sep 2014 17:49:04 +0200 Subject: [PATCH 025/779] Adding some more info about the merge step when done manually --- dev.git.asciidoc | 1 + 1 file changed, 1 insertion(+) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 2334298ad3..366755acb4 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -61,6 +61,7 @@ As such, every contribution gets reviewed by a committer, that effectively commi [start=5] . +git checkout master+; . +git merge --no-ff issue-''+; + - If this results in something else than having to edit a commit comment - something's wrong, you need to _STOP_ . +git push ehcache master+ to the main repository. Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. From ff1e5121140f29ce3674cfd0f0130241c141da3b Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Tue, 23 Sep 2014 11:11:59 -0400 Subject: [PATCH 026/779] Updated meeting notes and added link to next occurance --- dev.meetings.asciidoc | 55 ++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 52 insertions(+), 3 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 7895bc8a3c..c397dd724c 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,13 +2,62 @@ :toc: -== Sep 18, 2014 - Hangout on Air +== Sep 25, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/cst4usni73q4qkd315qtm8p6rm8[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Next public meeting on https://plus.google.com/u/0/events/cfllsv3gi2p7dmg0l8o28hmmk7c[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST === Agenda -*To be defined* + * Release https://github.com/ehcache/ehcache3/milestones[milestones]: + ** 107 Alpha + ** OSS Beta + * more TBD on the https://groups.google.com/forum/#!forum/ehcache-dev[Ehcache Developer Google Group] + +== Sep 18, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Moved to Cloudbees + +Our build infrastructure is now on Cloudbees here: +https://ehcache.ci.cloudbees.com + +Still need to publish +-SNAPSHOT+ to Sonatype though + +=== Git workflow + +We said we should not +git push --force+ to a branch that's currently under review (because of the PR associated); but rather closing the PR and creating a new one. + +WARNING: This decision has been invalidated since: it's okay to do it, but be vocal about it. One case where you just want to do it, is rebasing your branch should some other PR been merged in between. + +If you do changes based on the feedback from the PR, they probably should be a commit on their own atop of the other + +=== ConcurrentHashMap v8 port + +Is ported from jsr-166 cvs (revision information is recorded in the commit). Still uses +Unsafe+, but lets leave it like that for now (won't work on GAE for instance though). + +Need to have the CHMv8 tests not run everytime (at least not as they stand). + ++JSR166Wrapper+ contains all interfaces to please +javac+ + +Actually make use of CHMv8 in +OnHeapStore+ is still work that's still pending + +Also have a +Unsafe+ wrapper that adds the methods not present in 1.6 + +=== SPI Testing strategy (discussed https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A#t=1503[here]) + +Hung is currently working on a proposal, based on this here: https://gist.github.com/alexsnaps/f42557d008e2ed37f2b1 + +Acceptance criteria: + + * Not runtime dependency on a given testing framework (e.g. junit) + ** but can provide support for testing framework (e.g. to provide nice reporting) + * SPI tester should report a complete run, not stop on first failure it encounters + * A given SPI tester doesn't know about any given implementation, but implementations pull the SPI tester in + * Probably want to make the SPI testers available through maven using some qualifier (e.g. +core:SpiTesters+) + * The https://jcp.org/aboutJava/communityprocess/ec-public/TCK-docs/tsdg.pdf[Java™ Technology Test Suite +Development Guide 1.2] would probably contain some good input on writing actual SPI tests + * SPI tests are probably somewhat easier to write, given that we know where and how (UTSL!) a given SPI is actually used == Sep 11, 2014 - Hangout on Air From e234b8f938822783104054bf2d604b3f48a9d279 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 25 Sep 2014 11:30:38 -0400 Subject: [PATCH 027/779] Added some agenda items --- dev.git.asciidoc | 122 +++++++++++++++++++----------------------- dev.meetings.asciidoc | 2 + 2 files changed, 56 insertions(+), 68 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 366755acb4..dd706d3d45 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -1,68 +1,54 @@ -= Git usage - -:toc: - -== Fork on me GitHub! - - . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; - . +git clone+ that fork to your computer, by default that remote's name will be +origin+; - . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; - . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) - . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; - . You can have as many parallel branches as issues you might be working on; - . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; - -== Initiate a pull request - - . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: - - git pull ehcache - git checkout master - git rebase ehcache/master - git checkout issue- - git rebase master - - . Finally, +git push origin issue-''+ to push your branch to your account; - . You then need to create a pull request, using the UI on GitHub; - . Someone from our team is then going to review it. - -== Have it reviewed - - . The pull request will be reviewed for: - .. 'Correctness': the pull request should wholly and only be about the related issue; - .. 'Style': which needs to match the style of the project; - .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. - . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. - -== Merging a pull request - -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), the way we are looking at this is: - - - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; - - When you are code reviewing someone else's contribution, you do have commit rights. - -As a reviewer, you are expected to verify the following: - - . Branch to be merged is up-to-date with master - . Branch to be merged is pristine - it has not been used in a previous pull request - -As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: - - . +git remote add '' '+ the contributor's ehcache3 repository; - . +git fetch '' issue-''+; - . +git checkout -b issue-'' ''/issue-''+; - . 'do the actual review'; - --- THEN -- -[start=5] - . Use the GitHub UI to do the merge - --- OR -- -[start=5] - . +git checkout master+; - . +git merge --no-ff issue-''+; - - If this results in something else than having to edit a commit comment - something's wrong, you need to _STOP_ - . +git push ehcache master+ to the main repository. - -Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. -Always use a reference to the issue id in the commit message of the merge. += Git usage + +:toc: + +== Fork on me GitHub! + + . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; + . +git clone+ that fork to your computer, by default that remote's name will be +origin+; + . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; + . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) + . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; + . You can have as many parallel branches as issues you might be working on; + . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; + +== Initiate a pull request + + . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: + + git pull ehcache + git checkout master + git rebase ehcache/master + git checkout issue- + git rebase master + + . Finally, +git push origin issue-''+ to push your branch to your account; + . You then need to create a pull request, using the UI on GitHub; + . Someone from our team is then going to review it. + +== Have it reviewed + + . The pull request will be reviewed for: + .. 'Correctness': the pull request should wholly and only be about the related issue; + .. 'Style': which needs to match the style of the project; + .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. + . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. + +== Merging a pull request + +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*. The way we are looking at this is: + + - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; + - When you are code reviewing someone else's contribution, you do have commit rights. + +As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: + + . +git remote add '' '+ the contributor's ehcache3 repository; + . +git fetch '' issue-''+; + . +git checkout -b issue-'' ''/issue-''+; + . 'do the actual review'; + . +git checkout master+; + . +git cherry-pick ..issue-''+; + . +git push ehcache master+ to the main repository. + +The changes are now recorded as authored by the contributor, but committed by the reviewer. That way we also keep a linear timeline on master (where commits have a single parent, à la subversion). diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index c397dd724c..2920890013 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -11,6 +11,8 @@ Next public meeting on https://plus.google.com/u/0/events/cfllsv3gi2p7dmg0l8o28h * Release https://github.com/ehcache/ehcache3/milestones[milestones]: ** 107 Alpha ** OSS Beta + * Recap on SPI Testing + * +CacheLoader+ & +CacheWriter+ lifecycle in +StandaloneCache+ vs. managed ones * more TBD on the https://groups.google.com/forum/#!forum/ehcache-dev[Ehcache Developer Google Group] == Sep 18, 2014 - Hangout on Air From 5d2ec84133ab4dd599fdb7e151de92e006bb07a8 Mon Sep 17 00:00:00 2001 From: alexsnaps Date: Mon, 29 Sep 2014 18:45:56 -0700 Subject: [PATCH 028/779] Revert e20a767188e254e5db200098df6cdea3c83cdfce...e234b8f938822783104054bf2d604b3f48a9d279 on dev.git --- dev.git.asciidoc | 122 ++++++++++++++++++++++++++--------------------- 1 file changed, 68 insertions(+), 54 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index dd706d3d45..366755acb4 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -1,54 +1,68 @@ -= Git usage - -:toc: - -== Fork on me GitHub! - - . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; - . +git clone+ that fork to your computer, by default that remote's name will be +origin+; - . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; - . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) - . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; - . You can have as many parallel branches as issues you might be working on; - . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; - -== Initiate a pull request - - . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: - - git pull ehcache - git checkout master - git rebase ehcache/master - git checkout issue- - git rebase master - - . Finally, +git push origin issue-''+ to push your branch to your account; - . You then need to create a pull request, using the UI on GitHub; - . Someone from our team is then going to review it. - -== Have it reviewed - - . The pull request will be reviewed for: - .. 'Correctness': the pull request should wholly and only be about the related issue; - .. 'Style': which needs to match the style of the project; - .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. - . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. - -== Merging a pull request - -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), *don't use the github UI to merge*. The way we are looking at this is: - - - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; - - When you are code reviewing someone else's contribution, you do have commit rights. - -As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: - - . +git remote add '' '+ the contributor's ehcache3 repository; - . +git fetch '' issue-''+; - . +git checkout -b issue-'' ''/issue-''+; - . 'do the actual review'; - . +git checkout master+; - . +git cherry-pick ..issue-''+; - . +git push ehcache master+ to the main repository. - -The changes are now recorded as authored by the contributor, but committed by the reviewer. That way we also keep a linear timeline on master (where commits have a single parent, à la subversion). += Git usage + +:toc: + +== Fork on me GitHub! + + . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; + . +git clone+ that fork to your computer, by default that remote's name will be +origin+; + . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; + . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) + . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; + . You can have as many parallel branches as issues you might be working on; + . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; + +== Initiate a pull request + + . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: + + git pull ehcache + git checkout master + git rebase ehcache/master + git checkout issue- + git rebase master + + . Finally, +git push origin issue-''+ to push your branch to your account; + . You then need to create a pull request, using the UI on GitHub; + . Someone from our team is then going to review it. + +== Have it reviewed + + . The pull request will be reviewed for: + .. 'Correctness': the pull request should wholly and only be about the related issue; + .. 'Style': which needs to match the style of the project; + .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. + . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. + +== Merging a pull request + +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), the way we are looking at this is: + + - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; + - When you are code reviewing someone else's contribution, you do have commit rights. + +As a reviewer, you are expected to verify the following: + + . Branch to be merged is up-to-date with master + . Branch to be merged is pristine - it has not been used in a previous pull request + +As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: + + . +git remote add '' '+ the contributor's ehcache3 repository; + . +git fetch '' issue-''+; + . +git checkout -b issue-'' ''/issue-''+; + . 'do the actual review'; + +-- THEN -- +[start=5] + . Use the GitHub UI to do the merge + +-- OR -- +[start=5] + . +git checkout master+; + . +git merge --no-ff issue-''+; + - If this results in something else than having to edit a commit comment - something's wrong, you need to _STOP_ + . +git push ehcache master+ to the main repository. + +Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. +Always use a reference to the issue id in the commit message of the merge. From 8acca33d5f986c6fef1dced923af17013d113acc Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 2 Oct 2014 11:08:40 -0400 Subject: [PATCH 029/779] Updated with today's meeting info --- dev.meetings.asciidoc | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 2920890013..7c956b548a 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,12 +2,23 @@ :toc: -== Sep 25, 2014 - Hangout on Air +== Oct 2, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/cfllsv3gi2p7dmg0l8o28hmmk7c[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Next public meeting on https://plus.google.com/u/0/events/chnb8fkd2afivtn7h6h9v8f06ng[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST === Agenda + * What should a +Cache+ if everything gets veto'ed from being evicted? + * +CacheLoader+ & +CacheWriter+ only for implementing the Cache Through pattern? + ** Some background https://www.youtube.com/watch?v=a8LzwqZNfYE&list=UU43PVCp2j0b2og2DtxNOU1A[here in this previous meeting] + * Mocking time in tests + +== Sep 25, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=KaOagtwTHyw&index=2&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda (sorry, hadn't had time to review it yet) + * Release https://github.com/ehcache/ehcache3/milestones[milestones]: ** 107 Alpha ** OSS Beta From 695e0805fabe7e9b2663926b52b1b5b9a82f402e Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 2 Oct 2014 11:32:34 -0400 Subject: [PATCH 030/779] EOL ? --- dev.git.asciidoc | 136 +++++++++++++++++++++++------------------------ 1 file changed, 68 insertions(+), 68 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 366755acb4..586b9cb21d 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -1,68 +1,68 @@ -= Git usage - -:toc: - -== Fork on me GitHub! - - . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; - . +git clone+ that fork to your computer, by default that remote's name will be +origin+; - . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; - . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) - . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; - . You can have as many parallel branches as issues you might be working on; - . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; - -== Initiate a pull request - - . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: - - git pull ehcache - git checkout master - git rebase ehcache/master - git checkout issue- - git rebase master - - . Finally, +git push origin issue-''+ to push your branch to your account; - . You then need to create a pull request, using the UI on GitHub; - . Someone from our team is then going to review it. - -== Have it reviewed - - . The pull request will be reviewed for: - .. 'Correctness': the pull request should wholly and only be about the related issue; - .. 'Style': which needs to match the style of the project; - .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. - . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. - -== Merging a pull request - -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), the way we are looking at this is: - - - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; - - When you are code reviewing someone else's contribution, you do have commit rights. - -As a reviewer, you are expected to verify the following: - - . Branch to be merged is up-to-date with master - . Branch to be merged is pristine - it has not been used in a previous pull request - -As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: - - . +git remote add '' '+ the contributor's ehcache3 repository; - . +git fetch '' issue-''+; - . +git checkout -b issue-'' ''/issue-''+; - . 'do the actual review'; - --- THEN -- -[start=5] - . Use the GitHub UI to do the merge - --- OR -- -[start=5] - . +git checkout master+; - . +git merge --no-ff issue-''+; - - If this results in something else than having to edit a commit comment - something's wrong, you need to _STOP_ - . +git push ehcache master+ to the main repository. - -Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. -Always use a reference to the issue id in the commit message of the merge. += Git usage + +:toc: + +== Fork on me GitHub! + + . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; + . +git clone+ that fork to your computer, by default that remote's name will be +origin+; + . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; + . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) + . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; + . You can have as many parallel branches as issues you might be working on; + . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; + +== Initiate a pull request + + . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: + + git pull ehcache + git checkout master + git rebase ehcache/master + git checkout issue- + git rebase master + + . Finally, +git push origin issue-''+ to push your branch to your account; + . You then need to create a pull request, using the UI on GitHub; + . Someone from our team is then going to review it. + +== Have it reviewed + + . The pull request will be reviewed for: + .. 'Correctness': the pull request should wholly and only be about the related issue; + .. 'Style': which needs to match the style of the project; + .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. + . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. + +== Merging a pull request + +If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), the way we are looking at this is: + + - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; + - When you are code reviewing someone else's contribution, you do have commit rights. + +As a reviewer, you are expected to verify the following: + + . Branch to be merged is up-to-date with master + . Branch to be merged is pristine - it has not been used in a previous pull request + +As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: + + . +git remote add '' '+ the contributor's ehcache3 repository; + . +git fetch '' issue-''+; + . +git checkout -b issue-'' ''/issue-''+; + . 'do the actual review'; + +-- THEN -- +[start=5] + . Use the GitHub UI to do the merge + +-- OR -- +[start=5] + . +git checkout master+; + . +git merge --no-ff issue-''+; + - If this results in something else than having to edit a commit comment - something's wrong, you need to _STOP_ + . +git push ehcache master+ to the main repository. + +Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. +Always use a reference to the issue id in the commit message of the merge. From 233c37792026d62560acd33616f04612c50f74e7 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 2 Oct 2014 12:54:24 -0400 Subject: [PATCH 031/779] Added agenda item for today --- dev.meetings.asciidoc | 1 + 1 file changed, 1 insertion(+) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 7c956b548a..5abb2e6855 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -8,6 +8,7 @@ Next public meeting on https://plus.google.com/u/0/events/chnb8fkd2afivtn7h6h9v8 === Agenda + * Project structure and especially the spi-tester sources * What should a +Cache+ if everything gets veto'ed from being evicted? * +CacheLoader+ & +CacheWriter+ only for implementing the Cache Through pattern? ** Some background https://www.youtube.com/watch?v=a8LzwqZNfYE&list=UU43PVCp2j0b2og2DtxNOU1A[here in this previous meeting] From 541688fe78e9f3e4951763eba3ab6f6111cce3e6 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 9 Oct 2014 13:15:22 -0400 Subject: [PATCH 032/779] Added last week's and this week's link --- dev.meetings.asciidoc | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 5abb2e6855..63c596bb4d 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,9 +2,18 @@ :toc: +== Oct 9, 2014 - Hangout on Air + +Next public meeting on https://plus.google.com/u/0/events/cj6gm8bll8ckvqsm8te64nt7pio[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST + +=== Agenda + + * +EhcacheManager+ & +Ehcache+ implicit contract nailed ? + * Lifecycle and state transitions + == Oct 2, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/chnb8fkd2afivtn7h6h9v8f06ng[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Recording available https://www.youtube.com/watch?v=YgfsRhQPT7k&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] === Agenda From 4a4e255a9433990b1714a18802dc271272be2fda Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Fri, 10 Oct 2014 23:22:16 -0400 Subject: [PATCH 033/779] Updated dev meeting links --- dev.meetings.asciidoc | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 63c596bb4d..1d12aad26a 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,9 +2,17 @@ :toc: +== Oct 16, 2014 - Hangout on Air + +Next public meeting on https://plus.google.com/u/0/events/cljv4s8a52pqo36bh8r2afaiu1s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST + +=== Agenda + + * tbd + == Oct 9, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/cj6gm8bll8ckvqsm8te64nt7pio[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Recording available https://www.youtube.com/watch?v=P_P641-hkPs&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] === Agenda From 6853f4a5c6eda33b8524b25085a148aba8287457 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 22 Oct 2014 10:36:51 -0400 Subject: [PATCH 034/779] Updated the dev meeting details --- dev.meetings.asciidoc | 20 ++++++++++++++++++-- 1 file changed, 18 insertions(+), 2 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 1d12aad26a..6be1fe94c3 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,13 +2,29 @@ :toc: +== Oct 23, 2014 - Hangout on Air + +Next public meeting on https://plus.google.com/events/cdg21t736v4k8i57aacnlmdbnsc[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST + +=== Agenda + +Candidates up for discussion this week so far, probably can't cover all of them though: + + * Exception hierarchy + * Logging (levels, i18n, ...) + * XML Config + == Oct 16, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/cljv4s8a52pqo36bh8r2afaiu1s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Recording available https://www.youtube.com/watch?v=HWi7H7glR_o&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] === Agenda - * tbd + * https://github.com/ehcache/ehcache3/pull/109[PR #109] on `ClassLoader` per `Cache` + ** Should it be a `Service` or do we want to keep it as in the PR? + ** Let's revisit this based on user sample code we plan on doing after the _107 Alpha_ + * Update the `README` to explain how to get to this though _sonatype_ + * _107 Alpha_ to be released as `3.0.0-Alpha` to central == Oct 9, 2014 - Hangout on Air From 3f278386810fafe911e5a68974a784ddfdba574e Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Fri, 24 Oct 2014 14:49:56 -0400 Subject: [PATCH 035/779] Dev meeting update and dev guidelines --- Home.asciidoc | 2 +- dev.git.asciidoc | 1 + dev.guidelines.asciidoc | 69 +++++++++++++++++++++++++++++++++++++++++ dev.meetings.asciidoc | 20 +++++++++--- 4 files changed, 86 insertions(+), 6 deletions(-) create mode 100644 dev.guidelines.asciidoc diff --git a/Home.asciidoc b/Home.asciidoc index 4abd4a98ca..400f81bdbe 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -17,7 +17,7 @@ On paper (or on this screen), it's pretty straight forward: . If the task exists already and isn't assigned: drop us an email on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] about it and we'll make sure we help you getting started and we'll assign the task/issue to you; . If nothing matches in the existing issue list, create a bug as such; or, if we're talking about a larger task or feature, https://groups.google.com/forum/#!forum/ehcache-dev[drop us a message] first, and we'll see how to tackle it; . https://github.com/ehcache/ehcache3/fork[Fork] the project to your own repository and get started (you probably want to work on a dedicated branch); - . Rebase your fork and do a pull request. We'll use that to code review it (see link:dev.git[git usage page]) + . Rebase your fork and do a pull request. We'll use that to code review it (see link:dev.git[git usage page] as well as the link:dev.guidelines[developer guidelines]) . Be rich and famous! Now, the doing the work part might be a little more challenging, and we don't provide any guarantees as to becoming rich... but you'll be famous to us! diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 586b9cb21d..3a2a463d9f 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -32,6 +32,7 @@ .. 'Correctness': the pull request should wholly and only be about the related issue; .. 'Style': which needs to match the style of the project; .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. + .. You can look up link:dev.guidelines[general developer guidelines] as well . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. == Merging a pull request diff --git a/dev.guidelines.asciidoc b/dev.guidelines.asciidoc new file mode 100644 index 0000000000..076418cc6c --- /dev/null +++ b/dev.guidelines.asciidoc @@ -0,0 +1,69 @@ += Developer guidelines + +:toc: + +These are some things to consider when you add code to Ehcache, but certainly when you review a PR! + +== Formatting + +See what's there for now... Ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. We'll export settings for majors IDEs here asap. + +== Unit testing + +All changes need to come with appropriate test coverage. + +=== Adding code + +All this new code you add should have test coverage. + +=== Breaking existing tests + +Should you break an existing test, take great care before touching the test code to "fix it". While it could definitively be that the test is wrong, it may be correct as well. Always assume the latter is true first. If in doubt, again, ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. + +Changing an existing test for it to pass, because of you recent changes, should really be the last resort. Other than for compilation obviously, or adding mocks and the like. + +=== SPI tests + +We have an SPI module that covers testing functionality that needs to be provided by a given SPI, e.g. `org.ehcache.spi.cache.Store`. + +WARNING: work in progress + +== Logging + +We use `slf4j` for all our logging here... + +=== Log levels + +What level should be used for logging should be dependent on whether you log for the user's benefit (e.g. lifecycle), debugging purposes (a standard `Cache.get(K): V` path). But we don't log `WARN` or `ERROR`. + +==== At `INFO` level + +We log things about lifecycle: + + * Bootstrapping `CacheManager`, + * Adding, removing `Cache` to CacheManager + * ... + +Basically everything that would be informational to the end-user. + +==== Level `DEBUG` and below + +Helps us trace stuff, when some weird scenario is being debugged. + + * Delegating to `CacheLoader`, + * Delegating to `ResilienceStrategy`, + * `Store` internals... + +==== Levels `WARN` & `ERROR` + +Nothing really, if that level is required, we would rather want to throw! + +== Javadoc + +=== Public types + +Needs to be fully Javadoc'ed + +=== Internal concrete classes + +Require at least class-level Javadoc. But we value clear method, arguments and variable names above all here. diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 6be1fe94c3..d492374577 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,17 +2,27 @@ :toc: -== Oct 23, 2014 - Hangout on Air +== Oct 30, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/events/cdg21t736v4k8i57aacnlmdbnsc[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Next public meeting on https://plus.google.com/u/0/events/caba2lh0jeheppd54tnsqv4jrrc[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST === Agenda -Candidates up for discussion this week so far, probably can't cover all of them though: + * XML Configuration, + * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. + +== Oct 23, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda * Exception hierarchy - * Logging (levels, i18n, ...) - * XML Config + ** Conclusion being we postpone deciding what we do, until we tackle the OSS Beta milestone. 107 dictates what we need to do now anways + * https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A#t=2387[Logging (levels, i18n, ...)] + ** `INFO`: Logs lifecycle stuff + ** `WARN`/`ERROR`: We don't log, but throw + ** `DEBUG`/`TRACE`: Regular ops stuff, including delegating to the `ResilienceStrategy` == Oct 16, 2014 - Hangout on Air From b6dacc92af30ac0234ed9f2f314083fad40860c9 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 6 Nov 2014 11:30:30 -0500 Subject: [PATCH 036/779] Updated meeting notes --- dev.meetings.asciidoc | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index d492374577..c60982a50e 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,15 +2,31 @@ :toc: -== Oct 30, 2014 - Hangout on Air +== Nov 6, 2014 - Hangout on Air Next public meeting on https://plus.google.com/u/0/events/caba2lh0jeheppd54tnsqv4jrrc[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST === Agenda * XML Configuration, + ** How should we parse it? + ** Alex's crazy extension idea for 107 idea * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. +== Oct 30, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * _Expiry_ to be the Store's concern, just as eviction is + ** Store doesn't know about the public event listeners though, uses internal private mechanism + ** An entry, being present but expired, is considered absent (i.e. a `Cache.putIfAbsent` would succeed). + ** `ValueHolder` probably can go now too + * `storeByValue`, see https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=737[here] + (and followed up on https://groups.google.com/forum/#!topic/ehcache-dev/RoY-P6Zm9tc[ML]) + * Some XML stuff as of https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=2001[here] + == Oct 23, 2014 - Hangout on Air Recording available https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] From 108bdf45b0464f0c4e6846db62007a3cbdafafd6 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 6 Nov 2014 11:31:41 -0500 Subject: [PATCH 037/779] Updated meeting notes --- dev.meetings.asciidoc | 1 + 1 file changed, 1 insertion(+) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index c60982a50e..a5bad37b8a 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -8,6 +8,7 @@ Next public meeting on https://plus.google.com/u/0/events/caba2lh0jeheppd54tnsqv === Agenda + * Überjar! * XML Configuration, ** How should we parse it? ** Alex's crazy extension idea for 107 idea From fa27cd113903daa6686fefb3d9949d5153ff4ac2 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Thu, 13 Nov 2014 12:44:44 -0500 Subject: [PATCH 038/779] Dev meeting update --- dev.meetings.asciidoc | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index a5bad37b8a..32696a961f 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,9 +2,18 @@ :toc: +== Nov 13, 2014 - Hangout on Air + +Next public meeting on https://plus.google.com/u/0/events/cv6v25r855jsn078tebkcbead2s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST + +=== Agenda + + * Stats + * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. + == Nov 6, 2014 - Hangout on Air -Next public meeting on https://plus.google.com/u/0/events/caba2lh0jeheppd54tnsqv4jrrc[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST +Recording available https://www.youtube.com/watch?v=9CUnb5np5WM&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] === Agenda @@ -12,7 +21,6 @@ Next public meeting on https://plus.google.com/u/0/events/caba2lh0jeheppd54tnsqv * XML Configuration, ** How should we parse it? ** Alex's crazy extension idea for 107 idea - * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. == Oct 30, 2014 - Hangout on Air From e95dd6295a637ada42e9b7aaae1aa6d0a7125253 Mon Sep 17 00:00:00 2001 From: chrisdennis Date: Thu, 20 Nov 2014 12:33:56 -0800 Subject: [PATCH 039/779] Updated dev.meetings (asciidoc) --- dev.meetings.asciidoc | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/dev.meetings.asciidoc b/dev.meetings.asciidoc index 32696a961f..b5ad7ae8e4 100644 --- a/dev.meetings.asciidoc +++ b/dev.meetings.asciidoc @@ -2,6 +2,14 @@ :toc: +== Nov 20, 2014 - Hangout on Air - Rogue Edition + +Recording available https://www.youtube.com/watch?v=efCPffwBvaQ[here on YouTube] + +=== Agenda + + * putIfAbsent and CacheWriters + == Nov 13, 2014 - Hangout on Air Next public meeting on https://plus.google.com/u/0/events/cv6v25r855jsn078tebkcbead2s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST @@ -283,4 +291,4 @@ Created issue #21 . *Hibernate* to be integrated within the h2lc module there . *Groovy*, either: .. @candrews takes ownership, or - .. we find someone within TC/SAG to do so (unidentified yet though) + .. we find someone within TC/SAG to do so (unidentified yet though) \ No newline at end of file From 4242c1e9e5f4a173c61ff0db357b55e8ce7860f5 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 28 Jan 2015 14:59:54 -0500 Subject: [PATCH 040/779] Architecture details --- Home.asciidoc | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/Home.asciidoc b/Home.asciidoc index 400f81bdbe..7577ce10e7 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -38,9 +38,13 @@ The code core of Ehcache is split in three core modules: === Modular approach -+org.ehcache.spi.service.ServiceFactory+ are used to create +org.ehcache.spi.service.Service+, configured through +org.ehcache.spi.service.ServiceConfiguration+. Each of those services can be about anything. +==== Services -A special kind of +Service+ is the +org.ehcache.spi.cache.CacheProvider+, which is used by the +CacheManager+ to create all caches. +A `CacheManager` manages `Cache` instances, but also `Service` instances that can be used by either `Cache` or other `Service` instances. An example of `Service` being the `org.ehcache.spi.cache.Store.Provider`, it's the `Service` the `CacheManager` will use to create the `Store` instance underlying your `Cache`. + +`Service` are created by using the Java's https://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html[`java.util.ServiceLoader` service-provider loading facility]. It is used to locate all `org.ehcache.spi.service.ServiceFactory` implementations on the classpath. These are in turn used to create `Service` instances. Each `CacheManager` uses its own `org.ehcache.spi.ServiceLocator` facility to locate `Service` instances, which it then in turn life cycles. + +`Service` instances are configured by their own respective `ServiceConfiguration` at `Service.start()` invocation time. `CacheManager` and its `Service` instances can then use these services. In the case of the `org.ehcache.spi.cache.Store.Provider` instance, it is being used by the `CacheManager` to create a `Store` to back a `Cache`. Being a direct dependency of `Ehcache`, that `Service` interface is part of the core SPI. It defines a `createStore()` method that will be invoked by the `CacheManager` at `Cache` creation time. The `Store.Provider` implementation can introspect not only the `Store.Configuration` passed, but also all `ServiceConfiguration` instances associated with the `Cache` being created in order to decide what `Store` should be created (note: currently it only creates `OnHeapStore`, as this is the only topology supported... more to come). === Configuration From 73522b9b0f38ff5156d5806d496e75b1a864d74a Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 1 Apr 2015 08:27:57 -0400 Subject: [PATCH 041/779] Added general guidelines --- dev.guidelines.asciidoc | 55 ++++++++++++++++++++++++++++++----------- 1 file changed, 41 insertions(+), 14 deletions(-) diff --git a/dev.guidelines.asciidoc b/dev.guidelines.asciidoc index 076418cc6c..70df3c88bb 100644 --- a/dev.guidelines.asciidoc +++ b/dev.guidelines.asciidoc @@ -4,39 +4,66 @@ These are some things to consider when you add code to Ehcache, but certainly when you review a PR! -== Formatting +== General guidelines + +Whenever you start working on an issue, you probably want to consider some, if not all, of the items below: + +=== API changes + +If you need to change the public API (this includes additions), you probably want to start with that first. An easy way to go about that, is to add or modify `GettingStarted` documentation to concretely expose how the API would be affected. You can do this on your branch, as a first commit, and already share it for review with a larger audience, e.g. on the mailing list or through a preliminary pull request. + +=== Design + +Whether API is modified or not, you'll want to consider how you plan to go about implementing it all. There are a couple of specificities of the Ehcache internals that would need to be accounted for: + + . *`Service` additions or modifications*: effectively this is mainly about http://en.wikipedia.org/wiki/Inversion_of_control[IoC] and http://en.wikipedia.org/wiki/Liskov_substitution_principle[LSP], we want subsystems of your feature to be injected and abstracted away behind an interface, that would let the actual implementation easily be replaced with another. We also try to reuse existing `Service` definitions as much as possible. So don't hesitate to slightly tweak an existing one, rather than introducing a new one. + . *Lifecycle*: You'll want to make sure, if at all, how Ehcache's life cycling may affect your change. If anything requires any special life cycling (e.g. `PersistentCacheManager` services), you will have to account for these. + . *Failure*: Most things eventually do go wrong. Whether it's IO, some user provided implementation throwing, the actual `Store` being unaccessible... Things just go wrong. Ehcache tries to never do any harm to the user's application. As such your change should account for failure scenarios and possibly delegate to the `ResilienceStrategy` to enable users to deal with such scenarios sensibly. + +=== Last touches + +Once your change actually implemented (see coding guidelines below), you finally will want to make sure that: + + . You added adequate logging; + . Configuration is complete: + .. XML configuration was added, but that should never drive the actual configuration concerns; + .. XML Templating is correctly supported. + +== Coding guidelines + +=== Formatting See what's there for now... Ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. We'll export settings for majors IDEs here asap. -== Unit testing +=== Unit testing All changes need to come with appropriate test coverage. -=== Adding code +==== Adding code All this new code you add should have test coverage. -=== Breaking existing tests +==== Breaking existing tests Should you break an existing test, take great care before touching the test code to "fix it". While it could definitively be that the test is wrong, it may be correct as well. Always assume the latter is true first. If in doubt, again, ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. Changing an existing test for it to pass, because of you recent changes, should really be the last resort. Other than for compilation obviously, or adding mocks and the like. -=== SPI tests +==== SPI tests We have an SPI module that covers testing functionality that needs to be provided by a given SPI, e.g. `org.ehcache.spi.cache.Store`. WARNING: work in progress -== Logging +=== Logging We use `slf4j` for all our logging here... -=== Log levels +==== Log levels What level should be used for logging should be dependent on whether you log for the user's benefit (e.g. lifecycle), debugging purposes (a standard `Cache.get(K): V` path). But we don't log `WARN` or `ERROR`. -==== At `INFO` level +===== At `INFO` level We log things about lifecycle: @@ -46,7 +73,7 @@ We log things about lifecycle: Basically everything that would be informational to the end-user. -==== Level `DEBUG` and below +===== Level `DEBUG` and below Helps us trace stuff, when some weird scenario is being debugged. @@ -54,16 +81,16 @@ Helps us trace stuff, when some weird scenario is being debugged. * Delegating to `ResilienceStrategy`, * `Store` internals... -==== Levels `WARN` & `ERROR` +===== Levels `WARN` & `ERROR` Nothing really, if that level is required, we would rather want to throw! -== Javadoc +=== Javadoc -=== Public types +==== Public types Needs to be fully Javadoc'ed -=== Internal concrete classes +==== Internal concrete classes -Require at least class-level Javadoc. But we value clear method, arguments and variable names above all here. +Require at least class-level Javadoc. But we value clear method, arguments and variable names above all here. \ No newline at end of file From 83e0791ffe933705cc9c6c77b0b1aba224218643 Mon Sep 17 00:00:00 2001 From: Chris Dennis Date: Wed, 1 Apr 2015 10:47:40 -0400 Subject: [PATCH 042/779] a handful of minor corrections --- dev.guidelines.asciidoc | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/dev.guidelines.asciidoc b/dev.guidelines.asciidoc index 70df3c88bb..b6d7c40bff 100644 --- a/dev.guidelines.asciidoc +++ b/dev.guidelines.asciidoc @@ -16,15 +16,15 @@ If you need to change the public API (this includes additions), you probably wan Whether API is modified or not, you'll want to consider how you plan to go about implementing it all. There are a couple of specificities of the Ehcache internals that would need to be accounted for: - . *`Service` additions or modifications*: effectively this is mainly about http://en.wikipedia.org/wiki/Inversion_of_control[IoC] and http://en.wikipedia.org/wiki/Liskov_substitution_principle[LSP], we want subsystems of your feature to be injected and abstracted away behind an interface, that would let the actual implementation easily be replaced with another. We also try to reuse existing `Service` definitions as much as possible. So don't hesitate to slightly tweak an existing one, rather than introducing a new one. - . *Lifecycle*: You'll want to make sure, if at all, how Ehcache's life cycling may affect your change. If anything requires any special life cycling (e.g. `PersistentCacheManager` services), you will have to account for these. - . *Failure*: Most things eventually do go wrong. Whether it's IO, some user provided implementation throwing, the actual `Store` being unaccessible... Things just go wrong. Ehcache tries to never do any harm to the user's application. As such your change should account for failure scenarios and possibly delegate to the `ResilienceStrategy` to enable users to deal with such scenarios sensibly. + . *`Service` additions or modifications*: this is mainly about http://en.wikipedia.org/wiki/Inversion_of_control[IoC] and http://en.wikipedia.org/wiki/Liskov_substitution_principle[LSP], we want subsystems of your feature to be both injected and abstracted away behind an interface. This allows the actual implementation to be easily replaced with another. We also try to reuse existing `Service` definitions as much as possible. So don't hesitate to slightly tweak an existing one, rather than introducing a new one. + . *Lifecycle*: You'll want to assess how Ehcache's life cycling may affect your change (if at all). If anything requires any special life cycling (e.g. `PersistentCacheManager` services), you will have to account for this. + . *Failure*: Most things eventually do go wrong. Whether it's IO, some user provided implementation throwing, the actual `Store` being unaccessible... things just go wrong. Ehcache tries to never do any harm to the user's application. As such your change should account for failure scenarios and possibly delegate to the `ResilienceStrategy` to enable users to deal with such scenarios sensibly. === Last touches -Once your change actually implemented (see coding guidelines below), you finally will want to make sure that: +Once your change is implemented (see coding guidelines below), you will want to make sure that: - . You added adequate logging; + . You added adequate (but not excessive) logging; . Configuration is complete: .. XML configuration was added, but that should never drive the actual configuration concerns; .. XML Templating is correctly supported. From ba7994599bebc68566af170b47e5e4a9f42b4f7b Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Mon, 13 Apr 2015 08:17:34 -0400 Subject: [PATCH 043/779] More info --- module.api.asciidoc | 36 +++++++++++++++++++++++++++--------- module.core.asciidoc | 24 ++++++++++++++++++++++-- 2 files changed, 49 insertions(+), 11 deletions(-) diff --git a/module.api.asciidoc b/module.api.asciidoc index 939c6147f9..d29838d63d 100644 --- a/module.api.asciidoc +++ b/module.api.asciidoc @@ -4,12 +4,30 @@ == API Module -Contains all the interfaces, as well as exceptions, an Ehcache user would use explicitly. This includes: - - . Core types - .. +CacheManager+ - .. +Cache+ - . Configuration types - .. +CacheConfiguration+ - .. +ServiceConfiguration+ - . Exceptions +Contains all the interfaces, as well as exceptions, an Ehcache user would use explicitly. As a rule of thumb, you rarely want any actual code in this module. And when adding an interface, it should be a care one to the library, either from a user perspective, or from a SPI one. + +=== `CacheManager` and its `Cache` instances + +The `CacheManager` not only acts as a repository of `Cache` instances, but it also lifecycles them. The `CacheManager` is also responsible for lifecycling `Service` instances. These `Service` instances are provided by the `CacheManager` for its `Cache` instances to use. The `Cache` and `Service` instances can look up any `Service` by it's type by querying the `ServiceLocator`. + +`CacheManager` and `Cache` are two of the most important interfaces into Ehcache. They get supplemented by other interfaces such as `Expiry`, `CacheEvent` and other satellite types. + +=== Configuration types + +In order to create a `CacheManager`, you need to have a `CacheConfiguration` for each and every `Cache` instance you want to use. You also may need to configure some additional `Service` instances one or some of your `Cache` need (see below). + +A `CacheConfiguration` is read-only and as such immutable. The new `RuntimeCacheConfiguration` type exposes additional mutative methods on parameters that are tunable at runtime (i.e. once a `Cache` is in `Status.AVAILABLE`). + +=== SPI types + +In + +==== User-facing SPIs + +==== Generic `Service` instances and their `ServiceConfiguration` + +==== The `ServiceLocator` + +Every `CacheManager` has its own `ServiceLocator` instance. The `ServiceLocator` acts as a repository of concrete `Service` which can then be looked up by type. The `Service` instances it knows about are the ones provided to it at `CacheManager` construction time. `Service` instances can be injected directly, but will more generally be declared for use by providing a matching `ServiceConfiguration` to the `CacheManagerBuilder`. Not all `Service` are necessarily required to be user facing (through one of their `ServiceConfiguration` for instance). If a requested `Service` can't be found, it'll be looked up using Java's `ServiceLoader` facility from the classpath. + +The `ServiceLoader` fallback for `Service` lookups can be used by the end-user, but is expected to be used mainly by _anyone_ building an *Ehcache Distribution* (i.e. a so-called _überjar_ created by some mean from all the different modules that composes it). The idea is to only couple different `Service` to the minimal and the strictly required level. diff --git a/module.core.asciidoc b/module.core.asciidoc index 174bbf935e..5156d75178 100644 --- a/module.core.asciidoc +++ b/module.core.asciidoc @@ -6,14 +6,34 @@ Contains the +ServiceLocator+, as well as core SPI interfaces. +=== `CacheManager` and its `Cache` instances + +The `CacheManager` not only acts as a repository of `Cache` instances, but it also lifecycles them. The `CacheManager` is also responsible for lifecycling `Service` instances. These `Service` instances are provided by the `CacheManager` for its `Cache` instances to use. The `Cache` and `Service` instances can look up any `Service` by it's type by querying the `ServiceLocator`. + +==== The `ServiceLocator` + +Every `CacheManager` has its own `ServiceLocator` instance. The `ServiceLocator` acts as a repository of concrete `Service` which can then be looked up by type. The `Service` instances it knows about are the ones provided to it at `CacheManager` construction time. `Service` instances can be injected directly, but will more generally be declared for use by providing a matching `ServiceConfiguration` to the `CacheManagerBuilder`. Not all `Service` are necessarily required to be user facing (through one of their `ServiceConfiguration` for instance). If a requested `Service` can't be found, it'll be looked up using Java's `ServiceLoader` facility from the classpath. + +The `ServiceLoader` fallback for `Service` lookups can be used by the end-user, but is expected to be used mainly by _anyone_ building an *Ehcache Distribution* (i.e. a so-called _überjar_ created by some mean from all the different modules that composes it). The idea is to only couple different `Service` to the minimal and the strictly required level. + +=== Configuration types + +==== Minimal configurations + +In order to create a `CacheManager`, you need to configure `CacheConfiguration` for each and every `Cache` instance you want to use. You also may need to configure some additional `Service` instances one or some of your `Cache` need. Whether configured directly at the `CacheManager` level, or at the `Cache` level, a given `ServiceConfiguration` will be used by a single `Service` instance. But the `Service` itself may configure itself further for a given `Cache`. + +==== The `interface Store.Provider extends Service` as an example + +There will be only one `Store.Provider` instance registered for that type that the `CacheManager` will lookup using the `ServiceLocator` when creating a `Cache` instance. The `Store.Provider` acts as a _factory_ for `Store` instances. That factory may delegate to specialized implementations of `Store.Provider` it _knows_ about (e.g. `OnHeapStoreProvider`, `DiskStoreProvider`, ...) by looking at the `Store.Configuration` it's been asked to configure the `Store` instance for. + +What that `Store.Provider` instance it'll be can either be specified by injecting one directly into the `ServiceLocator` backing up the `CacheManager` to create the `Cache` instances. Or have it fallback to the _classpath_ of the application to resolve one. Where the `ServiceLoader` facility is only resorted to, if none injected instance could be found. + === Services ==== ServiceProvider === SPI's -==== CacheProvider - ==== Cache Store ==== Tiering interfaces From 37ca9769b4956c7753c816999d9231d5349a5a0a Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Mon, 13 Apr 2015 10:20:37 -0400 Subject: [PATCH 044/779] Initial design.basics stuff --- design.basics.asciidoc | 109 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 design.basics.asciidoc diff --git a/design.basics.asciidoc b/design.basics.asciidoc new file mode 100644 index 0000000000..856065d1d7 --- /dev/null +++ b/design.basics.asciidoc @@ -0,0 +1,109 @@ += Ehcache Design Fundamentals + +:toc: + +== `CacheManager`, `Cache` and their dependencies + +As in the 1.x & 2.x line, Ehcache has the notion of a `CacheManager`, who manages `Cache` instances. Managing a `Cache` +means fulfilling a couple of roles: + + - Life cycling it: e.g. `.init()`, `.closing()` the `Cache`; + - Providing it with `Service` instance: A `CacheManager` comes with a set of base abstract services `Cache` can use + and that it will lifecycle too; but the `CacheManager` can lifecycle any amount of additional `Service` types that + gets registered with it. These `Service` can then be looked up, e.g. by `Cache` or other `Service` instances, using the + `ServiceProvider` interface; + - Finally, the `CacheManager` acts as a repository of alias'ed `Cache` instances. Unlike in the previous versions, `Cache` + instances aren't named, but are registered with the `CacheManager` under an _alias_. The `Cache` is never aware of it. + +This diagram tries to summarize the different roles: + +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/baseTypes.png[Base Types] + +A user will only mostly interact with the `CacheManager` and `Cache` API types... He may need to configure specific +`Service` types for his `Cache` instances to use. See <> + +=== The `CacheManager` + +While the `CacheManager` does act as a repository, it is _not_ possible to add a `Cache` directly to a `CacheManager`. +A `Cache` can be created by a `CacheManager`, which will then keep a reference to it, alias'ed to a user provided name. +To remove that `Cache` from the `CacheManager`, it has to be explicitly removed using `CacheManager.removeCache(String)`. +Upon that method successfully returning, the `Cache` 's status will be `Status.UNINITIALIZED` and as such will not be +usable anymore, see <> section below. + +=== The `Cache` + +A `Cache` is backed by a `Store` where all cached entries (i.e. key to value mappings) are held. The `Cache` doesn't know +what topology this `Store` is using; whether it's storing these entries on the JVM's heap, off the heap, on disk, on a remote +JVM or any combination of the above. + +When a `Cache` is being constructed, e.g. by the `CacheManager` on a `.createCache()` method invoke, the `CacheManager` +will lookup a `Store.Provider` which is one of the bundled `Service` types of Ehcache, asking it to create a `Store` based +on the `CacheConfiguration` used to configure the given `Cache`. That indirection, makes both the `Cache` as well as the +`CacheManager` ignorant of what topology this `Cache` is to use. Ehcache comes with a `DefaultStoreProvider` that will +be loaded by the `ServiceProvider`, should one be explicitly provided. That in turn will resolve the required `Store` +instance to be provided to the `Cache` being created. + +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/cacheStore.png[Cache's Store] + +The `Cache` also tries to never _fails_ on operations invoked, e.g. a get shouldn't result in throwing an exception if the +`Store` that backs it up uses serialization and fails to retrieve the mapping. Instead, Ehcache tries to be resilient and +should try to clear that mapping from its `Store` and return `null` instead to the user. It is the responsibility of the +`Cache` to handle the exceptions a `Store` may throw (the `Store` interface explicitly declares it throws +`CacheAccessException`, which is a checked exception). The `Cache` will delegate failures to the `ResilienceStrategy`, +which in turn is responsible for handling the failure. + +Currently, Ehcache only has a single `ResilienceStrategy`, which is supporting single-JVM deployments, and will try to +_heal_ the `Store` on failure and making the invoking action on a `Cache` a no-op. We'll add more `ResilienceStrategy` +and will make it pluggable, when we move on to distributed topologies. + +=== The new `UserManagedCache` + +The `UserManagedCache` are, as the name implies, managed by the user instead of being managed by a `CacheManager`. While +these instances a meant to be lightweight, short-lived ones, nothing prohibits a user from building a distributed +`UserManagedCache` if so desired. + +As the user manages that instance himself, he needs to provide all `Service` instances required by the `UserManagedCache`. +Also he'll need to invoke lifecycle methods on it (see <>) and finally keep a reference to it, as it +won't available in any `CacheManager`. + +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/userManagedCache.png[UserManagedCache] + +== State transitions + +A lifecycled instance, e.g. a `CacheManager` or a `UserManagedCache`, have three states represented by the +`org.ehcache.Status` enum: + + . `UNINITIALIZED`: The instance can't be used, it probably just got instantiated or got `.close()` invoked on it; + . `MAINTENANCE`: The instance is only usable by the thread that got the _maintenance lease_ for it. Special maintenance + operations can be performed on the instance; + . `AVAILABLE`: The operational state of the instance, all operations can be performed by any amount of threads. + +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/stateTransitions.png[Statuses & transitions] + +State should only be maintained at the _higher_ user-visible API instance, e.g. a concrete `Cache` instance like `Ehcache`. +That means that it is the warrant for blocking operations during state transitions or on an _illegal state_. No need for +the underlying data structure to do so too (e.g. `Store`), as this would come to much higher cost during runtime. + +NOTE: A generic utility class `StatusTransitioner` encapsulate that responsibility and should be reusable across types that +require enforcing lifecycle constraints. + +== Configuration types and builders + +In the most generic sense, configuration types are used to _configure_ a given service _while_ it's being constructed. A +builder exposes a user-friendly DSL to configure and build _runtime instances_ (e.g. `CacheManager`). Finally runtime +configuration types are configured from configuration types and used at runtime by the actual configured instance, +providing a way for the user to mutate the behavior of that instance at runtime in limited ways. + +=== Configurations + +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/config.png[Configuration types] + +=== Builder guidelines + +== The `PersistentCacheManager` + +=== `CacheManagerBuilder.with()` 's extension point + +=== Locally persistent + +=== Clustered topology From 7d224dfb3f025808cfbc2a0c108fcb7a83305697 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Tue, 14 Apr 2015 13:50:52 -0400 Subject: [PATCH 045/779] CRUD doc stuff --- design.basics.asciidoc | 92 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 90 insertions(+), 2 deletions(-) diff --git a/design.basics.asciidoc b/design.basics.asciidoc index 856065d1d7..190140aa1b 100644 --- a/design.basics.asciidoc +++ b/design.basics.asciidoc @@ -94,16 +94,104 @@ builder exposes a user-friendly DSL to configure and build _runtime instances_ ( configuration types are configured from configuration types and used at runtime by the actual configured instance, providing a way for the user to mutate the behavior of that instance at runtime in limited ways. -=== Configurations +=== Configuring stuff + +You don't necessarily ever get exposed to a _configuration_ for a given type being constructed. The builder can hide it +all from you and will create the actual configuration at `.build()` invocation time. Configuration types are always +immutable. Instances of these types are used to configure some part of the system (e.g. `CacheManager`, `Cache`, +`Service`, ...). If a given configured type has a requirement to modify it's configuration, a additional _runtime +configuration_ is introduced, e.g. `RuntimeCacheConfiguration`. That type will expose additional mutative methods for +attributes that are mutable. Internally it will also let consumers of the type to register listener for these attributes. image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/config.png[Configuration types] -=== Builder guidelines +==== `ServiceProvider` and `ServiceConfiguration` + +A special type of configuration is the `ServiceConfiguration` type. That configuration type enables +the `ServiceProvider` to lookup the `ServiceFactory` to use to create the `Service` that's being +configured, see `ServiceProvider.findServiceFor(ServiceConfiguration config): T extends Service`. This is what +happens underneath of that call when the `CacheManager` or a `ServiceFactory` looks up `Service` instances: + + . The caller invokes `ServiceProvider.findServiceFor` + . The `ServiceProvider` looks up whether it already has that `Service` + .. If it does, that instance is being retuned + .. If it doesn't, it looks up all `ServiceFactory` it has for one that creates instances of that `Service` type. + ... If one is found in that `ServiceFactory` repository, it uses that to create the instance + ... If none is found, it uses the JDK's `java.util.ServiceLoader` service to load `ServiceFactory` and recheck + .. If nothing could be found, it an Exception is thrown + +=== Builder design guidelines + + - Copy the instance returned, instead of returning `this` + - Accept other builders as input, instead of just the actual "other thing's" configuration + - ... + +== `javax.cache` API implications + +While we know we don't want to strictly go by the JSR-107 (aka JCache) API contract in the Ehcache3 APIs (e.g. `CacheLoader` & +`CacheWriter` contracts when concurrent methods on the `Cache` are invoked), we still need a way to have our JCache +implementation pass the TCK. It is important to at least read the specification with regards to any feature that's being +implemented and list dissimilarities as well as how they'll be addressed in the 107 module. == The `PersistentCacheManager` +The `PersistentCacheManager` interface adds lifecycle methods to the `CacheManager` type. Those lifecycle methods enable +the user to completely destroy `Cache` instances a given `CacheManager` (e.g. destroy the clustered state of a `Cache` entirely, +or remove all the data of a `Cache` from disk); as well as go into _maintenance mode_ (see <> section). + === `CacheManagerBuilder.with()` 's extension point +A `CacheManagerBuilder` builds _at least_ a `CacheManager`, but its +`.with(CacheManagerConfiguration): CacheManagerBuilder` let's you build any subtype of `CacheManager` (currently +the supported types are a closed set of defined subtypes, but this could be extended to an open set later). + +[source,java] +---- + +PersistentCacheManager cm = newCacheManagerBuilder() // <1> + .with(new CacheManagerConfiguration()) // <2> + .build(true); // <3> +---- + +<1> the `T` of `CacheManagerBuilder` is still of `CacheManager` +<2> the `CacheManagerConfiguration` passed in to `.with` now narrows `T` down to `PersistentCacheManager` +<3> returns the instance of `T` built + === Locally persistent +When building a `PersistentCacheManager` the `CacheManagerConfiguration` passed to the builder +would let one configure all persistent related aspects of `Cache` instances managed by the `CacheManager`, e.g. root +location for writing cached data to. + === Clustered topology + +In a Terracotta clustered scenario, all clustered `Cache` instances are concidered persistent (i.e. will survive the +_client_ JVM restart). So the idea is to provide all clustered configuration passing such a +`CacheManagerConfiguration` instance, with all the Terracotta client configuration stuff, to the +`CacheManagerBuilder` at construction time. + +==== Persistence configuration + +Any given persistent `Cache` uses the lifecycle as described above in <>. Yet the data on disk, or +datastructures on disk to store. We think of states of those structures in these terms: + + . Inexistent, nothing there: nothing can be stored until these exist; + . Online: the datastructures are present (with or without any data), referenced by the `Store` and the `Cache` is usable; + . Offline: the datastructures are present (with or without data), not referenced by any `Store` and nothing accesses it. + +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/persistentStateTransitions.jpg[Persistence and statuses & their transitions] + +The user can fallback to the maintenance mode and the `Maintainable` instance returned when transitioning to the +maintenance state. That `Maintainable` can be used to: + + - `Maintainable.create()`, moving from nothing to online; _or_ + - `Maintainable.destroy()`, moving from offline to nothing + +the associated data for a given `Cache` on disk or within the Terracotta Server stripe(s). + +We also want to provide with configuration based _modes_ to automatically: + + - Create the persistent data structures if it doesn't already exit; + - Drop the persistent data structures if it exists, and create it anew; + - Verify the persistent data structures is there, otherwise fail fast; + - Create the persistent data structures expecting them to not be there, otherwise fail fast. From f2ce5bea4885ffbb3777d16bd5cf2b0d82a21f37 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 29 Apr 2015 10:18:15 +0200 Subject: [PATCH 046/779] Fix minor typos --- design.basics.asciidoc | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/design.basics.asciidoc b/design.basics.asciidoc index 190140aa1b..a8ec64acb7 100644 --- a/design.basics.asciidoc +++ b/design.basics.asciidoc @@ -13,7 +13,7 @@ means fulfilling a couple of roles: gets registered with it. These `Service` can then be looked up, e.g. by `Cache` or other `Service` instances, using the `ServiceProvider` interface; - Finally, the `CacheManager` acts as a repository of alias'ed `Cache` instances. Unlike in the previous versions, `Cache` - instances aren't named, but are registered with the `CacheManager` under an _alias_. The `Cache` is never aware of it. + instances aren't named, but are registered with the `CacheManager` under an _alias_. The `Cache` is never aware of this. This diagram tries to summarize the different roles: @@ -40,14 +40,14 @@ When a `Cache` is being constructed, e.g. by the `CacheManager` on a `.createCac will lookup a `Store.Provider` which is one of the bundled `Service` types of Ehcache, asking it to create a `Store` based on the `CacheConfiguration` used to configure the given `Cache`. That indirection, makes both the `Cache` as well as the `CacheManager` ignorant of what topology this `Cache` is to use. Ehcache comes with a `DefaultStoreProvider` that will -be loaded by the `ServiceProvider`, should one be explicitly provided. That in turn will resolve the required `Store` +be loaded by the `ServiceProvider`, should none be explicitly provided. That in turn will resolve the required `Store` instance to be provided to the `Cache` being created. image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/cacheStore.png[Cache's Store] The `Cache` also tries to never _fails_ on operations invoked, e.g. a get shouldn't result in throwing an exception if the `Store` that backs it up uses serialization and fails to retrieve the mapping. Instead, Ehcache tries to be resilient and -should try to clear that mapping from its `Store` and return `null` instead to the user. It is the responsibility of the +will, by default, try to clear that mapping from its `Store` and return `null` instead to the user. It is the responsibility of the `Cache` to handle the exceptions a `Store` may throw (the `Store` interface explicitly declares it throws `CacheAccessException`, which is a checked exception). The `Cache` will delegate failures to the `ResilienceStrategy`, which in turn is responsible for handling the failure. @@ -59,7 +59,7 @@ and will make it pluggable, when we move on to distributed topologies. === The new `UserManagedCache` The `UserManagedCache` are, as the name implies, managed by the user instead of being managed by a `CacheManager`. While -these instances a meant to be lightweight, short-lived ones, nothing prohibits a user from building a distributed +these instances are meant to be lightweight, short-lived ones, nothing prohibits a user from building a distributed `UserManagedCache` if so desired. As the user manages that instance himself, he needs to provide all `Service` instances required by the `UserManagedCache`. @@ -70,7 +70,7 @@ image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/des == State transitions -A lifecycled instance, e.g. a `CacheManager` or a `UserManagedCache`, have three states represented by the +A lifecycled instance, e.g. a `CacheManager` or a `UserManagedCache`, has three states represented by the `org.ehcache.Status` enum: . `UNINITIALIZED`: The instance can't be used, it probably just got instantiated or got `.close()` invoked on it; @@ -101,7 +101,7 @@ all from you and will create the actual configuration at `.build()` invocation t immutable. Instances of these types are used to configure some part of the system (e.g. `CacheManager`, `Cache`, `Service`, ...). If a given configured type has a requirement to modify it's configuration, a additional _runtime configuration_ is introduced, e.g. `RuntimeCacheConfiguration`. That type will expose additional mutative methods for -attributes that are mutable. Internally it will also let consumers of the type to register listener for these attributes. +attributes that are mutable. Internally it will also let consumers of the type register listener for these attributes. image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/config.png[Configuration types] @@ -118,7 +118,7 @@ happens underneath of that call when the `CacheManager` or a `ServiceFactory` lo .. If it doesn't, it looks up all `ServiceFactory` it has for one that creates instances of that `Service` type. ... If one is found in that `ServiceFactory` repository, it uses that to create the instance ... If none is found, it uses the JDK's `java.util.ServiceLoader` service to load `ServiceFactory` and recheck - .. If nothing could be found, it an Exception is thrown + .. If nothing could be found, an Exception is thrown === Builder design guidelines @@ -136,7 +136,7 @@ implemented and list dissimilarities as well as how they'll be addressed in the == The `PersistentCacheManager` The `PersistentCacheManager` interface adds lifecycle methods to the `CacheManager` type. Those lifecycle methods enable -the user to completely destroy `Cache` instances a given `CacheManager` (e.g. destroy the clustered state of a `Cache` entirely, +the user to completely destroy `Cache` instances from a given `CacheManager` (e.g. destroy the clustered state of a `Cache` entirely, or remove all the data of a `Cache` from disk); as well as go into _maintenance mode_ (see <> section). === `CacheManagerBuilder.with()` 's extension point @@ -165,7 +165,7 @@ location for writing cached data to. === Clustered topology -In a Terracotta clustered scenario, all clustered `Cache` instances are concidered persistent (i.e. will survive the +In a Terracotta clustered scenario, all clustered `Cache` instances are considered persistent (i.e. will survive the _client_ JVM restart). So the idea is to provide all clustered configuration passing such a `CacheManagerConfiguration` instance, with all the Terracotta client configuration stuff, to the `CacheManagerBuilder` at construction time. From f7a67d5808d7c1e33ae07ecb0dc6eb931cf5593a Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Mon, 11 May 2015 14:09:30 +0200 Subject: [PATCH 047/779] Expand builder design guildelines following work on issue #391 --- design.basics.asciidoc | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/design.basics.asciidoc b/design.basics.asciidoc index a8ec64acb7..cdbd6c3342 100644 --- a/design.basics.asciidoc +++ b/design.basics.asciidoc @@ -122,9 +122,10 @@ happens underneath of that call when the `CacheManager` or a `ServiceFactory` lo === Builder design guidelines - - Copy the instance returned, instead of returning `this` + - Copy the instance, apply modification and return the copy. Never modify and return `this` - Accept other builders as input, instead of just the actual "other thing's" configuration - - ... + - Provide names methods for boolean or `Enum` based settings. Apply this while keeping in mind that we do not want + method explosion on the builder as a whole. == `javax.cache` API implications From 2f039426ec7650e739c8c6d043896f98163f6b87 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Mon, 11 May 2015 17:17:55 +0200 Subject: [PATCH 048/779] Add defaults related builder design guideline --- design.basics.asciidoc | 1 + 1 file changed, 1 insertion(+) diff --git a/design.basics.asciidoc b/design.basics.asciidoc index cdbd6c3342..91e2ca9352 100644 --- a/design.basics.asciidoc +++ b/design.basics.asciidoc @@ -126,6 +126,7 @@ happens underneath of that call when the `CacheManager` or a `ServiceFactory` lo - Accept other builders as input, instead of just the actual "other thing's" configuration - Provide names methods for boolean or `Enum` based settings. Apply this while keeping in mind that we do not want method explosion on the builder as a whole. + - Default values are to be handled inside the configuration classes and not duplicated inside the builder. == `javax.cache` API implications From f7aa202e467d6528eab7655a04e8a426d6831088 Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Mon, 6 Jul 2015 12:51:21 -0400 Subject: [PATCH 049/779] Rough sketch for clustering design doc --- module.clustering.asciidoc | 66 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 module.clustering.asciidoc diff --git a/module.clustering.asciidoc b/module.clustering.asciidoc new file mode 100644 index 0000000000..a738b6af57 --- /dev/null +++ b/module.clustering.asciidoc @@ -0,0 +1,66 @@ += Terracotta's Clustering Module + +:toc: + +== Voltron + +What's Voltron? +What services does it provide? +Remoting? +Provider of resources to `Entity` instances? +Versioning? +How is _persistence_ addressed? +_Replication_? +_HA_? + +=== Server-side entity + + . Actual providers of functionality; + . Responsible for: + .. Maintaining their state? + .. Acquiring releasing of resources? + .. ... ? + +=== Client-side entity + + . (Stateful)? Proxies to the server-side entities + . Rejoin? + . Reconnect? + . ... ? + +== Ehcache's clustering model + +Clusters an actual `CacheManager`? i.e. no `UserManagedCache` version for `ClusteredCache`? +Only provides `ClusteredAuthoritativeTier` instances? +What about "associated data-structures", i.e. write-behind queues? +How's configuration handled? What's static? What's dynamic? + +=== The `ServerSideCacheManagerEntity` + +What is it? What are its responsibilities? + +==== Lifecycle + +How is it created? Destroyed? + +==== State + +What state does it require? + +==== State persistence + +How's that state _persisted_? _replicated_? + +=== The `ClientSideCacheManagerEntity` _[tbd]_ + +==== `TerracottaClientService` + +==== Lifecycle + +===== `ClusteredCache` registery & lifecycling + +==== `ClusteredStore` instances + +==== `ClusteredWriteBehindManager` instance(s)? + +==== Configuration validation From a9264524912c95e2624399c34869840b89c34c70 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Thu, 9 Jul 2015 12:19:48 +0530 Subject: [PATCH 050/779] Adding voltron storage spec and client communicator service --- module.clustering.asciidoc | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/module.clustering.asciidoc b/module.clustering.asciidoc index a738b6af57..c888524ce9 100644 --- a/module.clustering.asciidoc +++ b/module.clustering.asciidoc @@ -13,6 +13,38 @@ How is _persistence_ addressed? _Replication_? _HA_? +=== Voltron Storage Spec + + . Voltron provides `StorageService` service for as storage service for entities. + . The Storage service provided is sandboxed which will be used by the Entities to get `StorageChunk` s. + The allocation done for a particular Entity is scoped in a way, so that no other Entity + uses it or interferes with it. + . These chunks are fixed size resource(offheap, disk etc) allocations. + . To create a `StorageChunk` from storage service, one needs to provide the size of the chunk, + an identifier and the server pool id. + . The `StorageChunk`'s lifecycle is managed by the Entity'. It can create/destroy the chunks as per the need. + . An Entity can request for any number of `StorageChunk` s, limited only by the size of + the server side pool. + . Voltron internally sandboxes each individual chunk. (entityId:poolId:chunkId -> + provided `StorageChunk`) + . The `StorageChunk` provides apis to create, destroy and get `KeyValueStorage` s. It can request + for any number of `KeyValueStorage` s from the provided `StorageChunk`. + . The storage limit of `KeyValueStorage` is defined by the capacity of the `StorageChunk` it + it belongs to. + +=== Client Communication Service + . Client Communication service enables the entities to interact with the client. + . If an Entity needs to send messages to the client, the client communication service can be + invoked to send messages. + . The Client Communication Service is a different channel than the regular Endpoint which + clients use to send payload to the server. + . The point is that Client Communication service should not be misunderstood with the Endpoint + as it is not related to send acknowledgements back to the client. + . All the client -> server communications which happen through Endpoint channel are totally + different from the server -> client communications that happens through Client Communicator Service. + . Some of the use cases where this service can be used is sending invalidations about stale data, + requesting information from client, etc. + === Server-side entity . Actual providers of functionality; From 7948133e9c82ea36933d1c65b014b3430ec59737 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Mon, 10 Aug 2015 19:13:09 +0530 Subject: [PATCH 051/779] Montreal Design documented #297 --- design.tiering.asciidoc | 51 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 design.tiering.asciidoc diff --git a/design.tiering.asciidoc b/design.tiering.asciidoc new file mode 100644 index 0000000000..03ead4ccb2 --- /dev/null +++ b/design.tiering.asciidoc @@ -0,0 +1,51 @@ += Ehcache Tiering Model + +:toc: + +The `Store` in Ehcache is designed to hold data in multi-tiered model. Broadly, a cache +can have two major tiers - `CachingTier` and `AuthoritativeTier`. +`CacheStore` wires both the tier's for the Cache and provides a unified view of +the `Store`. We can break the tiers further and introduce additional layers like +2-Tier `CachingTier`. + +. What is CachingTier ? + +- In a multi-tiered cache, this tier holds the most recently used data. Conceptually +the cost of getting a value from the Caching Tier is low compared to other lower +tiers. All the data that is present in CachingTier, has to be present in AuthoritativeTier. +The authority will not evict the entry which is present in CachingTier. CachingTier is +always the subset of authority. + +. What is AuthoritativeTier ? + +- This tier is the ultimate source of truth for the cache data, thus the authority. +All the mutations for an entry are done at authority tier first. Afterwards the +returning thread uninstalls the stale entry from the caching tier. + +. How are they wired ? + +- All Multi-tiered Caches have only one store i.e. `CacheStore` which wires the + logic between a CachingTier and an AuthoritativeTier. All the mutative operations + are written in a way that the mutating thread uninstalls the entry from CachingTier + after the mutation is complete in authority. The Store has an invalidation listener + through which authority listens on all the invalidations done in caching tier. + +. Faulting + +- Whenever an entry is not found in CachingTier it is faulted from AuthoritativeTier. +Even if there are multiple threads trying to get a value, all the threads will fight +the race for the lock and the winning thread will install a fault for that key and wait +for value to be fetched from the authority by the fault. All other +threads will read the most recently fetched value installed in CachingTier. +The important point is that whenever an entry is faulted from authority, the contract +ensures that till the entry resides in caching tier , it will not be removed/evicted +from authority. + +. Invalidations and Flushing + +- In situations when caching tier decides that an entry needs to be evicted/expired, +it has to inform authority that it can now evict that entry. Therefore, whenever an +entry is expired/evicted from caching tier, it flushes that information to authority +using invalidation listener. All the flushed entries are now marked as evictable in +authority. + From c1a3733f577832fd80b111ebc9f989973581448a Mon Sep 17 00:00:00 2001 From: Alex Snaps Date: Wed, 26 Aug 2015 12:50:06 -0400 Subject: [PATCH 052/779] Updated Home (asciidoc) --- Home.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Home.asciidoc b/Home.asciidoc index 7577ce10e7..248b298c02 100644 --- a/Home.asciidoc +++ b/Home.asciidoc @@ -12,7 +12,7 @@ This wiki contains all design documents and other related material to doing deve On paper (or on this screen), it's pretty straight forward: - . Join the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] and say hello! + . Join the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] and say hello! Or join us on irc #ehcache on freenode . Check the https://github.com/ehcache/ehcache3/issues[issues] and verify what you want isn't yet planned or could even already being worked on by someone; We're also using a board on https://waffle.io/ehcache/ehcache3[waffle.io], where work for the current milestone is prioritized; . If the task exists already and isn't assigned: drop us an email on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] about it and we'll make sure we help you getting started and we'll assign the task/issue to you; . If nothing matches in the existing issue list, create a bug as such; or, if we're talking about a larger task or feature, https://groups.google.com/forum/#!forum/ehcache-dev[drop us a message] first, and we'll see how to tackle it; From c15201e0a0e0896756182775a6f362075a1054cf Mon Sep 17 00:00:00 2001 From: Abhilash Date: Thu, 27 Aug 2015 12:25:56 +0530 Subject: [PATCH 053/779] Adding tiering diagram #297 --- design.tiering.asciidoc | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/design.tiering.asciidoc b/design.tiering.asciidoc index 03ead4ccb2..d2d3b4d56d 100644 --- a/design.tiering.asciidoc +++ b/design.tiering.asciidoc @@ -49,3 +49,20 @@ entry is expired/evicted from caching tier, it flushes that information to autho using invalidation listener. All the flushed entries are now marked as evictable in authority. +image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/Faulting.png[Faulting & Flushing] + + . All writes directly go to the Authoritative tier.This tier has all the data such that caching tier always has a subset of authority + + . On return, the mapping in the caching tier is invalidated. + + . On eviction or expiry in the caching tier, the mapping is flushed to the authority. + + . Any reading thread tries to get data from the caching tier and returns + + . If the key is not found in caching tier, it is faulted from authority + + . On return, the mapping faulted from the authority is installed in the caching tier. The install may fail under heavy contention to preserve correctness. + + + + From 748c3663dd471298dfe5754c014ac8e6ddda01ec Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Mon, 7 Sep 2015 09:59:03 +0200 Subject: [PATCH 054/779] Update Service(Configuration) section following changes in #527 --- design.basics.asciidoc | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/design.basics.asciidoc b/design.basics.asciidoc index 91e2ca9352..3887225452 100644 --- a/design.basics.asciidoc +++ b/design.basics.asciidoc @@ -89,8 +89,8 @@ require enforcing lifecycle constraints. == Configuration types and builders -In the most generic sense, configuration types are used to _configure_ a given service _while_ it's being constructed. A -builder exposes a user-friendly DSL to configure and build _runtime instances_ (e.g. `CacheManager`). Finally runtime +In the most generic sense, configuration types are used to _configure_ a given service, either _while_ it is being constructed or when it is used. +A builder exposes a user-friendly DSL to configure and build _runtime instances_ (e.g. `CacheManager`). Finally runtime configuration types are configured from configuration types and used at runtime by the actual configured instance, providing a way for the user to mutate the behavior of that instance at runtime in limited ways. @@ -99,27 +99,38 @@ providing a way for the user to mutate the behavior of that instance at runtime You don't necessarily ever get exposed to a _configuration_ for a given type being constructed. The builder can hide it all from you and will create the actual configuration at `.build()` invocation time. Configuration types are always immutable. Instances of these types are used to configure some part of the system (e.g. `CacheManager`, `Cache`, -`Service`, ...). If a given configured type has a requirement to modify it's configuration, a additional _runtime +`Service`, ...). If a given configured type has a requirement to modify it's configuration, an additional _runtime configuration_ is introduced, e.g. `RuntimeCacheConfiguration`. That type will expose additional mutative methods for attributes that are mutable. Internally it will also let consumers of the type register listener for these attributes. image::https://raw.githubusercontent.com/ehcache/ehcache3/master/docs/images/design/basics/config.png[Configuration types] -==== `ServiceProvider` and `ServiceConfiguration` +==== Services creation, `ServiceCreationConfiguration`, `ServiceProvider` and `ServiceConfiguration` -A special type of configuration is the `ServiceConfiguration` type. That configuration type enables -the `ServiceProvider` to lookup the `ServiceFactory` to use to create the `Service` that's being -configured, see `ServiceProvider.findServiceFor(ServiceConfiguration config): T extends Service`. This is what -happens underneath of that call when the `CacheManager` or a `ServiceFactory` looks up `Service` instances: +A special type of configuration is the `ServiceCreationConfiguration` type. +That configuration type indicates to the system to lookup the `ServiceFactory` to use to create the `Service` that's being configured. +Subclasses of that configuration type are accepted at the outermost level of configuration, `CacheManager` or `UserManagedCacheBuilder`, which is the only place where services will be looked up from a configuration. - . The caller invokes `ServiceProvider.findServiceFor` - . The `ServiceProvider` looks up whether it already has that `Service` +This is what happens underneath that call when the `CacheManager` looks up `Service` instances: + +For each `ServiceCreationConfiguration` + + . The service subsystem looks up whether it already has that `Service` .. If it does, that instance is being retuned .. If it doesn't, it looks up all `ServiceFactory` it has for one that creates instances of that `Service` type. - ... If one is found in that `ServiceFactory` repository, it uses that to create the instance + ... If one is found in that `ServiceFactory` repository, it uses that to create the instance with the configuration ... If none is found, it uses the JDK's `java.util.ServiceLoader` service to load `ServiceFactory` and recheck .. If nothing could be found, an Exception is thrown +After this, services are started and can be consummed by the different components. +For this, the `ServiceProvider` is passed to `Service` instances at start point. +Form there, calling into `ServiceProvider.getService(Class serviceType)` will enable to retrieve a defined service. + +NOTE: When `Service.start(ServiceProvider serviceProvider)` is called, the service subsystem is currently starting. +So while all `Service` instances are defined, they are not necessarily started which means your code in `start(...)` needs to limit itself to service lookups and not consumption. + +The `ServiceConfiguration` interface enables to define extra configuration to a `Service` when using it. + === Builder design guidelines - Copy the instance, apply modification and return the copy. Never modify and return `this` From 48619a5dc78e62d917ab0d0bf396e8056a87368a Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 27 Oct 2015 09:59:12 -0700 Subject: [PATCH 055/779] Add description of contract between two caching tiers --- design.tiering.asciidoc | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/design.tiering.asciidoc b/design.tiering.asciidoc index d2d3b4d56d..1f21e5ac1a 100644 --- a/design.tiering.asciidoc +++ b/design.tiering.asciidoc @@ -2,33 +2,31 @@ :toc: -The `Store` in Ehcache is designed to hold data in multi-tiered model. Broadly, a cache -can have two major tiers - `CachingTier` and `AuthoritativeTier`. -`CacheStore` wires both the tier's for the Cache and provides a unified view of -the `Store`. We can break the tiers further and introduce additional layers like -2-Tier `CachingTier`. +The `Store` in Ehcache is designed to hold data in a tiered model. +A cache will always have at least one tier, possible multiple. +As soon as there are multiple tiers, they are immediately divided between a single `AuthoritativeTier` and one or more `CachingTier`. +It is the `CacheStore` that wires the authority and caching tiers and provides a unified view of the `Store` for the Cache. -. What is CachingTier ? +. What is `CachingTier` ? - In a multi-tiered cache, this tier holds the most recently used data. Conceptually the cost of getting a value from the Caching Tier is low compared to other lower -tiers. All the data that is present in CachingTier, has to be present in AuthoritativeTier. -The authority will not evict the entry which is present in CachingTier. CachingTier is -always the subset of authority. +tiers. All the data that is present in `CachingTier`, has to be present in `AuthoritativeTier`. +The authority will not evict an entry which is present in a `CachingTier`, which is +always a subset of the authority. +- In a two tier `CachingTier`, mappings are present in one tier or the other but never both at the same time. This contract is enforced by having all operations happen atomically from the higher tier's point of view. -. What is AuthoritativeTier ? +. What is `AuthoritativeTier` ? -- This tier is the ultimate source of truth for the cache data, thus the authority. -All the mutations for an entry are done at authority tier first. Afterwards the -returning thread uninstalls the stale entry from the caching tier. +- This tier holds all the cached mappings at any given point in time, it thus acts as the authority. . How are they wired ? -- All Multi-tiered Caches have only one store i.e. `CacheStore` which wires the - logic between a CachingTier and an AuthoritativeTier. All the mutative operations - are written in a way that the mutating thread uninstalls the entry from CachingTier - after the mutation is complete in authority. The Store has an invalidation listener - through which authority listens on all the invalidations done in caching tier. +- All multi-tiered `Cache` have only one store i.e. `CacheStore` which wires the + logic between the `CachingTier` and the `AuthoritativeTier`. All the mutative operations + are written in a way that the mutating thread uninstalls the entry from `CachingTier` + after the mutation is complete in the authority. The `Store` has an invalidation listener + through which the authority listens on all the invalidations done in caching tier. . Faulting From ca8ddd64a41ce925e3c360789b08e5f0ae026b90 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 27 Oct 2015 10:18:51 -0700 Subject: [PATCH 056/779] Fix typo --- design.tiering.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design.tiering.asciidoc b/design.tiering.asciidoc index 1f21e5ac1a..4d9dec10d4 100644 --- a/design.tiering.asciidoc +++ b/design.tiering.asciidoc @@ -14,7 +14,7 @@ the cost of getting a value from the Caching Tier is low compared to other lower tiers. All the data that is present in `CachingTier`, has to be present in `AuthoritativeTier`. The authority will not evict an entry which is present in a `CachingTier`, which is always a subset of the authority. -- In a two tier `CachingTier`, mappings are present in one tier or the other but never both at the same time. This contract is enforced by having all operations happen atomically from the higher tier's point of view. +- In a two tiers `CachingTier`, mappings are present in one tier or the other but never both at the same time. This contract is enforced by having all operations happen atomically from the higher tier's point of view. . What is `AuthoritativeTier` ? From 210c191528565250a91793d97ac844899ad73688 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 6 Apr 2016 19:08:26 +0200 Subject: [PATCH 057/779] Add design docs around XA caches --- module.xa.asciidoc | 60 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 module.xa.asciidoc diff --git a/module.xa.asciidoc b/module.xa.asciidoc new file mode 100644 index 0000000000..c588cd9786 --- /dev/null +++ b/module.xa.asciidoc @@ -0,0 +1,60 @@ += Transactions module + +:toc: + +== High level design + +Transaction support works through wrapping the `Store` that backs the `Cache` and storing a specific datastructure, a `SoftLock`, wrapping the cache values themselves. + +NOTE: No cache interactions are allowed outside of a transaction context. + +=== Operations under a transaction + +In the context of a transaction, cache operations are translated to `Commands` and stored in a transaction specific context. + +These commands cause `Store` mutations at specific stages in the lifecycle of the transaction. + +==== Prepare + +During the _prepare_ phase, all commands have their values, new and old if available, transformed into `SoftLock` instances. +These are saved in the `Store`. +A `SoftLock` from the prepare phase will carry the following information: + +* Transaction information allowing to identify which transaction created it, +* The new mapping value to install - can be `null` to indicate removal, +* The old mapping value when relevant. +Such `SoftLock` are considered _in doubt_. + +==== Commit + +During the _commit_ phase, _in doubt_ `SoftLock` will be retrieved from the `Store`. +That will be the case for all keys that were touched by the transaction. +As long as the retrieved `SoftLock` is linked to this transaction context, they will be replaced in the underlying `Store` with a `SoftLock` instance: + +* Holding the value for the mapping, identified as the _old_ value, +* disconnected from any transaction context. + +===== Commit in 1 phase + +In that case, we go directly from the command to the disconnected `SoftLock` but the principle remains the same. + +==== Rollback + +In case of _rollback_, _in doubt_ `SoftLock` will be retrieved from the `Store`. +That will be the case for all keys that were touched by the transaction. +As long as the retrieved `SoftLock` is linked to this transaction context, they will be replaced in the underlying `Store` with a `SoftLock` instance: + +* Holding the _old_ value, +* disconnected from any transaction context. + +===== Rollback before prepare + +Commands are simply dropped from the transaction context. + +== Interactions with other Ehcache features + +=== Eviction veto + +By default the `XAStore` uses the veto mechanism to protect all _in doubt_ `SoftLock`. + +Integration with user provided veto is limited to `SoftLock` that are not in doubt and which by definition only contain an _old_ value. From b0a503826064988ff19ea5086107e5d80b405838 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 6 Apr 2016 19:09:33 +0200 Subject: [PATCH 058/779] Updated module.xa (asciidoc) --- module.xa.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/module.xa.asciidoc b/module.xa.asciidoc index c588cd9786..0797105603 100644 --- a/module.xa.asciidoc +++ b/module.xa.asciidoc @@ -57,4 +57,4 @@ Commands are simply dropped from the transaction context. By default the `XAStore` uses the veto mechanism to protect all _in doubt_ `SoftLock`. -Integration with user provided veto is limited to `SoftLock` that are not in doubt and which by definition only contain an _old_ value. +Integration with user provided veto is limited to `SoftLock` that are not in doubt and which by definition only contain an _old_ value, which will be the value passed to the `vetoes(K key, V value)` method. From 1221195ae046073ba8a2c681370045d48e2b9b15 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 13 Apr 2016 12:01:37 -0400 Subject: [PATCH 059/779] Adding putIfAbsent sequence diagram --- module.clustering.asciidoc | 35 +++-------------------------------- 1 file changed, 3 insertions(+), 32 deletions(-) diff --git a/module.clustering.asciidoc b/module.clustering.asciidoc index c888524ce9..fa41460323 100644 --- a/module.clustering.asciidoc +++ b/module.clustering.asciidoc @@ -62,37 +62,8 @@ _HA_? == Ehcache's clustering model -Clusters an actual `CacheManager`? i.e. no `UserManagedCache` version for `ClusteredCache`? -Only provides `ClusteredAuthoritativeTier` instances? -What about "associated data-structures", i.e. write-behind queues? -How's configuration handled? What's static? What's dynamic? +=== Operations sequence diagrams -=== The `ServerSideCacheManagerEntity` +==== putIfAbsent -What is it? What are its responsibilities? - -==== Lifecycle - -How is it created? Destroyed? - -==== State - -What state does it require? - -==== State persistence - -How's that state _persisted_? _replicated_? - -=== The `ClientSideCacheManagerEntity` _[tbd]_ - -==== `TerracottaClientService` - -==== Lifecycle - -===== `ClusteredCache` registery & lifecycling - -==== `ClusteredStore` instances - -==== `ClusteredWriteBehindManager` instance(s)? - -==== Configuration validation +image::https://github.com/ehcache/ehcache3/blob/master/docs/images/design/clustered/putIfAbsentUml.png[putIfAbsent sequence] From 22e713fecd1a1be8704df1d63da3516f7c507557 Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Thu, 14 Apr 2016 11:52:30 -0400 Subject: [PATCH 060/779] Updated module.xa (asciidoc) --- module.xa.asciidoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/module.xa.asciidoc b/module.xa.asciidoc index 0797105603..9e87a91094 100644 --- a/module.xa.asciidoc +++ b/module.xa.asciidoc @@ -53,8 +53,8 @@ Commands are simply dropped from the transaction context. == Interactions with other Ehcache features -=== Eviction veto +=== Eviction advisor -By default the `XAStore` uses the veto mechanism to protect all _in doubt_ `SoftLock`. +By default the `XAStore` uses the `EvictionAdvisor` mechanism to protect all _in doubt_ `SoftLock`. -Integration with user provided veto is limited to `SoftLock` that are not in doubt and which by definition only contain an _old_ value, which will be the value passed to the `vetoes(K key, V value)` method. +Integration with user provided `EvictionAdvisor` is limited to `SoftLock` that are not in doubt and which by definition only contain an _old_ value, which will be the value passed to the `adviseAgainstEviction(K key, V value)` method. From 7929088528780eaace7a2d408c3f1c671f52c920 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Thu, 14 Apr 2016 12:03:32 -0400 Subject: [PATCH 061/779] Issue #965 Replace CacheStore with TieredStore following rename --- design.tiering.asciidoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/design.tiering.asciidoc b/design.tiering.asciidoc index 4d9dec10d4..5954e9dc71 100644 --- a/design.tiering.asciidoc +++ b/design.tiering.asciidoc @@ -5,7 +5,7 @@ The `Store` in Ehcache is designed to hold data in a tiered model. A cache will always have at least one tier, possible multiple. As soon as there are multiple tiers, they are immediately divided between a single `AuthoritativeTier` and one or more `CachingTier`. -It is the `CacheStore` that wires the authority and caching tiers and provides a unified view of the `Store` for the Cache. +It is the `TieredStore` that wires the authority and caching tiers and provides a unified view of the `Store` for the Cache. . What is `CachingTier` ? @@ -22,7 +22,7 @@ always a subset of the authority. . How are they wired ? -- All multi-tiered `Cache` have only one store i.e. `CacheStore` which wires the +- All multi-tiered `Cache` have only one store i.e. `TieredStore` which wires the logic between the `CachingTier` and the `AuthoritativeTier`. All the mutative operations are written in a way that the mutating thread uninstalls the entry from `CachingTier` after the mutation is complete in the authority. The `Store` has an invalidation listener From cc1cebd258a64e680d81de5d1c2f5ae699f3d87b Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 24 May 2016 21:54:13 +0200 Subject: [PATCH 062/779] Added description of the bugfixing strategy --- dev.git.asciidoc | 49 ++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 47 insertions(+), 2 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 3a2a463d9f..9430bdcfcb 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -7,13 +7,22 @@ . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; . +git clone+ that fork to your computer, by default that remote's name will be +origin+; . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; - . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1 below) + . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1.1 below) . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; . You can have as many parallel branches as issues you might be working on; . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; == Initiate a pull request +Now that Ehcache 3.0 has releases out there, bug fixes may apply to both the release branches and/or master. + +Given this, the development team has decided on the following development strategy. + +=== Feature development + +This happens on master only, using a rebase model described below. +We strive on keeping a clean and very linear history for feature development. + . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: git pull ehcache @@ -26,6 +35,42 @@ . You then need to create a pull request, using the UI on GitHub; . Someone from our team is then going to review it. +=== Bug fixing + +If what you are working on is a bug fix, we want to be able to merge the fix commits on all impacted release branches and master. +In order to do that, we use a strategy inspired from http://wiki.monotone.ca/DaggyFixes/[DaggyFixes]. + +==== Picking the base commit + +The base commit for your fix must be at the earliest a parent of all branches it will need to be merged to, it can also be at the latest the commit that introduced the bug as describe in DaggyFixes. + +Such a commit can be found using the following (presented here as an alias definiton): + +`alias.oldest-ancestor=!bash -c 'diff --old-line-format='' --new-line-format='' <(git rev-list --first-parent ${1:-master}) <(git rev-list --first-parent ${2:-HEAD}) | head -1' -` + +==== Developing the fix + +That's you doing the work - nothing specific there but the usual commit recommendations. + +==== Pull requests + +As the fix developer, integrating the fix in the different target branches is your responsibility. +So unless your fix can directly be merged in the different branches, you will have to merge the branches into the fix to resolve conflicts. + +I will use the `release/3.0` branch as the target in the example below and assume your fix branch is `issue-1048`. These names should be replaced by the one applicable to your context. + + . On your fix branch + + git checkout -b issue-1048-release-3.0 + git merge release/3.0 + // Resolve conflicts + git merge --continue + + . Open a pull request from that, making sure it is against `release/3.0` + . Repeat for each target branch, including `master` + +The idea behind this strategy is that the commits that were created on branch `issue-1048` in this example are now part of the history of the different releases and tracking which fix exists where is vastly simplified over the different strategies that are `cherry-pick` based. + == Have it reviewed . The pull request will be reviewed for: @@ -33,7 +78,7 @@ .. 'Style': which needs to match the style of the project; .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. .. You can look up link:dev.guidelines[general developer guidelines] as well - . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1 above, but finally +git push --force origin issue-''+ to keep the pull request updated. + . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1.1 above, but finally `git push --force origin issue-` to keep the pull request updated. == Merging a pull request From 43bff9d6eb17b0fabaaaac1013529fe892b37dad Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 30 Aug 2016 15:49:07 -0400 Subject: [PATCH 063/779] Updated design.basics (asciidoc) --- design.basics.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/design.basics.asciidoc b/design.basics.asciidoc index 3887225452..3c4fe6d94e 100644 --- a/design.basics.asciidoc +++ b/design.basics.asciidoc @@ -116,7 +116,7 @@ This is what happens underneath that call when the `CacheManager` looks up `Serv For each `ServiceCreationConfiguration` . The service subsystem looks up whether it already has that `Service` - .. If it does, that instance is being retuned + .. If it does, that instance returned .. If it doesn't, it looks up all `ServiceFactory` it has for one that creates instances of that `Service` type. ... If one is found in that `ServiceFactory` repository, it uses that to create the instance with the configuration ... If none is found, it uses the JDK's `java.util.ServiceLoader` service to load `ServiceFactory` and recheck From 561c38a4c55a21ef38dc268c516c71bbf45e4498 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 13 Sep 2016 13:43:47 +0200 Subject: [PATCH 064/779] Added commit comment section --- dev.guidelines.asciidoc | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/dev.guidelines.asciidoc b/dev.guidelines.asciidoc index b6d7c40bff..1f6c9d6ccd 100644 --- a/dev.guidelines.asciidoc +++ b/dev.guidelines.asciidoc @@ -31,6 +31,13 @@ Once your change is implemented (see coding guidelines below), you will want to == Coding guidelines +=== Commit comment + +* Make sure the issue the commit relates is referenced in the commit comment. +** If your commit closes an issue, think about using the [GitHub options](https://help.github.com/articles/closing-issues-via-commit-messages/) for automatically closing the issue when the commit reaches master. +* For your commit comment, you are strongly encouraged to follow the recommendations found [here}(http://chris.beams.io/posts/git-commit/#seven-rules) +** Feel free also to use emoji - current ones used are based on [the following](https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages) + === Formatting See what's there for now... Ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. We'll export settings for majors IDEs here asap. From 03fb7b4b0ba5a7d7312b126190c551e862b2d892 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 13 Sep 2016 13:44:41 +0200 Subject: [PATCH 065/779] Fix links formatting --- dev.guidelines.asciidoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dev.guidelines.asciidoc b/dev.guidelines.asciidoc index 1f6c9d6ccd..3d50d46f1e 100644 --- a/dev.guidelines.asciidoc +++ b/dev.guidelines.asciidoc @@ -34,9 +34,9 @@ Once your change is implemented (see coding guidelines below), you will want to === Commit comment * Make sure the issue the commit relates is referenced in the commit comment. -** If your commit closes an issue, think about using the [GitHub options](https://help.github.com/articles/closing-issues-via-commit-messages/) for automatically closing the issue when the commit reaches master. -* For your commit comment, you are strongly encouraged to follow the recommendations found [here}(http://chris.beams.io/posts/git-commit/#seven-rules) -** Feel free also to use emoji - current ones used are based on [the following](https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages) +** If your commit closes an issue, think about using the https://help.github.com/articles/closing-issues-via-commit-messages/[GitHub options] for automatically closing the issue when the commit reaches master. +* For your commit comment, you are strongly encouraged to follow the recommendations found http://chris.beams.io/posts/git-commit/#seven-rules[here] +** Feel free also to use emoji - current ones used are based on https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages[the following] === Formatting From 12d154a11e5b882e7fbd2fee65dbba1669b90028 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 13 Sep 2016 13:53:26 +0200 Subject: [PATCH 066/779] Added commit comment example --- dev.guidelines.asciidoc | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/dev.guidelines.asciidoc b/dev.guidelines.asciidoc index 3d50d46f1e..f59f36615a 100644 --- a/dev.guidelines.asciidoc +++ b/dev.guidelines.asciidoc @@ -38,6 +38,15 @@ Once your change is implemented (see coding guidelines below), you will want to * For your commit comment, you are strongly encouraged to follow the recommendations found http://chris.beams.io/posts/git-commit/#seven-rules[here] ** Feel free also to use emoji - current ones used are based on https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages[the following] +Here is an example: + +---- +:bug: Fix #1354 JSR-107 support in ClusteredStore stats + +Some context registrations are required to get the proper statistics +discovered by the JCache stats MBean +---- + === Formatting See what's there for now... Ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. We'll export settings for majors IDEs here asap. From d740d7cc7c8c5e294e841475b8ebb959878e3abb Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Wed, 11 Jan 2017 11:22:59 +0100 Subject: [PATCH 067/779] Updated dev.git (asciidoc) --- dev.git.asciidoc | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index 9430bdcfcb..ab0fab293c 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -57,6 +57,18 @@ That's you doing the work - nothing specific there but the usual commit recommen As the fix developer, integrating the fix in the different target branches is your responsibility. So unless your fix can directly be merged in the different branches, you will have to merge the branches into the fix to resolve conflicts. +The idea behind this strategy is that the commits that were created on branch `issue-1048` in this example are now part of the history of the different releases and tracking which fix exists where is vastly simplified over the different strategies that are `cherry-pick` based. + +===== When no manual merge is needed + +The easiest way is to use GitHub's *compare across forks* feature when creating the pull request. Use the Ehcache repo as the *base fork* and your own repo as the *head fork*, then pick _your_ branch containing the fix as the *compare* branch. + +Now you just need to select the Ehcache branches you want to target (every necessary `release/3.x` ones, plus `master`) as the *base* branch. GitHub will tell you if these branches can be automatically merged. If they can, just create the pull requests as-is. If all branches can be automatically merged, you're done after you created all the pull requests. + +If GitHub reports some branches as having conflicts, you have to read on to create special pull requests containing the merge work. + +===== When manually merging is necessary + I will use the `release/3.0` branch as the target in the example below and assume your fix branch is `issue-1048`. These names should be replaced by the one applicable to your context. . On your fix branch @@ -69,8 +81,6 @@ I will use the `release/3.0` branch as the target in the example below and assum . Open a pull request from that, making sure it is against `release/3.0` . Repeat for each target branch, including `master` -The idea behind this strategy is that the commits that were created on branch `issue-1048` in this example are now part of the history of the different releases and tracking which fix exists where is vastly simplified over the different strategies that are `cherry-pick` based. - == Have it reviewed . The pull request will be reviewed for: From fca8659f4ce4d8fcb2ee1594f31977a14179a954 Mon Sep 17 00:00:00 2001 From: Ludovic Orban Date: Wed, 11 Jan 2017 11:23:37 +0100 Subject: [PATCH 068/779] Updated dev.git (asciidoc) --- dev.git.asciidoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dev.git.asciidoc b/dev.git.asciidoc index ab0fab293c..9c4de849ea 100644 --- a/dev.git.asciidoc +++ b/dev.git.asciidoc @@ -59,7 +59,7 @@ So unless your fix can directly be merged in the different branches, you will ha The idea behind this strategy is that the commits that were created on branch `issue-1048` in this example are now part of the history of the different releases and tracking which fix exists where is vastly simplified over the different strategies that are `cherry-pick` based. -===== When no manual merge is needed +===== Create the pull requests The easiest way is to use GitHub's *compare across forks* feature when creating the pull request. Use the Ehcache repo as the *base fork* and your own repo as the *head fork*, then pick _your_ branch containing the fix as the *compare* branch. From 8fc90868b14ce48655962451ac6a229a910b25c6 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Thu, 12 Oct 2017 10:55:50 +0200 Subject: [PATCH 069/779] Issue #2068 Ehcache expiry based on java.time.Duration This deprecates the existing expiry related APIs and replaces them with APIs based on java.time.Duration For compatibility reasons, the builders still accept the old API and so does the XML. --- .../ehcache/jsr107/ConfigurationMerger.java | 2 +- .../org/ehcache/jsr107/Eh107CacheManager.java | 2 +- .../java/org/ehcache/jsr107/Eh107Expiry.java | 4 +- .../ehcache/jsr107/EhcacheExpiryWrapper.java | 9 +- .../jsr107/ExpiryPolicyToEhcacheExpiry.java | 35 ++- .../ParsesConfigurationExtensionTest.java | 11 +- ...che107ConfigurationIntegrationDocTest.java | 13 +- .../jsr107/ConfigurationMergerTest.java | 16 +- .../ehcache/config/CacheConfiguration.java | 13 + .../java/org/ehcache/expiry/Duration.java | 6 + .../java/org/ehcache/expiry/Expirations.java | 32 ++- .../main/java/org/ehcache/expiry/Expiry.java | 4 + .../org/ehcache/expiry/ExpiryPolicies.java | 229 ++++++++++++++++++ .../java/org/ehcache/expiry/ExpiryPolicy.java | 97 ++++++++ .../java/org/ehcache/expiry/package-info.java | 4 +- .../org/ehcache/expiry/ExpirationsTest.java | 22 +- .../ehcache/expiry/ExpiryPoliciesTest.java | 63 +++++ .../ClusteringServiceConfigurationParser.java | 1 + .../client/internal/store/ClusteredStore.java | 8 +- .../store/operations/ChainResolver.java | 2 - .../store/operations/ExpiryChainResolver.java | 18 +- .../client/BasicClusteredCacheExpiryTest.java | 7 +- .../client/ClusteredCacheExpirationTest.java | 18 +- ...steringServiceConfigurationParserTest.java | 1 + ...ClusterStateRepositoryReplicationTest.java | 2 +- .../StateRepositoryWhitelistingTest.java | 2 +- .../store/ClusteredStoreProviderTest.java | 8 +- .../internal/store/ClusteredStoreTest.java | 2 +- .../ExpiryChainResolverExpiryTest.java | 33 ++- .../operations/ExpiryChainResolverTest.java | 67 +++-- .../test/resources/clusteredConfiguration.txt | 4 +- .../test/resources/simpleConfiguration.txt | 2 +- .../store/StoreComputeIfAbsentTest.java | 7 +- .../internal/store/StoreComputeTest.java | 9 +- .../store/StoreExpiryEventListenerTest.java | 9 +- .../ehcache/internal/store/StoreFactory.java | 4 +- .../ehcache/internal/store/StoreGetTest.java | 9 +- .../internal/store/StorePutIfAbsentTest.java | 9 +- .../ehcache/internal/store/StorePutTest.java | 11 +- .../tier/AuthoritativeTierFactory.java | 4 +- .../tier/AuthoritativeTierGetAndFault.java | 8 +- .../main/java/org/ehcache/core/Ehcache.java | 20 +- .../java/org/ehcache/core/EhcacheManager.java | 2 +- .../core/EhcacheRuntimeConfiguration.java | 11 +- .../core/config/BaseCacheConfiguration.java | 17 +- .../org/ehcache/core/config/ExpiryUtils.java | 161 ++++++++++++ .../store/StoreConfigurationImpl.java | 10 +- .../core/spi/store/AbstractValueHolder.java | 16 +- .../org/ehcache/core/spi/store/Store.java | 4 +- .../core/EhcacheBasicPutIfAbsentTest.java | 4 +- .../ehcache/core/EhcacheBulkMethodsTest.java | 4 +- ...hcacheWithLoaderWriterBasicPutAllTest.java | 10 +- ...eWithLoaderWriterBasicPutIfAbsentTest.java | 8 +- ...cacheWithLoaderWriterBasicReplaceTest.java | 12 +- ...WithLoaderWriterBasicReplaceValueTest.java | 12 +- ...hcacheWithLoaderWriterBulkMethodsTest.java | 6 +- .../spi/store/AbstractValueHolderTest.java | 4 +- .../builders/CacheConfigurationBuilder.java | 28 ++- .../builders/UserManagedCacheBuilder.java | 24 +- .../impl/internal/store/heap/OnHeapStore.java | 43 ++-- .../heap/holders/CopiedOnHeapValueHolder.java | 3 +- .../holders/SerializedOnHeapValueHolder.java | 5 +- .../store/offheap/AbstractOffHeapStore.java | 39 ++- .../CacheConfigurationBuilderTest.java | 13 +- .../builders/UserManagedCacheBuilderTest.java | 7 +- .../java/org/ehcache/docs/GettingStarted.java | 10 +- .../PooledExecutorWriteBehindTest.java | 7 +- .../writebehind/WriteBehindEvictionTest.java | 7 +- .../writebehind/WriteBehindTest.java | 7 +- .../DefaultCacheStatisticsTest.java | 9 +- .../statistics/DefaultTierStatisticsTest.java | 9 +- .../disk/OffHeapDiskStoreProviderTest.java | 8 +- .../store/disk/OffHeapDiskStoreSPITest.java | 14 +- .../store/disk/OffHeapDiskStoreTest.java | 8 +- .../store/heap/BaseOnHeapStoreTest.java | 72 +++--- .../ByteSizedOnHeapStoreByRefSPITest.java | 14 +- .../ByteSizedOnHeapStoreByValueSPITest.java | 14 +- .../heap/CountSizedOnHeapStoreByRefTest.java | 6 +- .../CountSizedOnHeapStoreByValueTest.java | 6 +- .../heap/OnHeapStoreBulkMethodsTest.java | 7 +- .../store/heap/OnHeapStoreByRefSPITest.java | 14 +- .../store/heap/OnHeapStoreByRefTest.java | 6 +- .../store/heap/OnHeapStoreByValueSPITest.java | 14 +- .../store/heap/OnHeapStoreByValueTest.java | 11 +- .../OnHeapStoreCachingTierByRefSPITest.java | 4 +- .../OnHeapStoreCachingTierByValueSPITest.java | 4 +- .../store/heap/OnHeapStoreEvictionTest.java | 16 +- .../store/heap/OnHeapStoreKeyCopierTest.java | 7 +- .../heap/OnHeapStoreValueCopierTest.java | 6 +- .../heap/bytesized/ByteAccountingTest.java | 47 ++-- .../ByteSizedOnHeapStoreByRefTest.java | 6 +- .../ByteSizedOnHeapStoreByValueTest.java | 6 +- .../bytesized/OnHeapStoreBulkMethodsTest.java | 7 +- .../OnHeapStoreCachingTierByRefSPITest.java | 4 +- .../OnHeapStoreCachingTierByValueSPITest.java | 4 +- .../bytesized/OnHeapStoreEvictionTest.java | 8 +- .../heap/bytesized/OversizeMappingTest.java | 15 +- .../offheap/AbstractOffHeapStoreTest.java | 78 +++--- .../store/offheap/OffHeapStoreSPITest.java | 14 +- .../store/offheap/OffHeapStoreTest.java | 6 +- .../tiering/CompoundCachingTierSPITest.java | 4 +- .../TieredStoreFlushWhileShutdownTest.java | 10 +- .../store/tiering/TieredStoreMutatorTest.java | 4 +- .../store/tiering/TieredStoreSPITest.java | 14 +- .../tiering/TieredStoreWith3TiersSPITest.java | 14 +- .../integration/EventNotificationTest.java | 9 +- .../integration/ExpiryEhcacheTestBase.java | 7 +- .../ehcache/integration/ExpiryEventsTest.java | 8 +- .../statistics/TierCalculationTest.java | 6 +- .../transactions/xa/XACacheTest.java | 14 +- .../settings/EhcacheSettingsProviderTest.java | 8 +- .../transactions/xa/internal/XAStore.java | 16 +- .../integration/StatefulSerializerTest.java | 4 +- .../transactions/xa/internal/XAStoreTest.java | 46 ++-- .../xa/internal/XAValueHolderTest.java | 4 +- .../org/ehcache/xml/ConfigurationParser.java | 7 +- .../org/ehcache/xml/XmlConfiguration.java | 24 +- .../main/java/org/ehcache/xml/XmlModel.java | 22 ++ xml/src/main/resources/ehcache-core.xsd | 2 +- .../com/pany/ehcache/DeprecatedExpiry.java | 43 ++++ .../test/java/com/pany/ehcache/MyExpiry.java | 13 +- .../org/ehcache/xml/XmlConfigurationTest.java | 33 +-- .../test/resources/configs/expiry-caches.xml | 9 + 123 files changed, 1365 insertions(+), 701 deletions(-) create mode 100644 api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java create mode 100644 api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java create mode 100644 api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java create mode 100644 core/src/main/java/org/ehcache/core/config/ExpiryUtils.java create mode 100644 xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java diff --git a/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java b/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java index ec8db61e07..db33ef8ea2 100644 --- a/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java +++ b/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java @@ -127,7 +127,7 @@ ConfigHolder mergeConfigurations(String cacheName, Configuration(cacheConfiguration.getExpiry()); + expiryPolicy = new EhcacheExpiryWrapper<>(cacheConfiguration.getExpiryPolicy()); } return new ConfigHolder<>( diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java b/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java index 1b4e308765..d96e4a6516 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java @@ -119,7 +119,7 @@ private Eh107Cache wrapEhcacheCache(String alias, InternalCache config = new Eh107ReverseConfiguration<>(cache, cacheLoaderWriter != null, cacheLoaderWriter != null, storeByValueOnHeap); configurationMerger.setUpManagementAndStats(cache, config); - Eh107Expiry expiry = new EhcacheExpiryWrapper<>(cache.getRuntimeConfiguration().getExpiry()); + Eh107Expiry expiry = new EhcacheExpiryWrapper<>(cache.getRuntimeConfiguration().getExpiryPolicy()); CacheResources resources = new CacheResources<>(alias, wrapCacheLoaderWriter(cacheLoaderWriter), expiry); return new Eh107Cache<>(alias, config, resources, cache, this); } diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107Expiry.java b/107/src/main/java/org/ehcache/jsr107/Eh107Expiry.java index 16acd241a2..ffa45e7404 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107Expiry.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107Expiry.java @@ -15,12 +15,12 @@ */ package org.ehcache.jsr107; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; /** * Eh107Expiry */ -abstract class Eh107Expiry implements Expiry { +abstract class Eh107Expiry implements ExpiryPolicy { private final ThreadLocal shortCircuitAccess = new ThreadLocal<>(); void enableShortCircuitAccessCalls() { diff --git a/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java b/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java index 3b49e088b3..1d2b92f398 100644 --- a/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java +++ b/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java @@ -16,17 +16,18 @@ package org.ehcache.jsr107; import org.ehcache.ValueSupplier; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; + +import java.time.Duration; /** * EhcacheExpiryWrapper */ class EhcacheExpiryWrapper extends Eh107Expiry { - private final Expiry wrappedExpiry; + private final ExpiryPolicy wrappedExpiry; - EhcacheExpiryWrapper(Expiry wrappedExpiry) { + EhcacheExpiryWrapper(ExpiryPolicy wrappedExpiry) { this.wrappedExpiry = wrappedExpiry; } diff --git a/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java b/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java index 43c4ac13b8..740161bfe9 100644 --- a/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java +++ b/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java @@ -16,6 +16,7 @@ package org.ehcache.jsr107; import org.ehcache.ValueSupplier; +import org.ehcache.core.config.ExpiryUtils; import java.io.Closeable; import java.io.IOException; @@ -32,20 +33,17 @@ class ExpiryPolicyToEhcacheExpiry extends Eh107Expiry implements Clo } @Override - public org.ehcache.expiry.Duration getExpiryForCreation(K key, V value) { + public java.time.Duration getExpiryForCreation(K key, V value) { try { Duration duration = expiryPolicy.getExpiryForCreation(); - if (duration.isEternal()) { - return org.ehcache.expiry.Duration.INFINITE; - } - return new org.ehcache.expiry.Duration(duration.getDurationAmount(), duration.getTimeUnit()); + return convertDuration(duration); } catch (Throwable t) { - return org.ehcache.expiry.Duration.ZERO; + return java.time.Duration.ZERO; } } @Override - public org.ehcache.expiry.Duration getExpiryForAccess(K key, ValueSupplier value) { + public java.time.Duration getExpiryForAccess(K key, ValueSupplier value) { if (isShortCircuitAccessCalls()) { return null; } @@ -55,28 +53,22 @@ public org.ehcache.expiry.Duration getExpiryForAccess(K key, ValueSupplier oldValue, V newValue) { + public java.time.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { try { Duration duration = expiryPolicy.getExpiryForUpdate(); if (duration == null) { return null; } - if (duration.isEternal()) { - return org.ehcache.expiry.Duration.INFINITE; - } - return new org.ehcache.expiry.Duration(duration.getDurationAmount(), duration.getTimeUnit()); + return convertDuration(duration); } catch (Throwable t) { - return org.ehcache.expiry.Duration.ZERO; + return java.time.Duration.ZERO; } } @@ -86,4 +78,11 @@ public void close() throws IOException { ((Closeable)expiryPolicy).close(); } } + + private java.time.Duration convertDuration(Duration duration) { + if (duration.isEternal()) { + return org.ehcache.expiry.ExpiryPolicy.INFINITE; + } + return java.time.Duration.of(duration.getDurationAmount(), ExpiryUtils.jucTimeUnitToTemporalUnit(duration.getTimeUnit())); + } } diff --git a/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java b/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java index eedc12cae4..060633ba13 100644 --- a/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java +++ b/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java @@ -23,20 +23,19 @@ import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.core.EhcacheManager; import org.ehcache.core.spi.service.ServiceUtils; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.jsr107.config.Jsr107Configuration; import org.ehcache.config.ResourceType; import org.ehcache.xml.XmlConfiguration; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; import org.ehcache.jsr107.internal.DefaultJsr107Service; import org.ehcache.spi.service.Service; import org.junit.Test; import org.xml.sax.SAXException; import java.io.IOException; +import java.time.Duration; import java.util.Collections; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.hamcrest.CoreMatchers.equalTo; @@ -83,9 +82,9 @@ public void testXmlExample() throws ClassNotFoundException, SAXException, Instan final CacheRuntimeConfiguration runtimeConfiguration = productCache.getRuntimeConfiguration(); assertThat(runtimeConfiguration.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(200L)); - final Expiry expiry = runtimeConfiguration.getExpiry(); - assertThat(expiry.getClass().getName(), equalTo("org.ehcache.expiry.Expirations$TimeToIdleExpiry")); - assertThat(expiry.getExpiryForAccess(42L, null), equalTo(new Duration(2, TimeUnit.MINUTES))); + final ExpiryPolicy expiry = runtimeConfiguration.getExpiryPolicy(); + assertThat(expiry.getClass().getName(), equalTo("org.ehcache.expiry.ExpiryPolicies$TimeToIdleExpiryPolicy")); + assertThat(expiry.getExpiryForAccess(42L, null), equalTo(Duration.ofMinutes(2))); assertThat(runtimeConfiguration.getEvictionAdvisor(), instanceOf(com.pany.ehcache.MyEvictionAdvisor.class)); } diff --git a/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java b/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java index be00ddb591..841d49f95e 100644 --- a/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java +++ b/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java @@ -39,7 +39,6 @@ import java.io.File; import java.util.Random; -import java.util.concurrent.TimeUnit; import javax.cache.Cache; import javax.cache.CacheManager; @@ -129,11 +128,11 @@ public void testGettingToEhcacheConfiguration() { long nanoTime = System.nanoTime(); LOGGER.info("Seeding random with {}", nanoTime); Random random = new Random(nanoTime); - assertThat(runtimeConfiguration.getExpiry().getExpiryForCreation(random.nextLong(), Long.toOctalString(random.nextLong())), - equalTo(org.ehcache.expiry.Duration.INFINITE)); - assertThat(runtimeConfiguration.getExpiry().getExpiryForAccess(random.nextLong(), + assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForCreation(random.nextLong(), Long.toOctalString(random.nextLong())), + equalTo(org.ehcache.expiry.ExpiryPolicy.INFINITE)); + assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForAccess(random.nextLong(), ValueSuppliers.supplierOf(Long.toOctalString(random.nextLong()))), nullValue()); - assertThat(runtimeConfiguration.getExpiry().getExpiryForUpdate(random.nextLong(), + assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForUpdate(random.nextLong(), ValueSuppliers.supplierOf(Long.toOctalString(random.nextLong())), Long.toOctalString(random.nextLong())), nullValue()); } @@ -214,8 +213,8 @@ public void testWithoutEhcacheExplicitDependencyAndNoCodeChanges() throws Except } // end::jsr107SupplementWithTemplatesExample[] assertThat(ehcacheConfig.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), is(20L)); - assertThat(foosEhcacheConfig.getExpiry().getExpiryForCreation(42L, client1), - is(new org.ehcache.expiry.Duration(2, TimeUnit.MINUTES))); + assertThat(foosEhcacheConfig.getExpiryPolicy().getExpiryForCreation(42L, client1), + is(java.time.Duration.ofMinutes(2))); } @Test diff --git a/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java b/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java index 2f20b29728..6226a26293 100644 --- a/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java +++ b/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java @@ -18,12 +18,10 @@ import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.core.spi.service.ServiceUtils; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.jsr107.config.Jsr107Configuration; import org.ehcache.jsr107.config.Jsr107Service; @@ -38,8 +36,8 @@ import org.mockito.internal.creation.MockSettingsImpl; import java.io.Closeable; +import java.time.Duration; import java.util.Collection; -import java.util.concurrent.TimeUnit; import javax.cache.configuration.CacheEntryListenerConfiguration; import javax.cache.configuration.Factory; @@ -90,7 +88,7 @@ public void mergeConfigNoTemplateNoLoaderWriter() { MutableConfiguration configuration = new MutableConfiguration<>(); ConfigurationMerger.ConfigHolder configHolder = merger.mergeConfigurations("cache", configuration); - assertThat(configHolder.cacheResources.getExpiryPolicy().getExpiryForCreation(42L, "Yay!"), is(Duration.INFINITE)); + assertThat(configHolder.cacheResources.getExpiryPolicy().getExpiryForCreation(42L, "Yay!"), is(org.ehcache.expiry.ExpiryPolicy.INFINITE)); assertThat(configHolder.cacheResources.getCacheLoaderWriter(), nullValue()); assertThat(configHolder.useEhcacheLoaderWriter, is(false)); @@ -114,8 +112,8 @@ public void jsr107ExpiryGetsRegistered() { ConfigurationMerger.ConfigHolder configHolder = merger.mergeConfigurations("Cache", configuration); assertThat(factory.called, is(true)); - Expiry resourcesExpiry = configHolder.cacheResources.getExpiryPolicy(); - Expiry configExpiry = configHolder.cacheConfiguration.getExpiry(); + org.ehcache.expiry.ExpiryPolicy resourcesExpiry = configHolder.cacheResources.getExpiryPolicy(); + org.ehcache.expiry.ExpiryPolicy configExpiry = configHolder.cacheConfiguration.getExpiryPolicy(); assertThat(configExpiry, sameInstance(resourcesExpiry)); } @@ -165,7 +163,7 @@ public void loadsTemplateWhenNameFound() throws Exception { public void jsr107ExpiryGetsOverriddenByTemplate() throws Exception { when(jsr107Service.getTemplateNameForCache("cache")).thenReturn("cacheTemplate"); when(xmlConfiguration.newCacheConfigurationBuilderFromTemplate("cacheTemplate", Object.class, Object.class)).thenReturn( - newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withExpiry(Expirations.timeToLiveExpiration(new Duration(5, TimeUnit.MINUTES))) + newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMinutes(5))) ); MutableConfiguration configuration = new MutableConfiguration<>(); @@ -176,7 +174,7 @@ public void jsr107ExpiryGetsOverriddenByTemplate() throws Exception { assertThat(factory.called, is(false)); Eh107Expiry expiryPolicy = configHolder.cacheResources.getExpiryPolicy(); - Expiry expiry = configHolder.cacheConfiguration.getExpiry(); + org.ehcache.expiry.ExpiryPolicy expiry = configHolder.cacheConfiguration.getExpiryPolicy(); assertThat(expiryPolicy.getExpiryForAccess(42, supplierOf("Yay")), is(expiry.getExpiryForAccess(42, supplierOf("Yay")))); assertThat(expiryPolicy.getExpiryForUpdate(42, supplierOf("Yay"), "Lala"), is(expiry.getExpiryForUpdate(42, supplierOf("Yay"), "Lala"))); assertThat(expiryPolicy.getExpiryForCreation(42, "Yay"), is(expiry.getExpiryForCreation(42, "Yay"))); diff --git a/api/src/main/java/org/ehcache/config/CacheConfiguration.java b/api/src/main/java/org/ehcache/config/CacheConfiguration.java index d90c349792..f7d744b700 100644 --- a/api/src/main/java/org/ehcache/config/CacheConfiguration.java +++ b/api/src/main/java/org/ehcache/config/CacheConfiguration.java @@ -18,6 +18,7 @@ import org.ehcache.Cache; import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; import java.util.Collection; @@ -87,9 +88,21 @@ public interface CacheConfiguration { * The {@code Expiry} cannot be null. * * @return the {@code Expiry} + * + * @deprecated Use {@link #getExpiryPolicy()} */ + @Deprecated Expiry getExpiry(); + /** + * The {@link ExpiryPolicy} rules for the {@link Cache}. + *

+ * The {@code ExpiryPolicy} cannot be null. + * + * @return the {@code ExpiryPolicy} + */ + ExpiryPolicy getExpiryPolicy(); + /** * The {@link ResourcePools} for the {@link Cache}. *

diff --git a/api/src/main/java/org/ehcache/expiry/Duration.java b/api/src/main/java/org/ehcache/expiry/Duration.java index 477d9ea41e..032baa4a72 100644 --- a/api/src/main/java/org/ehcache/expiry/Duration.java +++ b/api/src/main/java/org/ehcache/expiry/Duration.java @@ -19,7 +19,13 @@ /** * A time duration in a given {@link TimeUnit}. + * + * @see java.time.Duration + * @see ExpiryPolicy + * + * @deprecated Replaced with {@link java.time.Duration} */ +@Deprecated public final class Duration { /** diff --git a/api/src/main/java/org/ehcache/expiry/Expirations.java b/api/src/main/java/org/ehcache/expiry/Expirations.java index bb19093d9f..b4b79fb4b6 100644 --- a/api/src/main/java/org/ehcache/expiry/Expirations.java +++ b/api/src/main/java/org/ehcache/expiry/Expirations.java @@ -17,16 +17,22 @@ import org.ehcache.ValueSupplier; +import java.util.Objects; + /** * Utility class for getting predefined {@link Expiry} instances. */ +@Deprecated public final class Expirations { /** * Get an {@link Expiry} instance for a non expiring (ie. "eternal") cache. * * @return the no expiry instance + * + * @deprecated Use {@link ExpiryPolicies#noExpiration()} instead */ + @Deprecated public static Expiry noExpiration() { return NoExpiry.INSTANCE; } @@ -36,7 +42,10 @@ public static Expiry noExpiration() { * * @param timeToLive the TTL duration * @return a TTL expiry + * + * @deprecated Use {@link ExpiryPolicies#timeToLiveExpiration(java.time.Duration)} instead */ + @Deprecated public static Expiry timeToLiveExpiration(Duration timeToLive) { if (timeToLive == null) { throw new NullPointerException("Duration cannot be null"); @@ -49,7 +58,10 @@ public static Expiry timeToLiveExpiration(Duration timeToLive) { * * @param timeToIdle the TTI duration * @return a TTI expiry + * + * @deprecated Use {@link ExpiryPolicies#timeToIdleExpiration(java.time.Duration)} instead */ + @Deprecated public static Expiry timeToIdleExpiration(Duration timeToIdle) { if (timeToIdle == null) { throw new NullPointerException("Duration cannot be null"); @@ -65,7 +77,10 @@ public static Expiry timeToIdleExpiration(Duration timeToIdle) { * @param the key type for the cache * @param the value type for the cache * @return an {@link Expiry} builder + * + * @deprecated Use {@link ExpiryPolicies#builder()} instead */ + @Deprecated public static ExpiryBuilder builder() { return new ExpiryBuilder<>(); } @@ -77,6 +92,7 @@ private Expirations() { /** * Simple implementation of the {@link Expiry} interface allowing to set constants to each expiry types. */ + @Deprecated private static class BaseExpiry implements Expiry { private final Duration create; @@ -111,18 +127,18 @@ public boolean equals(final Object o) { final BaseExpiry that = (BaseExpiry)o; - if (access != null ? !access.equals(that.access) : that.access != null) return false; - if (create != null ? !create.equals(that.create) : that.create != null) return false; - if (update != null ? !update.equals(that.update) : that.update != null) return false; + if (!Objects.equals(access, that.access)) return false; + if (!Objects.equals(create, that.create)) return false; + if (!Objects.equals(update, that.update)) return false; return true; } @Override public int hashCode() { - int result = create != null ? create.hashCode() : 0; - result = 31 * result + (access != null ? access.hashCode() : 0); - result = 31 * result + (update != null ? update.hashCode() : 0); + int result = Objects.hashCode(create); + result = 31 * result + Objects.hashCode(access); + result = 31 * result + Objects.hashCode(update); return result; } @@ -136,18 +152,21 @@ public String toString() { } } + @Deprecated private static class TimeToLiveExpiry extends BaseExpiry { TimeToLiveExpiry(Duration ttl) { super(ttl, null, ttl); } } + @Deprecated private static class TimeToIdleExpiry extends BaseExpiry { TimeToIdleExpiry(Duration tti) { super(tti, tti, tti); } } + @Deprecated private static class NoExpiry extends BaseExpiry { private static final Expiry INSTANCE = new NoExpiry(); @@ -163,6 +182,7 @@ private NoExpiry() { * @param Key type of the cache entries * @param Value type of the cache entries */ + @Deprecated public static final class ExpiryBuilder { private Duration create = Duration.INFINITE; diff --git a/api/src/main/java/org/ehcache/expiry/Expiry.java b/api/src/main/java/org/ehcache/expiry/Expiry.java index b9a38f5847..db8e44fc35 100644 --- a/api/src/main/java/org/ehcache/expiry/Expiry.java +++ b/api/src/main/java/org/ehcache/expiry/Expiry.java @@ -35,7 +35,11 @@ * @param the value type for the cache * * @see Expirations + * @see ExpiryPolicy + * + * @deprecated Replaced with {@link ExpiryPolicy} that builds on the {@code java.time} types. */ +@Deprecated public interface Expiry { /** diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java b/api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java new file mode 100644 index 0000000000..7aa75ae6c0 --- /dev/null +++ b/api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java @@ -0,0 +1,229 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.expiry; + +import org.ehcache.ValueSupplier; + +import java.util.Objects; + +/** + * Utility class for getting predefined {@link ExpiryPolicy} instances. + */ +public final class ExpiryPolicies { + + /** + * Get an {@link ExpiryPolicy} instance for a non expiring (ie. "eternal") cache. + * + * @return the no expiry instance + */ + public static ExpiryPolicy noExpiration() { + return NoExpiryPolicy.INSTANCE; + } + + /** + * Get a time-to-live (TTL) {@link ExpiryPolicy} instance for the given {@link java.time.Duration}. + * + * @param timeToLive the TTL duration + * @return a TTL expiry + */ + public static ExpiryPolicy timeToLiveExpiration(java.time.Duration timeToLive) { + Objects.requireNonNull(timeToLive, "TTL duration cannot be null"); + if (timeToLive.isNegative()) { + throw new IllegalArgumentException("TTL duration cannot be negative"); + } + return new TimeToLiveExpiryPolicy(timeToLive); + } + + /** + * Get a time-to-idle (TTI) {@link ExpiryPolicy} instance for the given {@link java.time.Duration}. + * + * @param timeToIdle the TTI duration + * @return a TTI expiry + */ + public static ExpiryPolicy timeToIdleExpiration(java.time.Duration timeToIdle) { + Objects.requireNonNull(timeToIdle, "TTI duration cannot be null"); + if (timeToIdle.isNegative()) { + throw new IllegalArgumentException("TTI duration cannot be negative"); + } + return new TimeToIdleExpiryPolicy(timeToIdle); + } + + /** + * Fluent API for creating an {@link ExpiryPolicy} instance where you can specify constant values for creation, access and update time. + * Unspecified values will be set to {@link ExpiryPolicy#INFINITE INFINITE} for create and {@code null} for access and update, matching + * the {@link #noExpiration()} no expiration} expiry. + * + * @param the key type for the cache + * @param the value type for the cache + * @return an {@link ExpiryPolicy} builder + */ + public static ExpiryPolicyBuilder builder() { + return new ExpiryPolicyBuilder<>(); + } + + + private ExpiryPolicies() { + // + } + + /** + * Simple implementation of the {@link ExpiryPolicy} interface allowing to set constants to each expiry types. + */ + private static class BaseExpiryPolicy implements ExpiryPolicy { + + private final java.time.Duration create; + private final java.time.Duration access; + private final java.time.Duration update; + + BaseExpiryPolicy(java.time.Duration create, java.time.Duration access, java.time.Duration update) { + this.create = create; + this.access = access; + this.update = update; + } + @Override + public java.time.Duration getExpiryForCreation(K key, V value) { + return create; + } + + @Override + public java.time.Duration getExpiryForAccess(K key, ValueSupplier value) { + return access; + } + + @Override + public java.time.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + return update; + } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + final BaseExpiryPolicy that = (BaseExpiryPolicy) o; + + if (!Objects.equals(access, that.access)) return false; + if (!Objects.equals(create, that.create)) return false; + if (!Objects.equals(update, that.update)) return false; + + return true; + } + + @Override + public int hashCode() { + int result = Objects.hashCode(create); + result = 31 * result + Objects.hashCode(access); + result = 31 * result + Objects.hashCode(update); + return result; + } + + @Override + public String toString() { + return this.getClass().getSimpleName() + "{" + + "create=" + create + + ", access=" + access + + ", update=" + update + + '}'; + } + } + + private static class TimeToLiveExpiryPolicy extends BaseExpiryPolicy { + TimeToLiveExpiryPolicy(java.time.Duration ttl) { + super(ttl, null, ttl); + } + } + + private static class TimeToIdleExpiryPolicy extends BaseExpiryPolicy { + TimeToIdleExpiryPolicy(java.time.Duration tti) { + super(tti, tti, tti); + } + } + + private static class NoExpiryPolicy extends BaseExpiryPolicy { + + private static final ExpiryPolicy INSTANCE = new NoExpiryPolicy(); + + private NoExpiryPolicy() { + super(ExpiryPolicy.INFINITE, null, null); + } + } + + /** + * Builder to create a simple {@link Expiry}. + * + * @param Key type of the cache entries + * @param Value type of the cache entries + */ + public static final class ExpiryPolicyBuilder { + + private java.time.Duration create = ExpiryPolicy.INFINITE; + private java.time.Duration access = null; + private java.time.Duration update = null; + + private ExpiryPolicyBuilder() {} + + /** + * Set TTL since creation + * + * @param create TTL since creation + * @return this builder + */ + public ExpiryPolicyBuilder setCreate(java.time.Duration create) { + Objects.requireNonNull(create, "Create duration cannot be null"); + if (create.isNegative()) { + throw new IllegalArgumentException("Create duration must be positive"); + } + this.create = create; + return this; + } + + /** + * Set TTL since last access + * + * @param access TTL since last access + * @return this builder + */ + public ExpiryPolicyBuilder setAccess(java.time.Duration access) { + if (access != null && access.isNegative()) { + throw new IllegalArgumentException("Access duration must be positive"); + } + this.access = access; + return this; + } + + /** + * Set TTL since last update + * + * @param update TTL since last update + * @return this builder + */ + public ExpiryPolicyBuilder setUpdate(java.time.Duration update) { + if (update != null && update.isNegative()) { + throw new IllegalArgumentException("Update duration must be positive"); + } + this.update = update; + return this; + } + + /** + * + * @return an {@link Expiry} + */ + public ExpiryPolicy build() { + return new BaseExpiryPolicy<>(create, access, update); + } + } +} diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java new file mode 100644 index 0000000000..0fe4b7a4eb --- /dev/null +++ b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java @@ -0,0 +1,97 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.expiry; + +import org.ehcache.ValueSupplier; + +import java.time.Duration; + +/** + * A policy object that governs expiration for mappings in a {@link org.ehcache.Cache Cache}. + *

+ * Previous values are not accessible directly but are rather available through a {@link ValueSupplier value supplier} + * to indicate that access can require computation (such as deserialization). + *

+ * {@link Duration#isNegative() Negative duration} are not supported, expiry policy implementation returning such a + * duration will result in immediate expiry, as if the duration was {@link java.time.Duration#ZERO zero}. + *

+ * NOTE: Some cache configurations (eg. caches with eventual consistency) may use local (ie. non-consistent) state + * to decide whether to call {@link #getExpiryForUpdate(Object, ValueSupplier, Object)} vs. + * {@link #getExpiryForCreation(Object, Object)}. For these cache configurations it is advised to return the same + * value for both of these methods + *

+ * See {@link ExpiryPolicies} for helper methods to create common {@code ExpiryPolicy} instances. + * + * @param the key type for the cache + * @param the value type for the cache + * + * @see ExpiryPolicies + */ +public interface ExpiryPolicy { + + /** + * A {@link java.time.Duration duration} that represents an infinite time. + */ + java.time.Duration INFINITE = java.time.Duration.ofSeconds(Long.MAX_VALUE); + + /** + * Returns the lifetime of an entry when it is initially added to a {@link org.ehcache.Cache Cache}. + *

+ * This method must not return {@code null}. + *

+ * Exceptions thrown from this method will be swallowed and result in the expiry duration being + * {@link java.time.Duration#ZERO ZERO}. + * + * @param key the key of the newly added entry + * @param value the value of the newly added entry + * @return a non-null {@code Duration} + */ + java.time.Duration getExpiryForCreation(K key, V value); + + /** + * Returns the expiration {@link java.time.Duration duration} (relative to the current time) when an existing entry + * is accessed from a {@link org.ehcache.Cache Cache}. + *

+ * Returning {@code null} indicates that the expiration time remains unchanged. + *

+ * Exceptions thrown from this method will be swallowed and result in the expiry duration being + * {@link java.time.Duration#ZERO ZERO}. + * + * @param key the key of the accessed entry + * @param value a value supplier for the accessed entry + * @return an expiration {@code Duration}, {@code null} means unchanged + */ + java.time.Duration getExpiryForAccess(K key, ValueSupplier value); + + + /** + * Returns the expiration {@link java.time.Duration duration} (relative to the current time) when an existing entry + * is updated in a {@link org.ehcache.Cache Cache}. + *

+ * Returning {@code null} indicates that the expiration time remains unchanged. + *

+ * Exceptions thrown from this method will be swallowed and result in the expiry duration being + * {@link java.time.Duration#ZERO ZERO}. + * + * @param key the key of the updated entry + * @param oldValue a value supplier for the previous value of the entry + * @param newValue the new value of the entry + * @return an expiration {@code Duration}, {@code null} means unchanged + */ + java.time.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue); + +} diff --git a/api/src/main/java/org/ehcache/expiry/package-info.java b/api/src/main/java/org/ehcache/expiry/package-info.java index 4ea3f314dd..5882311f93 100644 --- a/api/src/main/java/org/ehcache/expiry/package-info.java +++ b/api/src/main/java/org/ehcache/expiry/package-info.java @@ -15,6 +15,6 @@ */ /** - * {@link org.ehcache.expiry.Expiry Expiry} API of a {@link org.ehcache.Cache Cache}. + * {@link org.ehcache.expiry.ExpiryPolicy Expiry} API of a {@link org.ehcache.Cache Cache}. */ -package org.ehcache.expiry; \ No newline at end of file +package org.ehcache.expiry; diff --git a/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java b/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java index 05d8d1988c..8816331321 100644 --- a/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java +++ b/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java @@ -21,7 +21,6 @@ import java.util.concurrent.TimeUnit; -import org.ehcache.ValueSupplier; import org.junit.Test; public class ExpirationsTest { @@ -30,8 +29,8 @@ public class ExpirationsTest { public void testNoExpiration() { Expiry expiry = Expirations.noExpiration(); assertThat(expiry.getExpiryForCreation(this, this), equalTo(Duration.INFINITE)); - assertThat(expiry.getExpiryForAccess(this, holderOf(this)), nullValue()); - assertThat(expiry.getExpiryForUpdate(this, holderOf(this), this), nullValue()); + assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue()); + assertThat(expiry.getExpiryForUpdate(this, () -> this, this), nullValue()); } @Test @@ -39,17 +38,17 @@ public void testTTIExpiration() { Duration duration = new Duration(1L, TimeUnit.SECONDS); Expiry expiry = Expirations.timeToIdleExpiration(duration); assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration)); - assertThat(expiry.getExpiryForAccess(this, holderOf(this)), equalTo(duration)); - assertThat(expiry.getExpiryForUpdate(this, holderOf(this), this), equalTo(duration)); + assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(duration)); + assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration)); } @Test public void testTTLExpiration() { Duration duration = new Duration(1L, TimeUnit.SECONDS); Expiry expiry = Expirations.timeToLiveExpiration(duration); - assertThat(expiry.getExpiryForCreation(this, holderOf(this)), equalTo(duration)); - assertThat(expiry.getExpiryForAccess(this, holderOf(this)), nullValue()); - assertThat(expiry.getExpiryForUpdate(this, holderOf(this), this), equalTo(duration)); + assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration)); + assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue()); + assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration)); } @Test @@ -59,11 +58,8 @@ public void testExpiration() { Duration update = new Duration(3L, TimeUnit.SECONDS); Expiry expiry = Expirations.builder().setCreate(creation).setAccess(access).setUpdate(update).build(); assertThat(expiry.getExpiryForCreation(this, this), equalTo(creation)); - assertThat(expiry.getExpiryForAccess(this, holderOf(this)), equalTo(access)); - assertThat(expiry.getExpiryForUpdate(this, holderOf(this),this), equalTo(update)); + assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(access)); + assertThat(expiry.getExpiryForUpdate(this, () -> this,this), equalTo(update)); } - private ValueSupplier holderOf(final Object obj) { - return () -> obj; - } } diff --git a/api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java b/api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java new file mode 100644 index 0000000000..1071212c4f --- /dev/null +++ b/api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java @@ -0,0 +1,63 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.expiry; + +import org.junit.Test; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.nullValue; + +public class ExpiryPoliciesTest { + + @Test + public void testNoExpiration() { + ExpiryPolicy expiry = ExpiryPolicies.noExpiration(); + assertThat(expiry.getExpiryForCreation(this, this), equalTo(ExpiryPolicy.INFINITE)); + assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue()); + assertThat(expiry.getExpiryForUpdate(this, () -> this, this), nullValue()); + } + + @Test + public void testTTIExpiration() { + java.time.Duration duration = java.time.Duration.ofSeconds(1L); + ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(duration); + assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration)); + assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(duration)); + assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration)); + } + + @Test + public void testTTLExpiration() { + java.time.Duration duration = java.time.Duration.ofSeconds(1L); + ExpiryPolicy expiry = ExpiryPolicies.timeToLiveExpiration(duration); + assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration)); + assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue()); + assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration)); + } + + @Test + public void testExpiration() { + java.time.Duration creation = java.time.Duration.ofSeconds(1L); + java.time.Duration access = java.time.Duration.ofSeconds(2L); + java.time.Duration update = java.time.Duration.ofSeconds(3L); + ExpiryPolicy expiry = ExpiryPolicies.builder().setCreate(creation).setAccess(access).setUpdate(update).build(); + assertThat(expiry.getExpiryForCreation(this, this), equalTo(creation)); + assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(access)); + assertThat(expiry.getExpiryForUpdate(this, () -> this,this), equalTo(update)); + } + +} diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java index ddc8fc1f62..12d1c93454 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java @@ -54,6 +54,7 @@ import javax.xml.transform.stream.StreamSource; import static org.ehcache.clustered.client.internal.config.xml.ClusteredCacheConstants.*; +import static org.ehcache.xml.XmlModel.convertToJavaTemporalUnit; import static org.ehcache.xml.XmlModel.convertToJavaTimeUnit; /** diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java index 44cd04eaa9..56854debc3 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java @@ -52,8 +52,8 @@ import org.ehcache.core.spi.time.TimeSourceService; import org.ehcache.core.statistics.StoreOperationOutcomes.EvictionOutcome; import org.ehcache.core.statistics.TierOperationOutcomes; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.store.HashUtils; @@ -633,8 +633,8 @@ private ClusteredStore createStoreInternal(Configuration stor OperationsCodec codec = new OperationsCodec<>(storeConfig.getKeySerializer(), storeConfig.getValueSerializer()); ChainResolver resolver; - Expiry expiry = storeConfig.getExpiry(); - if (Expirations.noExpiration().equals(expiry)) { + ExpiryPolicy expiry = storeConfig.getExpiry(); + if (ExpiryPolicies.noExpiration().equals(expiry)) { resolver = new EternalChainResolver<>(codec); } else { resolver = new ExpiryChainResolver<>(codec, expiry); diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java index 8d1457b1a6..52943863e8 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ChainResolver.java @@ -27,7 +27,6 @@ import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; -import java.util.concurrent.TimeUnit; /** * An abstract chain resolver. @@ -42,7 +41,6 @@ */ public abstract class ChainResolver { protected static final Logger LOG = LoggerFactory.getLogger(EternalChainResolver.class); - protected static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS; protected final OperationsCodec codec; public ChainResolver(final OperationsCodec codec) { diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java index fd23dce9bf..650149bbb6 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java @@ -17,8 +17,10 @@ package org.ehcache.clustered.client.internal.store.operations; import org.ehcache.clustered.client.internal.store.operations.codecs.OperationsCodec; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.core.config.ExpiryUtils; +import org.ehcache.expiry.ExpiryPolicy; + +import java.time.Duration; import static java.util.Objects.requireNonNull; @@ -30,7 +32,7 @@ */ public class ExpiryChainResolver extends ChainResolver { - private final Expiry expiry; + private final ExpiryPolicy expiry; /** * Creates a resolver with the given codec and expiry policy. @@ -38,7 +40,7 @@ public class ExpiryChainResolver extends ChainResolver { * @param codec operation codec * @param expiry expiry policy */ - public ExpiryChainResolver(final OperationsCodec codec, Expiry expiry) { + public ExpiryChainResolver(final OperationsCodec codec, ExpiryPolicy expiry) { super(codec); this.expiry = requireNonNull(expiry, "Expiry cannot be null"); } @@ -93,12 +95,12 @@ private long calculateExpiryTime(K key, PutOperation existing, Operation cacheManagerBuilder(Expiry expiry) { + private CacheManagerBuilder cacheManagerBuilder(ExpiryPolicy expiry) { return newCacheManagerBuilder() .using(statisticsService) .using(new TimeSourceConfiguration(timeSource)) .with(cluster(CLUSTER_URI).autoCreate()) .withCache(CLUSTERED_CACHE, newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() - .heap(10) + .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB) .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 32, MemoryUnit.MB))) .withExpiry(expiry) .add(ClusteredStoreConfigurationBuilder.withConsistency(Consistency.STRONG))); } - private Expiry oneSecondExpiration() { - return Expirations.timeToLiveExpiration(Duration.of(1, TimeUnit.SECONDS)); + private ExpiryPolicy oneSecondExpiration() { + return ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1)); } @Before @@ -117,7 +117,7 @@ public void testGetExpirationPropagatedToHigherTiers() throws CachePersistenceEx @Test public void testGetNoExpirationPropagatedToHigherTiers() throws CachePersistenceException { - CacheManagerBuilder clusteredCacheManagerBuilder = cacheManagerBuilder(Expirations.noExpiration()); + CacheManagerBuilder clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicies.noExpiration()); try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) { diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParserTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParserTest.java index 72964e58ea..defb688ac8 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParserTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParserTest.java @@ -52,6 +52,7 @@ import javax.xml.transform.stream.StreamSource; import static java.time.temporal.ChronoUnit.MINUTES; +import static org.ehcache.xml.XmlModel.convertToJavaTemporalUnit; import static org.ehcache.xml.XmlModel.convertToJavaTimeUnit; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java index 9edde4a1e0..3c82a07808 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java @@ -49,7 +49,7 @@ import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.Eviction.noAdvice; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; -import static org.ehcache.expiry.Expirations.noExpiration; +import static org.ehcache.expiry.ExpiryPolicies.noExpiration; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java index 6975d20aa5..24c1b46934 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java @@ -49,7 +49,7 @@ import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.Eviction.noAdvice; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; -import static org.ehcache.expiry.Expirations.noExpiration; +import static org.ehcache.expiry.ExpiryPolicies.noExpiration; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java index 41125ca8c1..193046e7f6 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java @@ -30,8 +30,8 @@ import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.store.disk.OffHeapDiskStore; import org.ehcache.impl.internal.store.heap.OnHeapStore; import org.ehcache.impl.internal.store.offheap.OffHeapStore; @@ -168,8 +168,8 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { - return Expirations.noExpiration(); + public ExpiryPolicy getExpiry() { + return ExpiryPolicies.noExpiration(); } @Override diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java index cee4befaf5..82441274d0 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java @@ -35,7 +35,7 @@ import org.ehcache.core.spi.store.StoreAccessTimeoutException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.statistics.StoreOperationOutcomes; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.store.HashUtils; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java index ccf230c441..ad45fd8be6 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java @@ -23,17 +23,16 @@ import org.ehcache.clustered.client.internal.store.operations.codecs.OperationsCodec; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.clustered.common.internal.store.Element; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; +import java.time.Duration; import java.util.ArrayList; import java.util.List; -import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; @@ -63,10 +62,10 @@ public void initialSetup() { @Test @SuppressWarnings("unchecked") public void testGetExpiryForAccessIsIgnored() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(Duration.INFINITE); + when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "One", timeSource.getTimeMillis())); @@ -86,10 +85,10 @@ public void testGetExpiryForAccessIsIgnored() { @Test @SuppressWarnings("unchecked") public void testGetExpiryForCreationIsInvokedOnlyOnce() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(Duration.INFINITE); + when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "One", timeSource.getTimeMillis())); @@ -112,10 +111,10 @@ public void testGetExpiryForCreationIsInvokedOnlyOnce() { @Test @SuppressWarnings("unchecked") public void testGetExpiryForCreationIsNotInvokedForReplacedChains() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(Duration.INFINITE); + when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "Replaced", -10L)); @@ -136,10 +135,10 @@ public void testGetExpiryForCreationIsNotInvokedForReplacedChains() { @SuppressWarnings("unchecked") public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(Duration.INFINITE); + when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "Replaced", 10L)); @@ -161,7 +160,7 @@ public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { reset(expiry); - when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(Duration.INFINITE); + when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); list = new ArrayList<>(); list.add(new PutOperation<>(1L, "One", timeSource.getTimeMillis())); @@ -186,7 +185,7 @@ public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { @Test @SuppressWarnings("unchecked") public void testNullGetExpiryForCreation() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(null); @@ -205,7 +204,7 @@ public void testNullGetExpiryForCreation() { @Test @SuppressWarnings("unchecked") public void testNullGetExpiryForUpdate() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenReturn(null); @@ -226,10 +225,10 @@ public void testNullGetExpiryForUpdate() { @Test @SuppressWarnings("unchecked") public void testGetExpiryForUpdateUpdatesExpirationTimeStamp() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenReturn(new Duration(2L, TimeUnit.MILLISECONDS)); + when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenReturn(Duration.ofMillis(2L)); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "Replaced", -10L)); @@ -247,7 +246,7 @@ public void testGetExpiryForUpdateUpdatesExpirationTimeStamp() { @Test @SuppressWarnings("unchecked") public void testExpiryThrowsException() { - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenThrow(new RuntimeException("Test Update Expiry")); diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java index d47ea2b61e..d2edfb7792 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java @@ -21,8 +21,7 @@ import org.ehcache.clustered.client.internal.store.operations.codecs.OperationsCodec; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.clustered.common.internal.store.Element; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; import org.hamcrest.Description; @@ -31,9 +30,9 @@ import org.junit.Test; import java.nio.ByteBuffer; +import java.time.Duration; import java.util.concurrent.TimeUnit; -import static org.ehcache.expiry.Expirations.timeToIdleExpiration; import static org.hamcrest.Matchers.emptyIterable; import static org.hamcrest.Matchers.is; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; @@ -58,7 +57,7 @@ public void testResolveMaintainsOtherKeysInOrder() throws Exception { new PutOperation<>(2L, "Suresh", 0L), new PutOperation<>(2L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -75,7 +74,7 @@ public void testResolveMaintainsOtherKeysInOrder() throws Exception { @Test public void testResolveEmptyChain() throws Exception { Chain chain = getChainFromOperations(); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -90,7 +89,7 @@ public void testResolveChainWithNonExistentKey() throws Exception { new PutOperation<>(2L, "Suresh", 0L), new PutOperation<>(2L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 3L, 0L); Result result = resolvedChain.getResolvedResult(3L); assertNull(result); @@ -102,7 +101,7 @@ public void testResolveSinglePut() throws Exception { Operation expected = new PutOperation<>(1L, "Albin", 0L); Chain chain = getChainFromOperations(expected); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -118,7 +117,7 @@ public void testResolvePutsOnly() throws Exception { new PutOperation<>(1L, "Suresh", 0L), new PutOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -130,7 +129,7 @@ public void testResolvePutsOnly() throws Exception { public void testResolveSingleRemove() throws Exception { Chain chain = getChainFromOperations(new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -144,7 +143,7 @@ public void testResolveRemovesOnly() throws Exception { new RemoveOperation<>(1L, 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -158,7 +157,7 @@ public void testPutAndRemove() throws Exception { new PutOperation<>(1L, "Albin", 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -170,7 +169,7 @@ public void testResolvePutIfAbsentOnly() throws Exception { Operation expected = new PutOperation<>(1L, "Mathew", 0L); Chain chain = getChainFromOperations(new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -185,7 +184,7 @@ public void testResolvePutIfAbsentsOnly() throws Exception { new PutIfAbsentOperation<>(1L, "Suresh", 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -200,7 +199,7 @@ public void testResolvePutIfAbsentSucceeds() throws Exception { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -211,7 +210,7 @@ public void testResolvePutIfAbsentSucceeds() throws Exception { public void testResolveForSingleOperationDoesNotCompact() { Chain chain = getChainFromOperations(new PutOperation<>(1L, "Albin", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); assertThat(resolvedChain.isCompacted(), is(false)); assertThat(resolvedChain.getCompactionCount(), is(0)); @@ -233,7 +232,7 @@ public void testResolveForMultiplesOperationsAlwaysCompact() { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(2L, "Albin", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); assertThat(resolvedChain.isCompacted(), is(true)); assertThat(resolvedChain.getCompactionCount(), is(8)); @@ -247,7 +246,7 @@ public void testResolveForMultipleOperationHasCorrectIsFirstAndTimeStamp() { new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "AlbinAfterRemove", 3)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.timeToLiveExpiration(Duration.of(1, TimeUnit.HOURS))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.timeToLiveExpiration(Duration.ofHours(1))); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 3); Operation operation = codec.decode(resolvedChain.getCompactedChain().iterator().next().getPayload()); @@ -272,7 +271,7 @@ public void testResolveForMultipleOperationHasCorrectIsFirstAndTimeStampWithExpi new PutOperation<>(1L, "Albin4", 3L) ); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.timeToLiveExpiration(new Duration(1l, TimeUnit.MILLISECONDS))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1L))); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 3L); Operation operation = codec.decode(resolvedChain.getCompactedChain().iterator().next().getPayload()); @@ -299,7 +298,7 @@ public void testResolveDoesNotDecodeOtherKeyOperationValues() throws Exception { CountingLongSerializer keySerializer = new CountingLongSerializer(); CountingStringSerializer valueSerializer = new CountingStringSerializer(); OperationsCodec customCodec = new OperationsCodec<>(keySerializer, valueSerializer); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, timeToIdleExpiration(Duration.of(5, TimeUnit.SECONDS))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicies.timeToIdleExpiration(Duration.ofSeconds(5))); resolver.resolve(chain, 1L, 0L); assertThat(keySerializer.decodeCount, is(3)); @@ -318,7 +317,7 @@ public void testResolveDecodesOperationValueOnlyOnDemand() throws Exception { CountingLongSerializer keySerializer = new CountingLongSerializer(); CountingStringSerializer valueSerializer = new CountingStringSerializer(); OperationsCodec customCodec = new OperationsCodec<>(keySerializer, valueSerializer); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, timeToIdleExpiration(Duration.of(5, TimeUnit.SECONDS))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicies.timeToIdleExpiration(Duration.ofSeconds(5))); resolver.resolve(chain, 1L, 0L); assertThat(keySerializer.decodeCount, is(3)); @@ -337,7 +336,7 @@ public void testCompactingTwoKeys() throws Exception { new PutOperation<>(2L, "Suresh", 0L), new PutOperation<>(2L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); @@ -350,7 +349,7 @@ public void testCompactingTwoKeys() throws Exception { @Test public void testCompactEmptyChain() throws Exception { Chain chain = (new ChainBuilder()).build(); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compacted = resolver.applyOperation(chain, 0L); assertThat(compacted, emptyIterable()); } @@ -361,7 +360,7 @@ public void testCompactSinglePut() throws Exception { new PutOperation<>(1L, "Albin", 0L) ); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compacted = resolver.applyOperation(chain, 0L); assertThat(compacted, contains(operation(new PutOperation<>(1L, "Albin", 0L)))); @@ -374,7 +373,7 @@ public void testCompactMultiplePuts() throws Exception { new PutOperation<>(1L, "Suresh", 0L), new PutOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Mathew", 0L)))); } @@ -383,7 +382,7 @@ public void testCompactMultiplePuts() throws Exception { public void testCompactSingleRemove() throws Exception { Chain chain = getChainFromOperations(new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, emptyIterable()); } @@ -394,7 +393,7 @@ public void testCompactMultipleRemoves() throws Exception { new RemoveOperation<>(1L, 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, emptyIterable()); } @@ -405,7 +404,7 @@ public void testCompactPutAndRemove() throws Exception { new PutOperation<>(1L, "Albin", 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, emptyIterable()); } @@ -414,7 +413,7 @@ public void testCompactPutAndRemove() throws Exception { public void testCompactSinglePutIfAbsent() throws Exception { Chain chain = getChainFromOperations(new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Mathew", 0L)))); } @@ -426,7 +425,7 @@ public void testCompactMultiplePutIfAbsents() throws Exception { new PutIfAbsentOperation<>(1L, "Suresh", 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin", 0L)))); } @@ -438,7 +437,7 @@ public void testCompactPutIfAbsentAfterRemove() throws Exception { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Mathew", 0L)))); } @@ -459,7 +458,7 @@ public void testCompactForMultipleKeysAndOperations() { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(2L, "Albin", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(2L, "Albin", 0L)))); } @@ -472,7 +471,7 @@ public void testCompactHasCorrectTimeStamp() { new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin3", 3)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 3); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin3", 3)))); @@ -487,7 +486,7 @@ public void testCompactHasCorrectWithExpiry() { new PutOperation<>(1L, "Albin4", 3L) ); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, Expirations.timeToLiveExpiration(new Duration(1l, TimeUnit.MILLISECONDS))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1L))); Chain compactedChain = resolver.applyOperation(chain, 3L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin4", 3L)))); @@ -503,7 +502,7 @@ public void testCompactDecodesOperationValueOnlyOnDemand() throws Exception { CountingLongSerializer keySerializer = new CountingLongSerializer(); CountingStringSerializer valueSerializer = new CountingStringSerializer(); OperationsCodec customCodec = new OperationsCodec<>(keySerializer, valueSerializer); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, Expirations.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicies.noExpiration()); resolver.applyOperation(chain, 0L); assertThat(keySerializer.decodeCount, is(3)); diff --git a/clustered/integration-test/src/test/resources/clusteredConfiguration.txt b/clustered/integration-test/src/test/resources/clusteredConfiguration.txt index 9a601bca24..2d070ab3ff 100644 --- a/clustered/integration-test/src/test/resources/clusteredConfiguration.txt +++ b/clustered/integration-test/src/test/resources/clusteredConfiguration.txt @@ -4,7 +4,7 @@ caches: valueType: java.lang.String serviceConfigurations: None evictionAdvisor: None - expiry: NoExpiry + expiry: NoExpiryPolicy resourcePools: pools: heap: @@ -18,7 +18,7 @@ caches: valueType: java.lang.String serviceConfigurations: None evictionAdvisor: None - expiry: NoExpiry + expiry: NoExpiryPolicy resourcePools: pools: heap: diff --git a/clustered/integration-test/src/test/resources/simpleConfiguration.txt b/clustered/integration-test/src/test/resources/simpleConfiguration.txt index 09765c1a48..2767f10986 100644 --- a/clustered/integration-test/src/test/resources/simpleConfiguration.txt +++ b/clustered/integration-test/src/test/resources/simpleConfiguration.txt @@ -6,7 +6,7 @@ caches: - org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration - org.ehcache.impl.config.loaderwriter.writebehind.DefaultWriteBehindConfiguration evictionAdvisor: org.ehcache.clustered.management.EhcacheManagerToStringTest$1 - expiry: NoExpiry + expiry: NoExpiryPolicy resourcePools: pools: heap: diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java index 12de90867b..a01dc5eca8 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java @@ -17,16 +17,15 @@ import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; +import java.time.Duration; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -200,7 +199,7 @@ public void testException() throws Exception { @SPITest public void testComputeIfAbsentValuePresentExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); K key = factory.createKey(250928L); V value = factory.createValue(2059820L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java index 5b2fba1e72..1bd5dc40cc 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java @@ -17,8 +17,7 @@ import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; @@ -31,8 +30,8 @@ import static org.hamcrest.Matchers.nullValue; import org.junit.Assert; +import java.time.Duration; import java.util.function.BiFunction; -import java.util.function.Supplier; public class StoreComputeTest extends SPIStoreTester { @@ -194,7 +193,7 @@ public void testException() throws Exception { @SPITest public void testComputeExpiresOnAccess() throws Exception { TestTimeSource timeSource = new TestTimeSource(10042L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); final K key = factory.createKey(1042L); final V value = factory.createValue(1340142L); @@ -212,7 +211,7 @@ public void testComputeExpiresOnAccess() throws Exception { @SPITest public void testComputeExpiresOnUpdate() throws Exception { TestTimeSource timeSource = new TestTimeSource(10042L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setUpdate(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setUpdate(Duration.ZERO).build(), timeSource); final K key = factory.createKey(1042L); final V value = factory.createValue(1340142L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java index b2605a02df..82d9c5f0b2 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java @@ -22,17 +22,14 @@ import org.ehcache.event.EventType; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; import org.ehcache.spi.test.SPITest; import org.hamcrest.Matcher; -import java.util.concurrent.TimeUnit; -import java.util.function.BiFunction; -import java.util.function.Function; +import java.time.Duration; import static org.ehcache.internal.store.StoreCreationEventListenerTest.eventType; import static org.hamcrest.Matchers.*; @@ -62,7 +59,7 @@ public StoreExpiryEventListenerTest(StoreFactory factory) { @Before public void setUp() { timeSource = new TestTimeSource(); - kvStore = factory.newStoreWithExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS)), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1)), timeSource); } @After diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreFactory.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreFactory.java index 1cf75f0100..c2133a97ed 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreFactory.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreFactory.java @@ -17,8 +17,8 @@ package org.ehcache.internal.store; import org.ehcache.config.EvictionAdvisor; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.time.TimeSource; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceProvider; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.service.Service; @@ -35,7 +35,7 @@ public interface StoreFactory { Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor); - Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource); + Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource); Store.ValueHolder newValueHolder(V value); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java index 198cb048a6..6067cff545 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java @@ -16,18 +16,17 @@ package org.ehcache.internal.store; -import org.ehcache.ValueSupplier; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; +import java.time.Duration; + import static org.ehcache.core.spi.store.Store.ValueHolder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -154,7 +153,7 @@ public void wrongKeyTypeThrowsException() @SPITest public void testGetExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); K key = factory.createKey(250928L); V value = factory.createValue(2059820L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java index 6e2e4a5b36..be87f0ea90 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java @@ -16,17 +16,16 @@ package org.ehcache.internal.store; -import org.ehcache.ValueSupplier; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; +import java.time.Duration; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -180,7 +179,7 @@ public void wrongValueTypeThrowsException() @SPITest public void testPutIfAbsentValuePresentExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); K key = factory.createKey(250928L); V value = factory.createValue(2059820L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java index 9bb6977197..f6ba11a498 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java @@ -16,17 +16,16 @@ package org.ehcache.internal.store; -import org.ehcache.ValueSupplier; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; +import java.time.Duration; + import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -183,7 +182,7 @@ public void indicatesValueReplaced() throws LegalSPITesterException { public void indicatesValueReplacedWhenUpdateExpires() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(1000L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setUpdate(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setUpdate(Duration.ZERO).build(), timeSource); K key = factory.createKey(42L); V value = factory.createValue(42L); @@ -204,7 +203,7 @@ public void indicatesValueReplacedWhenUpdateExpires() throws LegalSPITesterExcep public void indicatesOperationNoOp() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(1000L); - kvStore = factory.newStoreWithExpiry(Expirations.builder().setCreate(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setCreate(Duration.ZERO).build(), timeSource); K key = factory.createKey(42L); try { diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFactory.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFactory.java index a79da797bc..dd55ba2413 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFactory.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFactory.java @@ -17,8 +17,8 @@ package org.ehcache.internal.tier; import org.ehcache.config.EvictionAdvisor; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.time.TimeSource; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.internal.store.StoreFactory; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; @@ -34,7 +34,7 @@ public interface AuthoritativeTierFactory extends StoreFactory { AuthoritativeTier newStoreWithCapacity(long capacity); @Override - AuthoritativeTier newStoreWithExpiry(Expiry expiry, TimeSource timeSource); + AuthoritativeTier newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource); @Override AuthoritativeTier newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java index 0f19d97245..d0e5d9b92b 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java @@ -17,17 +17,15 @@ package org.ehcache.internal.tier; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.internal.TestTimeSource; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.spi.test.After; -import org.ehcache.spi.test.Before; import org.ehcache.spi.test.Ignore; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; -import java.util.concurrent.TimeUnit; +import java.time.Duration; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; @@ -103,7 +101,7 @@ public void marksTheMappingAsNotEvictableAndReturnsValue() throws LegalSPITester @Ignore public void marksTheMappingAsNotExpirable() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(); - tier = factory.newStoreWithExpiry(Expirations.timeToIdleExpiration(new Duration(1, TimeUnit.MILLISECONDS)), timeSource); + tier = factory.newStoreWithExpiry(ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(1)), timeSource); K key = factory.createKey(1); V value = factory.createValue(1); diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index 8e73c9cb40..c59583e01f 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -16,6 +16,7 @@ package org.ehcache.core; +import java.time.Duration; import java.util.AbstractMap; import java.util.ArrayList; import java.util.Collection; @@ -61,8 +62,7 @@ import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveAllOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -216,7 +216,7 @@ public void put(final K key, final V value) { } private boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { - return newValueAlreadyExpired(logger, runtimeConfiguration.getExpiry(), key, oldValue, newValue); + return newValueAlreadyExpired(logger, runtimeConfiguration.getExpiryPolicy(), key, oldValue, newValue); } /** @@ -369,7 +369,7 @@ public void putAll(final Map entries) throws BulkCache } try { - PutAllFunction putAllFunction = new PutAllFunction<>(logger, entriesToRemap, runtimeConfiguration.getExpiry()); + PutAllFunction putAllFunction = new PutAllFunction<>(logger, entriesToRemap, runtimeConfiguration.getExpiryPolicy()); store.bulkCompute(entries.keySet(), putAllFunction); addBulkMethodEntriesCount(BulkOps.PUT_ALL, putAllFunction.getActualPutCount().get()); addBulkMethodEntriesCount(BulkOps.UPDATE_ALL, putAllFunction.getActualUpdateCount().get()); @@ -910,7 +910,7 @@ public void obliterate(Iterable keys) throws StoreAccessException { }; } - private static boolean newValueAlreadyExpired(Logger logger, Expiry expiry, K key, V oldValue, V newValue) { + private static boolean newValueAlreadyExpired(Logger logger, ExpiryPolicy expiry, K key, V oldValue, V newValue) { if (newValue == null) { return false; } @@ -927,7 +927,11 @@ private static boolean newValueAlreadyExpired(Logger logger, Expiry implements Cache.Entry { @@ -955,11 +959,11 @@ public static class PutAllFunction implements Function entriesToRemap; - private final Expiry expiry; + private final ExpiryPolicy expiry; private final AtomicInteger actualPutCount = new AtomicInteger(); private final AtomicInteger actualUpdateCount = new AtomicInteger(); - public PutAllFunction(Logger logger, Map entriesToRemap, Expiry expiry) { + public PutAllFunction(Logger logger, Map entriesToRemap, ExpiryPolicy expiry) { this.logger = logger; this.entriesToRemap = entriesToRemap; this.expiry = expiry; diff --git a/core/src/main/java/org/ehcache/core/EhcacheManager.java b/core/src/main/java/org/ehcache/core/EhcacheManager.java index 8288a34bf3..63b4522a88 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheManager.java +++ b/core/src/main/java/org/ehcache/core/EhcacheManager.java @@ -528,7 +528,7 @@ private CacheConfiguration adjustConfigurationWithCacheManagerDefau } if (cacheClassLoader != config.getClassLoader() ) { config = new BaseCacheConfiguration<>(config.getKeyType(), config.getValueType(), - config.getEvictionAdvisor(), cacheClassLoader, config.getExpiry(), + config.getEvictionAdvisor(), cacheClassLoader, config.getExpiryPolicy(), config.getResourcePools(), config.getServiceConfigurations().toArray( new ServiceConfiguration[config.getServiceConfigurations().size()])); } diff --git a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java index a2af56fbdd..88c7b39ac1 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java +++ b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java @@ -20,12 +20,14 @@ import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.internal.events.EventListenerWrapper; import org.ehcache.event.CacheEventListener; import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.event.EventType; import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; import java.util.ArrayList; @@ -44,7 +46,7 @@ class EhcacheRuntimeConfiguration implements CacheRuntimeConfiguration valueType; private final EvictionAdvisor evictionAdvisor; private final ClassLoader classLoader; - private final Expiry expiry; + private final ExpiryPolicy expiry; private volatile ResourcePools resourcePools; private final List cacheConfigurationListenerList @@ -57,7 +59,7 @@ class EhcacheRuntimeConfiguration implements CacheRuntimeConfiguration getExpiry() { + return ExpiryUtils.convertToExpiry(expiry); + } + + @Override + public ExpiryPolicy getExpiryPolicy() { return expiry; } diff --git a/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java b/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java index 09e775b3b0..894fbdadda 100644 --- a/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java +++ b/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java @@ -23,8 +23,9 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; -import org.ehcache.expiry.Expirations; import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; /** @@ -37,7 +38,7 @@ public class BaseCacheConfiguration implements CacheConfiguration { private final EvictionAdvisor evictionAdvisor; private final Collection> serviceConfigurations; private final ClassLoader classLoader; - private final Expiry expiry; + private final ExpiryPolicy expiry; private final ResourcePools resourcePools; /** @@ -53,7 +54,7 @@ public class BaseCacheConfiguration implements CacheConfiguration { */ public BaseCacheConfiguration(Class keyType, Class valueType, EvictionAdvisor evictionAdvisor, - ClassLoader classLoader, Expiry expiry, + ClassLoader classLoader, ExpiryPolicy expiry, ResourcePools resourcePools, ServiceConfiguration... serviceConfigurations) { if (keyType == null) { throw new NullPointerException("keyType cannot be null"); @@ -71,7 +72,7 @@ public BaseCacheConfiguration(Class keyType, Class valueType, if (expiry != null) { this.expiry = expiry; } else { - this.expiry = Expirations.noExpiration(); + this.expiry = ExpiryPolicies.noExpiration(); } this.resourcePools = resourcePools; this.serviceConfigurations = Collections.unmodifiableCollection(Arrays.asList(serviceConfigurations)); @@ -122,6 +123,14 @@ public ClassLoader getClassLoader() { */ @Override public Expiry getExpiry() { + return ExpiryUtils.convertToExpiry(expiry); + } + + /** + * {@inheritDoc} + */ + @Override + public ExpiryPolicy getExpiryPolicy() { return expiry; } diff --git a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java new file mode 100644 index 0000000000..fb7b85aa64 --- /dev/null +++ b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java @@ -0,0 +1,161 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.config; + +import org.ehcache.ValueSupplier; +import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; + +import java.time.Duration; +import java.time.temporal.ChronoUnit; +import java.time.temporal.TemporalUnit; +import java.util.concurrent.TimeUnit; + +/** + * ExpiryUtils + */ +public class ExpiryUtils { + + public static Expiry convertToExpiry(ExpiryPolicy expiryPolicy) { + + return new Expiry() { + + @Override + public org.ehcache.expiry.Duration getExpiryForCreation(K key, V value) { + return convertDuration(expiryPolicy.getExpiryForCreation(key, value)); + } + + @Override + public org.ehcache.expiry.Duration getExpiryForAccess(K key, ValueSupplier value) { + return convertDuration(expiryPolicy.getExpiryForAccess(key, value)); + } + + @Override + public org.ehcache.expiry.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + return convertDuration(expiryPolicy.getExpiryForUpdate(key, oldValue, newValue)); + } + + @Override + public String toString() { + return "Expiry wrapper of {" + expiryPolicy + " }"; + } + }; + } + + private static org.ehcache.expiry.Duration convertDuration(Duration duration) { + if (duration == null) { + return null; + } + if (duration.isNegative()) { + throw new IllegalArgumentException("Ehcache duration cannot be negative and so does not accept negative java.time.Duration: " + duration); + } + if (duration.isZero()) { + return org.ehcache.expiry.Duration.ZERO; + } else { + long nanos = duration.getNano(); + if (nanos == 0) { + return org.ehcache.expiry.Duration.of(duration.getSeconds(), TimeUnit.SECONDS); + } + long seconds = duration.getSeconds(); + long secondsInNanos = TimeUnit.SECONDS.toNanos(seconds); + if (secondsInNanos != Long.MAX_VALUE && Long.MAX_VALUE - secondsInNanos > nanos) { + return org.ehcache.expiry.Duration.of(duration.toNanos(), TimeUnit.NANOSECONDS); + } else { + long secondsInMicros = TimeUnit.SECONDS.toMicros(seconds); + if (secondsInMicros != Long.MAX_VALUE && Long.MAX_VALUE - secondsInMicros > nanos / 1_000) { + return org.ehcache.expiry.Duration.of(secondsInMicros + nanos / 1_000, TimeUnit.MICROSECONDS); + } else { + long secondsInMillis = TimeUnit.SECONDS.toMillis(seconds); + if (secondsInMillis != Long.MAX_VALUE && Long.MAX_VALUE - secondsInMillis > nanos / 1_000_000) { + return org.ehcache.expiry.Duration.of(duration.toMillis(), TimeUnit.MILLISECONDS); + } + } + } + return org.ehcache.expiry.Duration.of(seconds, TimeUnit.SECONDS); + } + } + + public static ExpiryPolicy convertToExpiryPolicy(Expiry expiry) { + return new ExpiryPolicy() { + @Override + public Duration getExpiryForCreation(K key, V value) { + org.ehcache.expiry.Duration duration = expiry.getExpiryForCreation(key, value); + return convertDuration(duration); + } + + @Override + public Duration getExpiryForAccess(K key, ValueSupplier value) { + org.ehcache.expiry.Duration duration = expiry.getExpiryForAccess(key, value); + return convertDuration(duration); + } + + @Override + public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + org.ehcache.expiry.Duration duration = expiry.getExpiryForUpdate(key, oldValue, newValue); + return convertDuration(duration); + } + + @Override + public String toString() { + return "Expiry wrapper of {" + expiry + " }"; + } + + private Duration convertDuration(org.ehcache.expiry.Duration duration) { + if (duration == null) { + return null; + } + if (duration.isInfinite()) { + return ExpiryPolicy.INFINITE; + } + try { + return Duration.of(duration.getLength(), jucTimeUnitToTemporalUnit(duration.getTimeUnit())); + } catch (ArithmeticException e) { + return ExpiryPolicy.INFINITE; + } + } + }; + } + + public static TemporalUnit jucTimeUnitToTemporalUnit(TimeUnit timeUnit) { + switch (timeUnit) { + case NANOSECONDS: + return ChronoUnit.NANOS; + case MICROSECONDS: + return ChronoUnit.MICROS; + case MILLISECONDS: + return ChronoUnit.MILLIS; + case SECONDS: + return ChronoUnit.SECONDS; + case MINUTES: + return ChronoUnit.MINUTES; + case HOURS: + return ChronoUnit.HOURS; + case DAYS: + return ChronoUnit.DAYS; + default: + throw new AssertionError("Unkown TimeUnit: " + timeUnit); + } + } + + public static long getExpirationMillis(long now, Duration duration) { + try { + return duration.plusMillis(now).toMillis(); + } catch (ArithmeticException e) { + return Long.MAX_VALUE; + } + } +} diff --git a/core/src/main/java/org/ehcache/core/internal/store/StoreConfigurationImpl.java b/core/src/main/java/org/ehcache/core/internal/store/StoreConfigurationImpl.java index a9265f23c6..819763dc55 100644 --- a/core/src/main/java/org/ehcache/core/internal/store/StoreConfigurationImpl.java +++ b/core/src/main/java/org/ehcache/core/internal/store/StoreConfigurationImpl.java @@ -19,8 +19,8 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.store.Store; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.serialization.Serializer; /** @@ -33,7 +33,7 @@ public class StoreConfigurationImpl implements Store.Configuration { private final Class valueType; private final EvictionAdvisor evictionAdvisor; private final ClassLoader classLoader; - private final Expiry expiry; + private final ExpiryPolicy expiry; private final ResourcePools resourcePools; private final Serializer keySerializer; private final Serializer valueSerializer; @@ -50,7 +50,7 @@ public class StoreConfigurationImpl implements Store.Configuration { public StoreConfigurationImpl(CacheConfiguration cacheConfig, int dispatcherConcurrency, Serializer keySerializer, Serializer valueSerializer) { this(cacheConfig.getKeyType(), cacheConfig.getValueType(), cacheConfig.getEvictionAdvisor(), - cacheConfig.getClassLoader(), cacheConfig.getExpiry(), cacheConfig.getResourcePools(), + cacheConfig.getClassLoader(), cacheConfig.getExpiryPolicy(), cacheConfig.getResourcePools(), dispatcherConcurrency, keySerializer, valueSerializer); } @@ -69,7 +69,7 @@ public StoreConfigurationImpl(CacheConfiguration cacheConfig, int dispatch */ public StoreConfigurationImpl(Class keyType, Class valueType, EvictionAdvisor evictionAdvisor, - ClassLoader classLoader, Expiry expiry, + ClassLoader classLoader, ExpiryPolicy expiry, ResourcePools resourcePools, int dispatcherConcurrency, Serializer keySerializer, Serializer valueSerializer) { this.keyType = keyType; @@ -119,7 +119,7 @@ public ClassLoader getClassLoader() { * {@inheritDoc} */ @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } diff --git a/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java b/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java index b4ec5080ff..1ea7cff683 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java +++ b/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java @@ -16,8 +16,9 @@ package org.ehcache.core.spi.store; -import org.ehcache.expiry.Duration; +import org.ehcache.core.config.ExpiryUtils; +import java.time.Duration; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLongFieldUpdater; @@ -81,19 +82,10 @@ private void updateExpirationTime(long update) { public void accessed(long now, Duration expiration) { final TimeUnit timeUnit = nativeTimeUnit(); if (expiration != null) { - if (expiration.isInfinite()) { + if (expiration.getSeconds() == Long.MAX_VALUE) { setExpirationTime(Store.ValueHolder.NO_EXPIRE, null); } else { - long millis = timeUnit.convert(expiration.getLength(), expiration.getTimeUnit()); - long newExpirationTime ; - if (millis == Long.MAX_VALUE) { - newExpirationTime = Long.MAX_VALUE; - } else { - newExpirationTime = now + millis; - if (newExpirationTime < 0) { - newExpirationTime = Long.MAX_VALUE; - } - } + long newExpirationTime = ExpiryUtils.getExpirationMillis(now, expiration); setExpirationTime(newExpirationTime, timeUnit); } } diff --git a/core/src/main/java/org/ehcache/core/spi/store/Store.java b/core/src/main/java/org/ehcache/core/spi/store/Store.java index a9dcc41d16..7b6b123ab7 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/Store.java +++ b/core/src/main/java/org/ehcache/core/spi/store/Store.java @@ -21,8 +21,8 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.store.events.StoreEventSource; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.serialization.Serializer; import org.ehcache.spi.service.PluralService; import org.ehcache.spi.service.Service; @@ -608,7 +608,7 @@ interface Configuration { /** * The expiration policy instance for this store */ - Expiry getExpiry(); + ExpiryPolicy getExpiry(); /** * The resource pools this store can make use of diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java index 6923013bc8..2cafbc8b63 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java @@ -24,7 +24,7 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.hamcrest.Matchers; import org.junit.Test; import org.slf4j.LoggerFactory; @@ -175,7 +175,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessException() throws Exception */ private Ehcache getEhcache() { CacheConfiguration config = new BaseCacheConfiguration<>(String.class, String.class, null, null, - Expirations.noExpiration(), ResourcePoolsHelper.createHeapOnlyPools()); + ExpiryPolicies.noExpiration(), ResourcePoolsHelper.createHeapOnlyPools()); final Ehcache ehcache = new Ehcache<>(config, this.store, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBasicPutIfAbsentTest")); ehcache.init(); assertThat("cache not initialized", ehcache.getStatus(), Matchers.is(Status.AVAILABLE)); diff --git a/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java b/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java index e26db61190..df879ecbeb 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java @@ -18,9 +18,9 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.core.events.CacheEventDispatcher; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; +import org.ehcache.expiry.ExpiryPolicy; import org.junit.Test; import org.slf4j.LoggerFactory; @@ -101,7 +101,7 @@ public void testRemoveAll() throws Exception { protected InternalCache getCache(Store store) { CacheConfiguration cacheConfig = mock(CacheConfiguration.class); - when(cacheConfig.getExpiry()).thenReturn(mock(Expiry.class)); + when(cacheConfig.getExpiryPolicy()).thenReturn(mock(ExpiryPolicy.class)); CacheEventDispatcher cacheEventDispatcher = mock(CacheEventDispatcher.class); return new Ehcache<>(cacheConfig, store, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBulkMethodsTest")); } diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java index 4d45741a26..3a522f3450 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java @@ -15,6 +15,7 @@ */ package org.ehcache.core; +import java.time.Duration; import java.util.Collections; import java.util.EnumSet; import java.util.LinkedHashSet; @@ -28,10 +29,9 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.BulkOps; import org.ehcache.core.statistics.CacheOperationOutcomes; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.Matchers; import org.junit.Test; @@ -1870,7 +1870,7 @@ public void testPutAllPartialIntersectionsImmediatelyExpiredCreatedEntries() thr this.cacheLoaderWriter = spy(fakeLoaderWriter); @SuppressWarnings("unchecked") - final Expiry expiry = mock(Expiry.class); + final ExpiryPolicy expiry = mock(ExpiryPolicy.class); when(expiry.getExpiryForCreation(any(String.class), any(String.class))).thenReturn(Duration.ZERO); final EhcacheWithLoaderWriter ehcache = this.getEhcache(cacheLoaderWriter, expiry); @@ -1901,7 +1901,7 @@ public void testPutAllPartialIntersectionsImmediatelyExpiredUpdatedEntries() thr this.cacheLoaderWriter = spy(fakeLoaderWriter); @SuppressWarnings("unchecked") - final Expiry expiry = mock(Expiry.class); + final ExpiryPolicy expiry = mock(ExpiryPolicy.class); when(expiry.getExpiryForUpdate(any(String.class), argThat(org.ehcache.core.util.Matchers.holding(instanceOf(String.class))), any(String.class))).thenReturn(Duration.ZERO); final EhcacheWithLoaderWriter ehcache = this.getEhcache(cacheLoaderWriter, expiry); @@ -1930,7 +1930,7 @@ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWrit return getEhcache(cacheLoaderWriter, CACHE_CONFIGURATION); } - private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, Expiry expiry) { + private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { CacheConfiguration config = new BaseCacheConfiguration<>(String.class, String.class, null, null, expiry, ResourcePoolsHelper.createHeapOnlyPools()); return getEhcache(cacheLoaderWriter, config); diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java index 0ffdb1ad18..297d87f315 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java @@ -23,9 +23,9 @@ import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.Matchers; import org.junit.Test; @@ -476,10 +476,10 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionCacheLoaderWriterExc * @return a new {@code Ehcache} instance */ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter) { - return getEhcache(cacheLoaderWriter, Expirations.noExpiration()); + return getEhcache(cacheLoaderWriter, ExpiryPolicies.noExpiration()); } - private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, Expiry expiry) { + private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { CacheConfiguration config = new BaseCacheConfiguration<>(String.class, String.class, null, null, expiry, ResourcePoolsHelper.createHeapOnlyPools()); final EhcacheWithLoaderWriter ehcache = new EhcacheWithLoaderWriter<>(config, this.store, cacheLoaderWriter, cacheEventDispatcher, LoggerFactory diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java index e1f349a283..17ffdaf9fe 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java @@ -22,10 +22,9 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.CoreMatchers; import org.junit.Test; @@ -33,6 +32,7 @@ import org.mockito.Mock; import org.slf4j.LoggerFactory; +import java.time.Duration; import java.util.Collections; import java.util.EnumSet; @@ -521,7 +521,7 @@ public void testReplaceWithImmediatelyExpiredEntry() throws Exception { final FakeCacheLoaderWriter fakeWriter = new FakeCacheLoaderWriter(Collections.singletonMap("key", "old-value")); @SuppressWarnings("unchecked") - final Expiry expiry = mock(Expiry.class); + final ExpiryPolicy expiry = mock(ExpiryPolicy.class); when(expiry.getExpiryForUpdate(eq("key"), argThat(holding("old-value")), eq("value"))).thenReturn(Duration.ZERO); final EhcacheWithLoaderWriter ehcache = this.getEhcache(fakeWriter, expiry); @@ -543,10 +543,10 @@ public void testReplaceWithImmediatelyExpiredEntry() throws Exception { * @return a new {@code EhcacheWithLoaderWriter} instance */ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter) { - return getEhcache(cacheLoaderWriter, Expirations.noExpiration()); + return getEhcache(cacheLoaderWriter, ExpiryPolicies.noExpiration()); } - private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, Expiry expiry) { + private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { CacheConfiguration config = new BaseCacheConfiguration<>(String.class, String.class, null, null, expiry, ResourcePoolsHelper.createHeapOnlyPools()); final EhcacheWithLoaderWriter ehcache diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java index 57b10a8bfb..5e59491ab2 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java @@ -22,16 +22,16 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.mockito.Mock; import org.slf4j.LoggerFactory; +import java.time.Duration; import java.util.Collections; import java.util.EnumSet; @@ -896,7 +896,7 @@ public void testReplaceWithImmediatelyExpiredEntry() throws Exception { final FakeCacheLoaderWriter fakeWriter = new FakeCacheLoaderWriter(Collections.singletonMap("key", "old-value")); @SuppressWarnings("unchecked") - final Expiry expiry = mock(Expiry.class); + final ExpiryPolicy expiry = mock(ExpiryPolicy.class); when(expiry.getExpiryForUpdate(eq("key"), argThat(holding("old-value")), eq("value"))).thenReturn(Duration.ZERO); final EhcacheWithLoaderWriter ehcache = this.getEhcache(fakeWriter, expiry); @@ -919,10 +919,10 @@ public void testReplaceWithImmediatelyExpiredEntry() throws Exception { * @return a new {@code EhcacheWithLoaderWriter} instance */ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter) { - return getEhcache(cacheLoaderWriter, Expirations.noExpiration()); + return getEhcache(cacheLoaderWriter, ExpiryPolicies.noExpiration()); } - private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, Expiry expiry) { + private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { CacheConfiguration config = new BaseCacheConfiguration<>(String.class, String.class, null, null, expiry, ResourcePoolsHelper.createHeapOnlyPools()); final EhcacheWithLoaderWriter ehcache = new EhcacheWithLoaderWriter<>(config, this.store, cacheLoaderWriter, cacheEventDispatcher, LoggerFactory diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBulkMethodsTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBulkMethodsTest.java index 433df5006f..24fc0cb5dd 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBulkMethodsTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBulkMethodsTest.java @@ -22,11 +22,9 @@ import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.slf4j.LoggerFactory; import static org.hamcrest.Matchers.hasEntry; @@ -119,7 +117,7 @@ public void testRemoveAllWithWriter() throws Exception { protected InternalCache getCache(Store store, CacheLoaderWriter cacheLoaderWriter) { CacheConfiguration cacheConfig = mock(CacheConfiguration.class); - when(cacheConfig.getExpiry()).thenReturn(mock(Expiry.class)); + when(cacheConfig.getExpiryPolicy()).thenReturn(mock(ExpiryPolicy.class)); CacheEventDispatcher cacheEventDispatcher = mock(CacheEventDispatcher.class); return new EhcacheWithLoaderWriter(cacheConfig, store, cacheLoaderWriter, cacheEventDispatcher, LoggerFactory.getLogger(EhcacheWithLoaderWriter.class + "-" + "EhcacheWithLoaderWriterBulkMethodsTest")); } diff --git a/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java b/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java index 0722c96d9a..964f50b379 100644 --- a/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java +++ b/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java @@ -16,10 +16,10 @@ package org.ehcache.core.spi.store; -import org.ehcache.expiry.Duration; import org.ehcache.core.spi.time.TimeSource; import org.junit.Test; +import java.time.Duration; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; @@ -219,7 +219,7 @@ public String value() { return "abc"; } }; - valueHolder.accessed((timeSource.getTimeMillis()), new Duration(1L, TimeUnit.MILLISECONDS)); + valueHolder.accessed((timeSource.getTimeMillis()), Duration.ofMillis(1L)); timeSource.advanceTime(1000); assertThat(valueHolder.hitRate(timeSource.getTimeMillis(), TimeUnit.SECONDS), is(1.0f)); diff --git a/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java b/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java index 2a73b359d4..8cc7a15137 100644 --- a/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java @@ -22,9 +22,11 @@ import org.ehcache.config.ResourcePools; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.BaseCacheConfiguration; +import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.config.store.StoreEventSourceConfiguration; import org.ehcache.core.spi.store.heap.SizeOfEngine; import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.event.DefaultCacheEventDispatcherConfiguration; import org.ehcache.impl.config.event.DefaultCacheEventListenerConfiguration; @@ -59,7 +61,7 @@ public class CacheConfigurationBuilder implements Builder> { private final Collection> serviceConfigurations = new HashSet<>(); - private Expiry expiry; + private ExpiryPolicy expiry; private ClassLoader classLoader = null; private EvictionAdvisor evictionAdvisor; private ResourcePools resourcePools; @@ -108,7 +110,7 @@ public static CacheConfigurationBuilder newCacheConfigurationBuilde CacheConfigurationBuilder builder = newCacheConfigurationBuilder(configuration.getKeyType(), configuration.getValueType(), configuration.getResourcePools()) .withClassLoader(configuration.getClassLoader()) .withEvictionAdvisor(configuration.getEvictionAdvisor()) - .withExpiry(configuration.getExpiry()); + .withExpiry(configuration.getExpiryPolicy()); for (ServiceConfiguration serviceConfig : configuration.getServiceConfigurations()) { builder = builder.add(serviceConfig); } @@ -284,12 +286,32 @@ public CacheConfigurationBuilder withResourcePools(ResourcePoolsBuilder re /** * Adds {@link Expiry} configuration to the returned builder. *

- * {@link Expiry} is what controls data freshness in a cache. + * {@code Expiry} is what controls data freshness in a cache. * * @param expiry the expiry to use * @return a new builder with the added expiry + * + * @deprecated Use {@link #withExpiry(ExpiryPolicy)} instead */ + @Deprecated public CacheConfigurationBuilder withExpiry(Expiry expiry) { + if (expiry == null) { + throw new NullPointerException("Null expiry"); + } + CacheConfigurationBuilder otherBuilder = new CacheConfigurationBuilder<>(this); + otherBuilder.expiry = ExpiryUtils.convertToExpiryPolicy(expiry); + return otherBuilder; + } + + /** + * Adds {@link ExpiryPolicy} configuration to the returned builder. + *

+ * {@code ExpiryPolicy} is what controls data freshness in a cache. + * + * @param expiry the expiry to use + * @return a new builder with the added expiry + */ + public CacheConfigurationBuilder withExpiry(ExpiryPolicy expiry) { if (expiry == null) { throw new NullPointerException("Null expiry"); } diff --git a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java index 9f5c311a3e..62067fa058 100644 --- a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java @@ -31,6 +31,7 @@ import org.ehcache.core.InternalCache; import org.ehcache.core.PersistentUserManagedEhcache; import org.ehcache.core.config.BaseCacheConfiguration; +import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.events.CacheEventListenerConfiguration; import org.ehcache.core.events.CacheEventListenerProvider; @@ -45,8 +46,9 @@ import org.ehcache.core.spi.store.heap.SizeOfEngine; import org.ehcache.core.spi.store.heap.SizeOfEngineProvider; import org.ehcache.event.CacheEventListener; -import org.ehcache.expiry.Expirations; import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.serializer.DefaultSerializerConfiguration; import org.ehcache.impl.config.store.heap.DefaultSizeOfEngineProviderConfiguration; @@ -108,7 +110,7 @@ public class UserManagedCacheBuilder> imp private String id; private final Set services = new HashSet<>(); private final Set> serviceCreationConfigurations = new HashSet<>(); - private Expiry expiry = Expirations.noExpiration(); + private ExpiryPolicy expiry = ExpiryPolicies.noExpiration(); private ClassLoader classLoader = ClassLoading.getDefaultClassLoader(); private EvictionAdvisor evictionAdvisor; private CacheLoaderWriter cacheLoaderWriter; @@ -449,8 +451,26 @@ public final UserManagedCacheBuilder withClassLoader(ClassLoader classL * * @param expiry the expiry to use * @return a new builer with the added expiry + * + * @deprecated Use {@link #withExpiry(ExpiryPolicy)} instead */ + @Deprecated public final UserManagedCacheBuilder withExpiry(Expiry expiry) { + if (expiry == null) { + throw new NullPointerException("Null expiry"); + } + UserManagedCacheBuilder otherBuilder = new UserManagedCacheBuilder<>(this); + otherBuilder.expiry = ExpiryUtils.convertToExpiryPolicy(expiry); + return otherBuilder; + } + + /** + * Adds {@link ExpiryPolicy} configuration to the returned builder. + * + * @param expiry the expiry to use + * @return a new builer with the added expiry + */ + public final UserManagedCacheBuilder withExpiry(ExpiryPolicy expiry) { if (expiry == null) { throw new NullPointerException("Null expiry"); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index 479c5b1756..936743d858 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -25,12 +25,12 @@ import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; import org.ehcache.config.units.MemoryUnit; +import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.heap.LimitExceededException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.SerializingCopier; @@ -72,6 +72,7 @@ import org.terracotta.statistics.StatisticsManager; import org.terracotta.statistics.observer.OperationObserver; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -84,7 +85,6 @@ import java.util.Map.Entry; import java.util.Random; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -152,7 +152,7 @@ public class OnHeapStore implements Store, HigherCachingTier { private volatile long capacity; private final EvictionAdvisor evictionAdvisor; - private final Expiry expiry; + private final ExpiryPolicy expiry; private final TimeSource timeSource; private final StoreEventDispatcher storeEventDispatcher; @SuppressWarnings("unchecked") @@ -1273,6 +1273,9 @@ private OnHeapValueHolder setAccessTimeAndExpiryThenReturnMappingOutsideLock( Duration duration; try { duration = expiry.getExpiryForAccess(key, valueHolder); + if (duration != null && duration.isNegative()) { + duration = Duration.ZERO; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); duration = Duration.ZERO; @@ -1291,6 +1294,9 @@ private OnHeapValueHolder setAccessTimeAndExpiryThenReturnMappingUnderLock(K Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForAccess(key, valueHolder); + if (duration != null && duration.isNegative()) { + duration = Duration.ZERO; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } @@ -1333,6 +1339,9 @@ private OnHeapValueHolder newUpdateValueHolder(K key, OnHeapValueHolder ol Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForUpdate(key, oldValue, newValue); + if (duration != null && duration.isNegative()) { + duration = Duration.ZERO; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } @@ -1346,10 +1355,10 @@ private OnHeapValueHolder newUpdateValueHolder(K key, OnHeapValueHolder ol if (duration == null) { expirationTime = oldValue.expirationTime(OnHeapValueHolder.TIME_UNIT); } else { - if (duration.isInfinite()) { + if (duration.getSeconds() == Long.MAX_VALUE) { expirationTime = ValueHolder.NO_EXPIRE; } else { - expirationTime = safeExpireTime(now, duration); + expirationTime = ExpiryUtils.getExpirationMillis(now, duration); } } @@ -1372,6 +1381,9 @@ private OnHeapValueHolder newCreateValueHolder(K key, V value, long now, Stor Duration duration; try { duration = expiry.getExpiryForCreation(key, value); + if (duration.isNegative()) { + return null; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return null; @@ -1380,7 +1392,7 @@ private OnHeapValueHolder newCreateValueHolder(K key, V value, long now, Stor return null; } - long expirationTime = duration.isInfinite() ? ValueHolder.NO_EXPIRE : safeExpireTime(now, duration); + long expirationTime = duration.getSeconds() == Long.MAX_VALUE ? ValueHolder.NO_EXPIRE : ExpiryUtils.getExpirationMillis(now, duration); OnHeapValueHolder holder = null; try { @@ -1396,6 +1408,9 @@ private OnHeapValueHolder importValueFromLowerTier(K key, ValueHolder valu Duration expiration = Duration.ZERO; try { expiration = expiry.getExpiryForAccess(key, valueHolder); + if (expiration != null && expiration.isNegative()) { + expiration = Duration.ZERO; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } @@ -1466,20 +1481,6 @@ private boolean checkEvictionAdvice(K key, V value) { } } - private static long safeExpireTime(long now, Duration duration) { - long millis = OnHeapValueHolder.TIME_UNIT.convert(duration.getLength(), duration.getTimeUnit()); - - if (millis == Long.MAX_VALUE) { - return Long.MAX_VALUE; - } - - long result = now + millis; - if (result < 0) { - return Long.MAX_VALUE; - } - return result; - } - private void updateUsageInBytesIfRequired(long delta) { map.updateUsageInBytesIfRequired(delta); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java index d7b7a9e87a..fe1b46c9a5 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.store.heap.holders; -import org.ehcache.expiry.Duration; import org.ehcache.sizeof.annotations.IgnoreSizeOf; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.copy.Copier; @@ -51,7 +50,7 @@ protected CopiedOnHeapValueHolder(long id, V value, long creationTime, long expi * @param now timestamp in millis * @param expiration computed expiration duration */ - public CopiedOnHeapValueHolder(Store.ValueHolder valueHolder, V value, boolean evictionAdvice, Copier valueCopier, long now, Duration expiration) { + public CopiedOnHeapValueHolder(Store.ValueHolder valueHolder, V value, boolean evictionAdvice, Copier valueCopier, long now, java.time.Duration expiration) { super(valueHolder.getId(), valueHolder.creationTime(TIME_UNIT), valueHolder.expirationTime(TIME_UNIT), evictionAdvice); if (value == null) { throw new NullPointerException("null value"); diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java index 2a47a0bce8..3d01646c55 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.store.heap.holders; import org.ehcache.spi.serialization.SerializerException; -import org.ehcache.expiry.Duration; import org.ehcache.sizeof.annotations.IgnoreSizeOf; import org.ehcache.core.spi.store.Store; import org.ehcache.impl.internal.store.BinaryValueHolder; @@ -49,13 +48,13 @@ public SerializedOnHeapValueHolder(V value, long creationTime, long expirationTi this(-1, value, creationTime, expirationTime, evictionAdvice, serializer); } - public SerializedOnHeapValueHolder(Store.ValueHolder valueHolder, V value, boolean evictionAdvice, Serializer serializer, long now, Duration expiration) { + public SerializedOnHeapValueHolder(Store.ValueHolder valueHolder, V value, boolean evictionAdvice, Serializer serializer, long now, java.time.Duration expiration) { this(valueHolder.getId(), value, valueHolder.creationTime(TIME_UNIT), valueHolder.expirationTime(TIME_UNIT), evictionAdvice, serializer); this.setHits(valueHolder.hits()); this.accessed(now, expiration); } - public SerializedOnHeapValueHolder(Store.ValueHolder valueHolder, ByteBuffer binaryValue, boolean evictionAdvice, Serializer serializer, long now, Duration expiration) { + public SerializedOnHeapValueHolder(Store.ValueHolder valueHolder, ByteBuffer binaryValue, boolean evictionAdvice, Serializer serializer, long now, java.time.Duration expiration) { super(valueHolder.getId(), valueHolder.creationTime(TIME_UNIT), valueHolder.expirationTime(TIME_UNIT), evictionAdvice); this.buffer = binaryValue; this.serializer = serializer; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index a7b88f28f0..a53e161ece 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -16,13 +16,13 @@ package org.ehcache.impl.internal.store.offheap; +import java.time.Duration; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; @@ -32,12 +32,12 @@ import org.ehcache.Cache; import org.ehcache.config.EvictionAdvisor; +import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.time.TimeSource; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.store.offheap.factories.EhcacheSegmentFactory; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEventSource; @@ -72,7 +72,7 @@ public abstract class AbstractOffHeapStore implements AuthoritativeTier eventDispatcher; - private final Expiry expiry; + private final ExpiryPolicy expiry; private final OperationObserver getObserver; private final OperationObserver putObserver; @@ -1000,6 +1000,9 @@ private OffHeapValueHolder setAccessTimeAndExpiryThenReturnMapping(K key, Off Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForAccess(key, valueHolder); + if (duration != null && duration.isNegative()) { + duration = Duration.ZERO; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } @@ -1017,6 +1020,9 @@ private OffHeapValueHolder newUpdatedValueHolder(K key, V value, OffHeapValue Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForUpdate(key, existing, value); + if (duration != null && duration.isNegative()) { + duration = Duration.ZERO; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } @@ -1027,10 +1033,10 @@ private OffHeapValueHolder newUpdatedValueHolder(K key, V value, OffHeapValue if (duration == null) { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, existing.expirationTime(OffHeapValueHolder.TIME_UNIT)); - } else if (duration.isInfinite()) { + } else if (duration.getSeconds() == Long.MAX_VALUE) { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, OffHeapValueHolder.NO_EXPIRE); } else { - return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, safeExpireTime(now, duration)); + return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, ExpiryUtils.getExpirationMillis(now, duration)); } } @@ -1038,6 +1044,9 @@ private OffHeapValueHolder newCreateValueHolder(K key, V value, long now, Sto Duration duration = Duration.ZERO; try { duration = expiry.getExpiryForCreation(key, value); + if (duration.isNegative()) { + return null; + } } catch (RuntimeException re) { LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } @@ -1047,10 +1056,10 @@ private OffHeapValueHolder newCreateValueHolder(K key, V value, long now, Sto eventSink.created(key, value); - if (duration.isInfinite()) { + if (duration.getSeconds() == Long.MAX_VALUE) { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, OffHeapValueHolder.NO_EXPIRE); } else { - return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, safeExpireTime(now, duration)); + return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, ExpiryUtils.getExpirationMillis(now, duration)); } } @@ -1073,20 +1082,6 @@ private void invokeValve() throws StoreAccessException { } } - private static long safeExpireTime(long now, Duration duration) { - long millis = OffHeapValueHolder.TIME_UNIT.convert(duration.getLength(), duration.getTimeUnit()); - - if (millis == Long.MAX_VALUE) { - return Long.MAX_VALUE; - } - - long result = now + millis; - if (result < 0) { - return Long.MAX_VALUE; - } - return result; - } - private void checkKey(K keyObject) { if (keyObject == null) { throw new NullPointerException(); diff --git a/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java b/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java index a5843409fc..ae46129c48 100644 --- a/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java @@ -20,9 +20,8 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.service.ServiceUtils; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; import org.ehcache.impl.config.serializer.DefaultSerializerConfiguration; @@ -221,7 +220,7 @@ public Long copyForWrite(Object obj) { public void testNothing() { final CacheConfigurationBuilder builder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, CharSequence.class, heap(10)); - final Expiry expiry = Expirations.timeToIdleExpiration(Duration.INFINITE); + final ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(ExpiryPolicy.INFINITE); builder .withEvictionAdvisor((key, value) -> value.charAt(0) == 'A') @@ -235,7 +234,7 @@ public void testOffheapGetsAddedToCacheConfiguration() { ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)); - final Expiry expiry = Expirations.timeToIdleExpiration(Duration.INFINITE); + final ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(ExpiryPolicy.INFINITE); CacheConfiguration config = builder .withEvictionAdvisor((key, value) -> value.charAt(0) == 'A') @@ -274,7 +273,7 @@ public void testCopyingOfExistingConfiguration() { @SuppressWarnings("unchecked") EvictionAdvisor eviction = mock(EvictionAdvisor.class); @SuppressWarnings("unchecked") - Expiry expiry = mock(Expiry.class); + ExpiryPolicy expiry = mock(ExpiryPolicy.class); ServiceConfiguration service = mock(ServiceConfiguration.class); CacheConfiguration configuration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Integer.class, String.class, heap(10)) @@ -291,7 +290,7 @@ public void testCopyingOfExistingConfiguration() { assertThat(copy.getClassLoader(), equalTo(loader)); assertThat(copy.getEvictionAdvisor(), IsSame.>sameInstance(eviction)); - assertThat(copy.getExpiry(), IsSame.>sameInstance(expiry)); + assertThat(copy.getExpiryPolicy(), IsSame.>sameInstance(expiry)); assertThat(copy.getServiceConfigurations(), contains(IsSame.>sameInstance(service))); } } diff --git a/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java b/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java index 2a326fc36a..29350a4724 100644 --- a/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java @@ -21,17 +21,16 @@ import org.ehcache.UserManagedCache; import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.event.EventType; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.impl.internal.spi.event.DefaultCacheEventListenerProviderTest; import org.junit.Test; +import java.time.Duration; import java.util.Iterator; import java.util.Map; import java.util.Set; -import java.util.concurrent.TimeUnit; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -81,7 +80,7 @@ public void testInvalidListenerConfig() { @Test public void testTypedCacheWithExpirationPolicy() { try (UserManagedCache cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class) - .withExpiry(Expirations.timeToIdleExpiration(new Duration(30, TimeUnit.SECONDS))) + .withExpiry(ExpiryPolicies.timeToIdleExpiration(Duration.ofSeconds(30))) .build(true)) { assertThat(cache, notNullValue()); } diff --git a/impl/src/test/java/org/ehcache/docs/GettingStarted.java b/impl/src/test/java/org/ehcache/docs/GettingStarted.java index 5e45fd3093..044dfbed82 100644 --- a/impl/src/test/java/org/ehcache/docs/GettingStarted.java +++ b/impl/src/test/java/org/ehcache/docs/GettingStarted.java @@ -29,9 +29,8 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.docs.plugs.ListenerObject; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.serialization.JavaSerializer; import org.ehcache.docs.plugs.OddKeysEvictionAdvisor; import org.ehcache.docs.plugs.SampleLoaderWriter; @@ -44,6 +43,7 @@ import java.io.File; import java.io.Serializable; import java.net.URISyntaxException; +import java.time.Duration; import java.util.EnumSet; import java.util.concurrent.TimeUnit; @@ -244,7 +244,7 @@ public void expiry() throws Exception { // tag::expiry[] CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)) // <1> - .withExpiry(Expirations.timeToLiveExpiration(Duration.of(20, TimeUnit.SECONDS))) // <2> + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(20))) // <2> .build(); // end::expiry[] } @@ -354,7 +354,7 @@ private String getStoragePath() throws URISyntaxException { return getClass().getClassLoader().getResource(".").toURI().getPath(); } - public static class CustomExpiry implements Expiry { + public static class CustomExpiry implements ExpiryPolicy { @Override public Duration getExpiryForCreation(Long key, String value) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java index c70974a837..33464a039e 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java @@ -15,12 +15,11 @@ */ package org.ehcache.impl.internal.loaderwriter.writebehind; -import java.util.concurrent.TimeUnit; +import java.time.Duration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.executor.PooledExecutionServiceConfiguration; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; @@ -35,7 +34,7 @@ public class PooledExecutorWriteBehindTest extends AbstractWriteBehindTestBase { @Override protected CacheConfigurationBuilder configurationBuilder() { return newCacheConfigurationBuilder(String.class, String.class, heap(100)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java index 8f12427608..7e2cb833dc 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java @@ -15,12 +15,11 @@ */ package org.ehcache.impl.internal.loaderwriter.writebehind; -import java.util.concurrent.TimeUnit; +import java.time.Duration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; @@ -35,7 +34,7 @@ public class WriteBehindEvictionTest extends AbstractWriteBehindTestBase { @Override protected CacheConfigurationBuilder configurationBuilder() { return newCacheConfigurationBuilder(String.class, String.class, heap(10)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(100, TimeUnit.MILLISECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(100))); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java index 56613a5811..106ad91ad1 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java @@ -15,12 +15,11 @@ */ package org.ehcache.impl.internal.loaderwriter.writebehind; -import java.util.concurrent.TimeUnit; +import java.time.Duration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; @@ -35,7 +34,7 @@ public class WriteBehindTest extends AbstractWriteBehindTestBase { @Override protected CacheConfigurationBuilder configurationBuilder() { return newCacheConfigurationBuilder(String.class, String.class, heap(100)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java index e90d3f3112..86c5ab608c 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java @@ -16,22 +16,21 @@ package org.ehcache.impl.internal.statistics; -import java.util.concurrent.TimeUnit; - import org.assertj.core.api.AbstractObjectAssert; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.core.InternalCache; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.internal.TestTimeSource; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.time.Duration; + import static org.assertj.core.api.Assertions.assertThat; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; @@ -49,7 +48,7 @@ public void before() { CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(10)) - .withExpiry(Expirations.timeToLiveExpiration(Duration.of(TIME_TO_EXPIRATION, TimeUnit.MILLISECONDS))) + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java index 6cf38f2bd2..af74987fe2 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java @@ -16,22 +16,21 @@ package org.ehcache.impl.internal.statistics; -import java.util.concurrent.TimeUnit; - import org.assertj.core.api.AbstractObjectAssert; import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.internal.TestTimeSource; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.time.Duration; + import static org.assertj.core.api.Assertions.assertThat; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; @@ -49,7 +48,7 @@ public void before() { CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(10)) - .withExpiry(Expirations.timeToLiveExpiration(Duration.of(TIME_TO_EXPIRATION, TimeUnit.MILLISECONDS))) + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java index 6aba43f141..6cc487992a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java @@ -27,8 +27,8 @@ import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.DefaultTimeSourceService; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; @@ -117,8 +117,8 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { - return Expirations.noExpiration(); + public ExpiryPolicy getExpiry() { + return ExpiryPolicies.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java index 1ad20ba49e..e2703c4029 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java @@ -23,8 +23,8 @@ import org.ehcache.config.SizedResourcePool; import org.ehcache.config.units.MemoryUnit; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.executor.OnDemandExecutionService; @@ -83,26 +83,26 @@ public void setUp() throws Exception { @Override public AuthoritativeTier newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public AuthoritativeTier newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public AuthoritativeTier newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public AuthoritativeTier newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public AuthoritativeTier newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } - private AuthoritativeTier newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private AuthoritativeTier newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { Serializer keySerializer = new JavaSerializer<>(getClass().getClassLoader()); Serializer valueSerializer = new JavaSerializer<>(getClass().getClassLoader()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java index 0c283df278..6d4bb1127f 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java @@ -28,7 +28,7 @@ import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.executor.OnDemandExecutionService; @@ -80,7 +80,7 @@ import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.ehcache.config.units.MemoryUnit.MB; import static org.ehcache.core.internal.service.ServiceLocator.dependencySet; -import static org.ehcache.expiry.Expirations.noExpiration; +import static org.ehcache.expiry.ExpiryPolicies.noExpiration; import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_DISK_SEGMENTS; import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_WRITER_CONCURRENCY; import static org.ehcache.impl.internal.spi.TestServiceProvider.providerContaining; @@ -242,7 +242,7 @@ public void testProvidingOffHeapDiskStoreConfiguration() throws Exception { } @Override - protected OffHeapDiskStore createAndInitStore(final TimeSource timeSource, final Expiry expiry) { + protected OffHeapDiskStore createAndInitStore(final TimeSource timeSource, final ExpiryPolicy expiry) { try { SerializationProvider serializationProvider = new DefaultSerializationProvider(null); serializationProvider.start(providerContaining(diskResourceService)); @@ -265,7 +265,7 @@ protected OffHeapDiskStore createAndInitStore(final TimeSource t } @Override - protected OffHeapDiskStore createAndInitStore(TimeSource timeSource, Expiry expiry, EvictionAdvisor evictionAdvisor) { + protected OffHeapDiskStore createAndInitStore(TimeSource timeSource, ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor) { try { SerializationProvider serializationProvider = new DefaultSerializationProvider(null); serializationProvider.start(providerContaining(diskResourceService)); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java index 3358880e92..43931944fa 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java @@ -22,9 +22,8 @@ import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.store.heap.holders.CopiedOnHeapValueHolder; import org.ehcache.core.spi.time.SystemTimeSource; @@ -46,6 +45,7 @@ import org.junit.runner.Description; import org.mockito.InOrder; +import java.time.Duration; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; @@ -196,7 +196,7 @@ public void testGetExpired() throws Exception { StoreEventSink eventSink = getStoreEventSink(); StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); assertThat(store.get("key").value(), equalTo("value")); timeSource.advanceTime(1); @@ -212,7 +212,7 @@ public void testGetExpired() throws Exception { public void testGetNoExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(2, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(2))); StoreEventSink eventSink = getStoreEventSink(); store.put("key", "value"); timeSource.advanceTime(1); @@ -224,7 +224,7 @@ public void testGetNoExpired() throws Exception { @Test public void testAccessTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, Expirations.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); store.put("key", "value"); long first = store.get("key").lastAccessTime(TimeUnit.MILLISECONDS); @@ -254,7 +254,7 @@ public void testContainsKeyExpired() throws Exception { StoreEventSink eventSink = getStoreEventSink(); StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -295,7 +295,7 @@ public void testPutOverwrite() throws Exception { @Test public void testCreateTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, Expirations.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); assertThat(store.containsKey("key"), is(false)); store.put("key", "value"); ValueHolder valueHolder = store.get("key"); @@ -338,7 +338,7 @@ public void testPutIfAbsentValuePresent() throws Exception { @Test public void testPutIfAbsentUpdatesAccessTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, Expirations.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); assertThat(store.get("key"), nullValue()); store.putIfAbsent("key", "value"); long first = store.get("key").lastAccessTime(TimeUnit.MILLISECONDS); @@ -351,7 +351,7 @@ public void testPutIfAbsentUpdatesAccessTime() throws Exception { public void testPutIfAbsentExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); ValueHolder prev = store.putIfAbsent("key", "value2"); @@ -405,7 +405,7 @@ public void testRemoveTwoArgExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); assertThat(store.get("key").value(), equalTo("value")); @@ -447,7 +447,7 @@ public void testReplaceTwoArgExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -494,7 +494,7 @@ public void testReplaceThreeArgExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -535,7 +535,7 @@ public void testIterator() throws Exception { public void testIteratorExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key1", "value1"); store.put("key2", "value2"); store.put("key3", "value3"); @@ -553,7 +553,7 @@ public void testIteratorExpired() throws Exception { @Test public void testIteratorDoesNotUpdateAccessTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, Expirations.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); store.put("key1", "value1"); store.put("key2", "value2"); @@ -569,7 +569,7 @@ public void testIteratorDoesNotUpdateAccessTime() throws Exception { @Test public void testComputeReplaceTrue() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, Expirations.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); StoreEventSink eventSink = getStoreEventSink(); StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); @@ -592,7 +592,7 @@ public void testComputeReplaceTrue() throws Exception { @Test public void testComputeReplaceFalse() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, Expirations.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); store.put("key", "value"); ValueHolder installedHolder = store.get("key"); @@ -692,7 +692,7 @@ public void testComputeExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); ValueHolder newValue = store.compute("key", (mappedKey, mappedValue) -> { @@ -711,7 +711,7 @@ public void testComputeExpired() throws Exception { public void testComputeWhenExpireOnCreate() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(1000L); - OnHeapStore store = newStore(timeSource, Expirations.builder().setCreate(Duration.ZERO).build()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.builder().setCreate(Duration.ZERO).build()); ValueHolder result = store.compute("key", (key, value) -> "value", () -> false); assertThat(result, nullValue()); @@ -721,7 +721,7 @@ public void testComputeWhenExpireOnCreate() throws Exception { public void testComputeWhenExpireOnUpdate() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(1000L); - OnHeapStore store = newStore(timeSource, Expirations.builder().setUpdate(Duration.ZERO).build()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); store.put("key", "value"); ValueHolder result = store.compute("key", (key, value) -> "newValue", () -> false); @@ -732,7 +732,7 @@ public void testComputeWhenExpireOnUpdate() throws Exception { public void testComputeWhenExpireOnAccess() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(1000L); - OnHeapStore store = newStore(timeSource, Expirations.builder().setAccess(Duration.ZERO).build()); + OnHeapStore store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); store.put("key", "value"); ValueHolder result = store.compute("key", (key, value) -> value, () -> false); @@ -804,7 +804,7 @@ public void testComputeIfAbsentException() throws Exception { public void testComputeIfAbsentExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -826,7 +826,7 @@ public void testComputeIfAbsentExpired() throws Exception { @Test public void testExpiryCreateException() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, new Expiry() { + OnHeapStore store = newStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { @@ -852,11 +852,11 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o public void testExpiryAccessExceptionReturnsValueAndExpiresIt() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(5); - OnHeapStore store = newStore(timeSource, new Expiry() { + OnHeapStore store = newStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override @@ -878,15 +878,15 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o @Test public void testExpiryUpdateException() throws Exception{ final TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, new Expiry() { + OnHeapStore store = newStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForAccess(String key, ValueSupplier value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override @@ -894,7 +894,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o if (timeSource.getTimeMillis() > 0) { throw new RuntimeException(); } - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } }); @@ -910,7 +910,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o public void testGetOrComputeIfAbsentExpiresOnHit() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); @SuppressWarnings("unchecked") CachingTier.InvalidationListener invalidationListener = mock(CachingTier.InvalidationListener.class); store.setInvalidationListener(invalidationListener); @@ -932,7 +932,7 @@ public void testGetOrComputeIfAbsentExpiresOnHit() throws Exception { public void testGetOfComputeIfAbsentExpiresWithLoaderWriter() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); @SuppressWarnings("unchecked") CachingTier.InvalidationListener invalidationListener = mock(CachingTier.InvalidationListener.class); store.setInvalidationListener(invalidationListener); @@ -1217,7 +1217,7 @@ public void testEvictionDoneUnderEvictedKeyLockScope() throws Exception { @Test(timeout = 2000L) public void testIteratorExpiryHappensUnderExpiredKeyLockScope() throws Exception { TestTimeSource testTimeSource = new TestTimeSource(); - final OnHeapStore store = newStore(testTimeSource, Expirations.timeToLiveExpiration(new Duration(10, TimeUnit.MILLISECONDS))); + final OnHeapStore store = newStore(testTimeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10))); store.put("key", "value"); @@ -1335,19 +1335,19 @@ protected StoreEventDispatcher getStoreEventDispatcher() { } protected OnHeapStore newStore() { - return newStore(SystemTimeSource.INSTANCE, Expirations.noExpiration(), Eviction.noAdvice()); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice()); } protected OnHeapStore newStore(EvictionAdvisor evictionAdvisor) { - return newStore(SystemTimeSource.INSTANCE, Expirations.noExpiration(), evictionAdvisor); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), evictionAdvisor); } - protected OnHeapStore newStore(TimeSource timeSource, Expiry expiry) { + protected OnHeapStore newStore(TimeSource timeSource, ExpiryPolicy expiry) { return newStore(timeSource, expiry, Eviction.noAdvice()); } protected abstract void updateStoreCapacity(OnHeapStore store, int newCapacity); protected abstract OnHeapStore newStore(final TimeSource timeSource, - final Expiry expiry, final EvictionAdvisor evictionAdvisor); + final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java index ea9fa0fa7f..ac5cff597b 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java @@ -20,8 +20,8 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -57,26 +57,26 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @SuppressWarnings("unchecked") - private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { ResourcePools resourcePools = buildResourcePools(capacity); Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), evictionAdvisor, getClass().getClassLoader(), expiry, resourcePools, 0, null, null); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java index 6002a12b5d..04f610b240 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java @@ -20,8 +20,8 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -62,25 +62,25 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } - private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { ResourcePools resourcePools = buildResourcePools(capacity); Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), evictionAdvisor, getClass().getClassLoader(), expiry, resourcePools, 0, diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByRefTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByRefTest.java index d58618eb4e..496025298d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByRefTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByRefTest.java @@ -21,7 +21,7 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; import org.ehcache.core.spi.time.TimeSource; @@ -46,7 +46,7 @@ protected void updateStoreCapacity(OnHeapStore store, int newCapacity) { @Override @SuppressWarnings("unchecked") protected OnHeapStore newStore(final TimeSource timeSource, - final Expiry expiry, + final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, final int capacity) { return new OnHeapStore(new Store.Configuration() { @@ -73,7 +73,7 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByValueTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByValueTest.java index 43e2542eb4..b3361ee632 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByValueTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/CountSizedOnHeapStoreByValueTest.java @@ -22,7 +22,7 @@ import org.ehcache.config.ResourcePools; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.events.StoreEventDispatcher; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.store.Store; @@ -46,7 +46,7 @@ protected void updateStoreCapacity(OnHeapStore store, int newCapacity) { @Override protected OnHeapStore newStore(final TimeSource timeSource, - final Expiry expiry, + final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, final Copier keyCopier, final Copier valueCopier, final int capacity) { StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); return new OnHeapStore<>(new Store.Configuration() { @@ -74,7 +74,7 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java index fa7d5cc3ab..6df8c6fe5a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java @@ -17,7 +17,7 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -34,7 +34,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; -import java.util.function.Function; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.hamcrest.Matchers.is; @@ -55,7 +54,7 @@ public class OnHeapStoreBulkMethodsTest { protected Store.Configuration mockStoreConfig() { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(Expirations.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(CharSequence.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build()); @@ -74,7 +73,7 @@ protected OnHeapStore newStore() { public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(Expirations.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(Number.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java index a6b9a3a5e3..4fce95e584 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java @@ -20,8 +20,8 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -63,26 +63,26 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @SuppressWarnings("unchecked") - private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { ResourcePools resourcePools = buildResourcePools(capacity); Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), evictionAdvisor, getClass().getClassLoader(), expiry, resourcePools, 0, null, null); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefTest.java index 02e43f6be2..abe0f0960f 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefTest.java @@ -16,20 +16,20 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.config.EvictionAdvisor; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.time.TimeSource; +import org.ehcache.expiry.ExpiryPolicy; public abstract class OnHeapStoreByRefTest extends BaseOnHeapStoreTest { @Override protected OnHeapStore newStore(final TimeSource timeSource, - final Expiry expiry, + final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor) { return newStore(timeSource, expiry, evictionAdvisor, 100); } protected abstract OnHeapStore newStore(TimeSource timeSource, - Expiry expiry, + ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor, int capacity); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java index 5b7a6bb4b6..9b4bfc9b5b 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java @@ -20,8 +20,8 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -68,25 +68,25 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } - private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { ResourcePools resourcePools = buildResourcePools(capacity); Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), evictionAdvisor, getClass().getClassLoader(), expiry, resourcePools, 0, diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java index b41bc112b4..7e5f3725ea 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java @@ -21,11 +21,11 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.spi.serialization.SerializerException; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.spi.time.SystemTimeSource; import org.ehcache.core.spi.time.TimeSource; @@ -40,7 +40,6 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import java.util.function.Function; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.hamcrest.CoreMatchers.instanceOf; @@ -71,7 +70,7 @@ public Long copyForWrite(Long obj) { @Test public void testKeyCopierCalledOnGetOrComputeIfAbsent() throws Exception { LongCopier keyCopier = new LongCopier(); - OnHeapStore store = newStore(SystemTimeSource.INSTANCE, Expirations.noExpiration(), Eviction.noAdvice(), + OnHeapStore store = newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice(), keyCopier, new SerializingCopier<>(new JavaSerializer<>(ClassLoader.getSystemClassLoader())), 100); ValueHolder computed = store.getOrComputeIfAbsent(1L, key -> new AbstractValueHolder(-1, -1) { @@ -177,7 +176,7 @@ public void testStoreByValue() { } @Override - protected OnHeapStore newStore(TimeSource timeSource, Expiry expiry, + protected OnHeapStore newStore(TimeSource timeSource, ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor) { Copier keyCopier = new SerializingCopier<>(new JavaSerializer<>(getClass().getClassLoader())); Copier valueCopier = new SerializingCopier<>(new JavaSerializer<>(getClass().getClassLoader())); @@ -185,7 +184,7 @@ protected OnHeapStore newStore(TimeSource timeSource, Expiry OnHeapStore newStore(TimeSource timeSource, - Expiry expiry, EvictionAdvisor evictionAdvisor, + ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor, Copier keyCopier, Copier valueCopier, int capacity); private void performAssertions(Cache cache, boolean same) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java index 9eddac0fc5..94cb8dadd3 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java @@ -19,7 +19,7 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -71,7 +71,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), Expirations.noExpiration(), buildResourcePools(capacity), 0, null, null); + ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, null, null); return new OnHeapStore(config, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java index 0885e675b8..8507da9f93 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java @@ -19,7 +19,7 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -74,7 +74,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), Expirations.noExpiration(), buildResourcePools(capacity), 0, + ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); return new OnHeapStore<>(config, SystemTimeSource.INSTANCE, defaultCopier, defaultCopier, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java index e4624a3956..f4a3ee90ef 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java @@ -20,11 +20,9 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.core.spi.store.events.StoreEvent; -import org.ehcache.core.spi.store.events.StoreEventListener; import org.ehcache.event.EventType; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -33,7 +31,6 @@ import org.ehcache.core.spi.time.SystemTimeSource; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.Store.ValueHolder; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.copy.Copier; import org.ehcache.spi.serialization.Serializer; @@ -41,12 +38,9 @@ import org.junit.Test; import java.io.Serializable; -import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Semaphore; -import java.util.function.BiFunction; -import java.util.function.Function; import static org.ehcache.config.Eviction.noAdvice; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; @@ -112,7 +106,7 @@ public void testEvictionCandidateLimits() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreConfigurationImpl configuration = new StoreConfigurationImpl<>( String.class, String.class, noAdvice(), - getClass().getClassLoader(), Expirations.noExpiration(), heap(1).build(), 1, null, null); + getClass().getClassLoader(), ExpiryPolicies.noExpiration(), heap(1).build(), 1, null, null); TestStoreEventDispatcher eventDispatcher = new TestStoreEventDispatcher<>(); final String firstKey = "daFirst"; eventDispatcher.addEventListener(event -> { @@ -154,8 +148,8 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { - return Expirations.noExpiration(); + public ExpiryPolicy getExpiry() { + return ExpiryPolicies.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java index 57ff5c329b..f1ffaeb098 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java @@ -19,7 +19,7 @@ import org.ehcache.Cache; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -33,10 +33,7 @@ import java.util.Arrays; import java.util.Collection; -import java.util.Map; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.Function; import java.util.function.Supplier; import static java.util.Collections.singleton; @@ -82,7 +79,7 @@ public void setUp() { when(configuration.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()); when(configuration.getKeyType()).thenReturn(Key.class); when(configuration.getValueType()).thenReturn(String.class); - when(configuration.getExpiry()).thenReturn(Expirations.noExpiration()); + when(configuration.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); @SuppressWarnings("unchecked") Store.Configuration config = configuration; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java index e47e8339db..f93c12a173 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java @@ -19,7 +19,7 @@ import org.ehcache.Cache; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -34,8 +34,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Map; -import java.util.function.BiFunction; -import java.util.function.Function; import java.util.function.Supplier; import static java.util.Collections.singleton; @@ -81,7 +79,7 @@ public void setUp() { when(configuration.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()); when(configuration.getKeyType()).thenReturn(Long.class); when(configuration.getValueType()).thenReturn(Value.class); - when(configuration.getExpiry()).thenReturn(Expirations.noExpiration()); + when(configuration.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); @SuppressWarnings("unchecked") Store.Configuration config = configuration; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java index e4e99de1f3..39f830d79f 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java @@ -23,9 +23,8 @@ import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.heap.LimitExceededException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -45,11 +44,9 @@ import org.hamcrest.Matcher; import org.junit.Test; +import java.time.Duration; import java.util.Arrays; import java.util.concurrent.TimeUnit; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.ehcache.internal.store.StoreCreationEventListenerTest.eventType; @@ -80,22 +77,22 @@ public class ByteAccountingTest { OnHeapStoreForTests newStore() { - return newStore(SystemTimeSource.INSTANCE, Expirations.noExpiration(), Eviction.noAdvice()); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice()); } OnHeapStoreForTests newStore(int capacity) { - return newStore(SystemTimeSource.INSTANCE, Expirations.noExpiration(), Eviction.noAdvice(), capacity); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice(), capacity); } - OnHeapStoreForTests newStore(TimeSource timeSource, Expiry expiry) { + OnHeapStoreForTests newStore(TimeSource timeSource, ExpiryPolicy expiry) { return newStore(timeSource, expiry, Eviction.noAdvice()); } - OnHeapStoreForTests newStore(TimeSource timeSource, Expiry expiry, EvictionAdvisor evictionAdvisor) { + OnHeapStoreForTests newStore(TimeSource timeSource, ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor) { return newStore(timeSource, expiry, evictionAdvisor, 100); } - private OnHeapStoreForTests newStore(final TimeSource timeSource, final Expiry expiry, final EvictionAdvisor evictionAdvisor, + private OnHeapStoreForTests newStore(final TimeSource timeSource, final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, final int capacity) { return new OnHeapStoreForTests<>(new Store.Configuration() { @@ -122,7 +119,7 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } @@ -173,7 +170,7 @@ public void testPutUpdate() throws StoreAccessException { @Test public void testPutExpiryOnCreate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setCreate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setCreate(Duration.ZERO).build()); store.put(KEY, VALUE); @@ -183,7 +180,7 @@ public void testPutExpiryOnCreate() throws StoreAccessException { @Test public void testPutExpiryOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); store.put(KEY, VALUE); store.put(KEY, "otherValue"); @@ -240,7 +237,7 @@ public void testRemoveTwoArgExpired() throws StoreAccessException { @Test public void testRemoveTwoArgExpiresOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); store.put(KEY, VALUE); store.remove(KEY, "whatever value, it expires on access"); @@ -282,7 +279,7 @@ public void testReplaceTwoArgExpired() throws StoreAccessException { @Test public void testReplaceTwoArgExpiresOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); store.put(KEY, VALUE); store.replace(KEY, "whatever value, it expires on update"); @@ -324,7 +321,7 @@ public void testReplaceThreeArgExpired() throws StoreAccessException { @Test public void testReplaceThreeArgExpiresOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); store.put(KEY, VALUE); store.replace(KEY, VALUE, "whatever value, it expires on update"); @@ -357,7 +354,7 @@ public void testPutIfAbsentOverExpired() throws StoreAccessException { @Test public void testPutIfAbsentExpiresOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); store.put(KEY, VALUE); store.putIfAbsent(KEY, "another value ... whatever"); @@ -420,7 +417,7 @@ public void testCompute() throws StoreAccessException { @Test public void testComputeExpiryOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); store.put(KEY, VALUE); store.compute(KEY, (s, s2) -> s2, () -> false); @@ -431,7 +428,7 @@ public void testComputeExpiryOnAccess() throws StoreAccessException { @Test public void testComputeExpiryOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); store.put(KEY, VALUE); store.compute(KEY, (s, s2) -> s2); @@ -455,7 +452,7 @@ public void testComputeIfAbsent() throws StoreAccessException { @Test public void testComputeIfAbsentExpireOnCreate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setCreate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setCreate(Duration.ZERO).build()); store.computeIfAbsent(KEY, s -> VALUE); @@ -465,7 +462,7 @@ public void testComputeIfAbsentExpireOnCreate() throws StoreAccessException { @Test public void testComputeIfAbsentExpiryOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, Expirations.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); store.put(KEY, VALUE); store.computeIfAbsent(KEY, s -> { @@ -479,7 +476,7 @@ public void testComputeIfAbsentExpiryOnAccess() throws StoreAccessException { @Test public void testExpiry() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStoreForTests store = newStore(timeSource, Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.MILLISECONDS))); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); store.put(KEY, VALUE); assertThat(store.getCurrentUsageInBytes(), is(SIZE_OF_KEY_VALUE_PAIR)); @@ -517,8 +514,8 @@ public void testEviction() throws StoreAccessException { } - private Expiry ttlCreation600ms() { - return Expirations.builder().setCreate(new Duration(600L, TimeUnit.MILLISECONDS)).build(); + private ExpiryPolicy ttlCreation600ms() { + return ExpiryPolicies.builder().setCreate(Duration.ofMillis(600L)).build(); } static long getSize(String key, String value) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByRefTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByRefTest.java index 1c102303ad..13df73130d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByRefTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByRefTest.java @@ -22,7 +22,7 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; import org.ehcache.impl.internal.store.heap.OnHeapStore; @@ -50,7 +50,7 @@ protected void updateStoreCapacity(OnHeapStore store, int newCapacity) { @Override @SuppressWarnings("unchecked") protected OnHeapStore newStore(final TimeSource timeSource, - final Expiry expiry, + final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, final int capacity) { return new OnHeapStore(new Store.Configuration() { @@ -77,7 +77,7 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByValueTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByValueTest.java index 7d45e0683e..95dcaa740a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByValueTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteSizedOnHeapStoreByValueTest.java @@ -22,7 +22,7 @@ import org.ehcache.config.ResourcePools; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.events.StoreEventDispatcher; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; import org.ehcache.impl.internal.store.heap.OnHeapStore; import org.ehcache.impl.internal.store.heap.OnHeapStoreByValueTest; @@ -50,7 +50,7 @@ protected void updateStoreCapacity(OnHeapStore store, int newCapacity) { @Override protected OnHeapStore newStore(final TimeSource timeSource, - final Expiry expiry, + final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, final Copier keyCopier, final Copier valueCopier, final int capacity) { StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); @@ -79,7 +79,7 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java index 7a232c2f89..9b82807dc3 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java @@ -17,7 +17,7 @@ package org.ehcache.impl.internal.store.heap.bytesized; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -32,7 +32,6 @@ import java.util.HashSet; import java.util.Map; import java.util.concurrent.ConcurrentMap; -import java.util.function.Function; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.hamcrest.Matchers.is; @@ -47,7 +46,7 @@ public class OnHeapStoreBulkMethodsTest extends org.ehcache.impl.internal.store. protected Store.Configuration mockStoreConfig() { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(Expirations.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(CharSequence.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(100, MemoryUnit.KB).build()); @@ -66,7 +65,7 @@ protected OnHeapStore newStore() { public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(Expirations.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(Number.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(100, MemoryUnit.KB).build()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java index 076d998527..ba70889ac1 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java @@ -19,7 +19,7 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -69,7 +69,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), Expirations.noExpiration(), buildResourcePools(capacity), 0, null, null); + ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, null, null); return new OnHeapStore(config, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new DefaultSizeOfEngine(Long.MAX_VALUE, Long.MAX_VALUE), NullStoreEventDispatcher.nullStoreEventDispatcher()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java index 9761e1b7d0..9a33df716f 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java @@ -19,7 +19,7 @@ import org.ehcache.config.ResourcePools; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -72,7 +72,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), Expirations.noExpiration(), buildResourcePools(capacity), 0, + ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); return new OnHeapStore<>(config, SystemTimeSource.INSTANCE, defaultCopier, defaultCopier, new DefaultSizeOfEngine(Long.MAX_VALUE, Long.MAX_VALUE), NullStoreEventDispatcher.nullStoreEventDispatcher()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java index 37abbe782c..059c566f07 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java @@ -18,9 +18,9 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.time.TimeSource; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.serialization.Serializer; @@ -57,8 +57,8 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { - return Expirations.noExpiration(); + public ExpiryPolicy getExpiry() { + return ExpiryPolicies.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java index cf6e480bc7..95841408e5 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java @@ -20,8 +20,8 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; import org.ehcache.impl.internal.store.heap.OnHeapStore; @@ -32,9 +32,6 @@ import org.ehcache.spi.serialization.Serializer; import org.junit.Test; -import java.util.function.BiFunction; -import java.util.function.Function; - import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; @@ -51,11 +48,11 @@ public class OversizeMappingTest { private static final String OVER_SIZED_VALUE = new String(new byte[1000]); OnHeapStoreForTests newStore() { - return newStore(SystemTimeSource.INSTANCE, Expirations.noExpiration(), Eviction.noAdvice(), 100); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice(), 100); } - private OnHeapStoreForTests newStore(final TimeSource timeSource, final Expiry expiry, final EvictionAdvisor evictionAdvisor, - final int capacity) { + private OnHeapStoreForTests newStore(final TimeSource timeSource, final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, + final int capacity) { return new OnHeapStoreForTests<>(new Store.Configuration() { @SuppressWarnings("unchecked") @@ -81,7 +78,7 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { + public ExpiryPolicy getExpiry() { return expiry; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java index 6bed6257fa..cae9c1d5d9 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java @@ -22,17 +22,15 @@ import org.ehcache.config.units.MemoryUnit; import org.ehcache.event.EventType; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.store.AbstractValueHolder; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; -import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.core.statistics.StoreOperationOutcomes; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.Matchers; @@ -45,15 +43,13 @@ import org.terracotta.statistics.OperationStatistic; import org.terracotta.statistics.StatisticsManager; +import java.time.Duration; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.ehcache.impl.internal.util.Matchers.valueHeld; @@ -92,7 +88,7 @@ public void after() { @Test public void testGetAndRemoveNoValue() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.noExpiration()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.noExpiration()); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.MISS)); @@ -100,7 +96,7 @@ public void testGetAndRemoveNoValue() throws Exception { @Test public void testGetAndRemoveValue() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.noExpiration()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.noExpiration()); offHeapStore.put("1", "one"); assertThat(offHeapStore.getAndRemove("1").value(), equalTo("one")); @@ -110,7 +106,7 @@ public void testGetAndRemoveValue() throws Exception { @Test public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); @@ -128,7 +124,7 @@ public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { @Test public void testInstallMapping() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).value(), equalTo("one")); @@ -146,7 +142,7 @@ public void testInstallMapping() throws Exception { @Test public void testInvalidateKeyAbsent() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); final AtomicReference> invalidated = new AtomicReference<>(); offHeapStore.setInvalidationListener((key, valueHolder) -> invalidated.set(valueHolder)); @@ -158,7 +154,7 @@ public void testInvalidateKeyAbsent() throws Exception { @Test public void testInvalidateKeyPresent() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("1", "one"); @@ -174,7 +170,7 @@ public void testInvalidateKeyPresent() throws Exception { @Test public void testClear() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("1", "one"); offHeapStore.put("2", "two"); @@ -188,7 +184,7 @@ public void testClear() throws Exception { @Test public void testWriteBackOfValueHolder() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("key1", "value1"); timeSource.advanceTime(10); @@ -202,7 +198,7 @@ public void testWriteBackOfValueHolder() throws StoreAccessException { @Test public void testEvictionAdvisor() throws StoreAccessException { - Expiry expiry = Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS)); + ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L)); EvictionAdvisor evictionAdvisor = (key, value) -> true; performEvictionTest(timeSource, expiry, evictionAdvisor); @@ -210,7 +206,7 @@ public void testEvictionAdvisor() throws StoreAccessException { @Test public void testBrokenEvictionAdvisor() throws StoreAccessException { - Expiry expiry = Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS)); + ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L)); EvictionAdvisor evictionAdvisor = (key, value) -> { throw new UnsupportedOperationException("Broken advisor!"); }; @@ -220,7 +216,7 @@ public void testBrokenEvictionAdvisor() throws StoreAccessException { @Test public void testFlushUpdatesAccessStats() throws StoreAccessException { - Expiry expiry = Expirations.timeToIdleExpiration(new Duration(15L, TimeUnit.MILLISECONDS)); + ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L)); offHeapStore = createAndInitStore(timeSource, expiry); try { final String key = "foo"; @@ -244,14 +240,14 @@ public void testFlushUpdatesAccessStats() throws StoreAccessException { @Test public void testFlushUpdatesHits() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, Expirations.noExpiration()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.noExpiration()); final String key = "foo1"; final String value = "bar1"; offHeapStore.put(key, value); for(int i = 0; i < 5; i++) { final Store.ValueHolder valueHolder = offHeapStore.getAndFault(key); timeSource.advanceTime(1); - ((AbstractValueHolder)valueHolder).accessed(timeSource.getTimeMillis(), new Duration(1L, TimeUnit.MILLISECONDS)); + ((AbstractValueHolder)valueHolder).accessed(timeSource.getTimeMillis(), Duration.ofMillis(1L)); assertThat(offHeapStore.flush(key, new DelegatingValueHolder<>(valueHolder)), is(true)); } assertThat(offHeapStore.getAndFault(key).hits(), is(5L)); @@ -259,7 +255,7 @@ public void testFlushUpdatesHits() throws StoreAccessException { @Test public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); final List expiredKeys = new ArrayList<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { @@ -283,7 +279,7 @@ public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessExcepti @Test public void testGetWithExpiryOnAccess() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.builder().setAccess(Duration.ZERO).build()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); offHeapStore.put("key", "value"); final AtomicReference expired = new AtomicReference<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { @@ -297,7 +293,7 @@ public void testGetWithExpiryOnAccess() throws Exception { @Test public void testExpiryCreateException() throws Exception{ - offHeapStore = createAndInitStore(timeSource, new Expiry() { + offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { throw new RuntimeException(); @@ -319,10 +315,10 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o @Test public void testExpiryAccessException() throws Exception{ - offHeapStore = createAndInitStore(timeSource, new Expiry() { + offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override @@ -343,15 +339,15 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o @Test public void testExpiryUpdateException() throws Exception{ - offHeapStore = createAndInitStore(timeSource, new Expiry() { + offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForAccess(String key, ValueSupplier value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override @@ -359,7 +355,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o if (timeSource.getTimeMillis() > 0) { throw new RuntimeException(); } - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } }); @@ -372,7 +368,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o @Test public void testGetAndFaultOnExpiredEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); try { offHeapStore.put("key", "value"); timeSource.advanceTime(20L); @@ -389,7 +385,7 @@ public void testGetAndFaultOnExpiredEntry() throws StoreAccessException { public void testComputeExpiresOnAccess() throws StoreAccessException { timeSource.advanceTime(1000L); offHeapStore = createAndInitStore(timeSource, - Expirations.builder().setAccess(Duration.ZERO).setUpdate(Duration.ZERO).build()); + ExpiryPolicies.builder().setAccess(Duration.ZERO).setUpdate(Duration.ZERO).build()); offHeapStore.put("key", "value"); Store.ValueHolder result = offHeapStore.compute("key", (s, s2) -> s2, () -> false); @@ -402,7 +398,7 @@ public void testComputeExpiresOnUpdate() throws StoreAccessException { timeSource.advanceTime(1000L); offHeapStore = createAndInitStore(timeSource, - Expirations.builder().setAccess(Duration.ZERO).setUpdate(Duration.ZERO).build()); + ExpiryPolicies.builder().setAccess(Duration.ZERO).setUpdate(Duration.ZERO).build()); offHeapStore.put("key", "value"); Store.ValueHolder result = offHeapStore.compute("key", (s, s2) -> "newValue", () -> false); @@ -412,7 +408,7 @@ public void testComputeExpiresOnUpdate() throws StoreAccessException { @Test public void testComputeOnExpiredEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); offHeapStore.put("key", "value"); timeSource.advanceTime(20L); @@ -427,7 +423,7 @@ public void testComputeOnExpiredEntry() throws StoreAccessException { @Test public void testComputeIfAbsentOnExpiredEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToIdleExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); offHeapStore.put("key", "value"); timeSource.advanceTime(20L); @@ -441,7 +437,7 @@ public void testComputeIfAbsentOnExpiredEntry() throws StoreAccessException { @Test public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToLiveExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); offHeapStore.put("key2", "value2"); @@ -470,7 +466,7 @@ public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception { @Test public void testIteratorWithSingleExpiredEntry() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToLiveExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); @@ -484,7 +480,7 @@ public void testIteratorWithSingleExpiredEntry() throws Exception { @Test public void testIteratorWithSingleNonExpiredEntry() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToLiveExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); @@ -497,19 +493,19 @@ public void testIteratorWithSingleNonExpiredEntry() throws Exception { @Test public void testIteratorOnEmptyStore() throws Exception { - offHeapStore = createAndInitStore(timeSource, Expirations.timeToLiveExpiration(new Duration(10L, TimeUnit.MILLISECONDS))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); Store.Iterator>> iterator = offHeapStore.iterator(); assertFalse(iterator.hasNext()); } - protected abstract AbstractOffHeapStore createAndInitStore(final TimeSource timeSource, final Expiry expiry); + protected abstract AbstractOffHeapStore createAndInitStore(final TimeSource timeSource, final ExpiryPolicy expiry); - protected abstract AbstractOffHeapStore createAndInitStore(final TimeSource timeSource, final Expiry expiry, EvictionAdvisor evictionAdvisor); + protected abstract AbstractOffHeapStore createAndInitStore(final TimeSource timeSource, final ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor); protected abstract void destroyStore(AbstractOffHeapStore store); - private void performEvictionTest(TestTimeSource timeSource, Expiry expiry, EvictionAdvisor evictionAdvisor) throws StoreAccessException { + private void performEvictionTest(TestTimeSource timeSource, ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor) throws StoreAccessException { AbstractOffHeapStore offHeapStore = createAndInitStore(timeSource, expiry, evictionAdvisor); try { @SuppressWarnings("unchecked") diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java index 456488d4c2..72926b27d1 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java @@ -22,8 +22,8 @@ import org.ehcache.config.SizedResourcePool; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.core.spi.time.SystemTimeSource; import org.ehcache.core.spi.time.TimeSource; @@ -55,26 +55,26 @@ public void setUp() { authoritativeTierFactory = new AuthoritativeTierFactory() { @Override public AuthoritativeTier newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public AuthoritativeTier newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public AuthoritativeTier newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public AuthoritativeTier newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public AuthoritativeTier newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } - private AuthoritativeTier newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private AuthoritativeTier newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { Serializer keySerializer = new JavaSerializer<>(getClass().getClassLoader()); Serializer valueSerializer = new JavaSerializer<>(getClass().getClassLoader()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreTest.java index 402d7dd006..6c2e7e7b0a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreTest.java @@ -21,7 +21,7 @@ import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.spi.serialization.DefaultSerializationProvider; import org.ehcache.core.spi.time.TimeSource; @@ -44,7 +44,7 @@ public class OffHeapStoreTest extends AbstractOffHeapStoreTest { @Override - protected OffHeapStore createAndInitStore(TimeSource timeSource, Expiry expiry) { + protected OffHeapStore createAndInitStore(TimeSource timeSource, ExpiryPolicy expiry) { try { SerializationProvider serializationProvider = new DefaultSerializationProvider(null); serializationProvider.start(providerContaining()); @@ -63,7 +63,7 @@ protected OffHeapStore createAndInitStore(TimeSource timeSource, } @Override - protected OffHeapStore createAndInitStore(TimeSource timeSource, Expiry expiry, EvictionAdvisor evictionAdvisor) { + protected OffHeapStore createAndInitStore(TimeSource timeSource, ExpiryPolicy expiry, EvictionAdvisor evictionAdvisor) { try { SerializationProvider serializationProvider = new DefaultSerializationProvider(null); serializationProvider.start(providerContaining()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java index 6b715ceb60..ea91370275 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java @@ -21,7 +21,7 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.events.StoreEventDispatcher; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -77,7 +77,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), Expirations.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); + ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); StoreEventDispatcher eventDispatcher = NullStoreEventDispatcher.nullStoreEventDispatcher(); OffHeapStore offHeapStore = new OffHeapStore<>(config, SystemTimeSource.INSTANCE, eventDispatcher, 10 * 1024 * 1024); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java index 4699b16a23..d7d8f2c398 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java @@ -20,11 +20,11 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.core.spi.service.DiskResourceService; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.impl.persistence.DefaultDiskResourceService; import org.ehcache.impl.internal.store.disk.OffHeapDiskStore; import org.ehcache.impl.internal.store.heap.OnHeapStore; @@ -34,13 +34,11 @@ import org.ehcache.impl.serialization.JavaSerializer; import org.ehcache.spi.serialization.Serializer; import org.ehcache.spi.persistence.PersistableResourceService.PersistenceSpaceIdentifier; -import org.ehcache.spi.service.ServiceConfiguration; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; -import java.io.Serializable; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.ehcache.core.internal.service.ServiceLocator.dependencySet; @@ -81,8 +79,8 @@ public ClassLoader getClassLoader() { } @Override - public Expiry getExpiry() { - return Expirations.noExpiration(); + public ExpiryPolicy getExpiry() { + return ExpiryPolicies.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java index e8938e6dc0..48c1389b05 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java @@ -25,8 +25,8 @@ import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.core.spi.time.SystemTimeSource; import org.ehcache.docs.plugs.StringCopier; -import org.ehcache.expiry.Expirations; import org.ehcache.core.events.NullStoreEventDispatcher; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; import org.ehcache.impl.internal.store.basic.NopStore; import org.ehcache.impl.internal.store.heap.OnHeapStore; @@ -173,7 +173,7 @@ public void setUp() throws Exception { // Not relevant to the test, just used to instantiate the OnHeapStore Store.Configuration config = new StoreConfigurationImpl<>(String.class, String.class, - null, getClass().getClassLoader(), Expirations.noExpiration(), resourcePools, 0, null, null); + null, getClass().getClassLoader(), ExpiryPolicies.noExpiration(), resourcePools, 0, null, null); // Here again, all parameters are useless, we only care about the beforeCompletingTheFault implementation CachingTier cachingTier = new OnHeapStore<>(config, SystemTimeSource.INSTANCE, diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java index 98a6b07f8b..d3105e8c93 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java @@ -26,8 +26,8 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -105,25 +105,25 @@ public void setUp() throws IOException { @Override public Store newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } - private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { Serializer keySerializer = new JavaSerializer<>(getClass().getClassLoader()); Serializer valueSerializer = new JavaSerializer<>(getClass().getClassLoader()); Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java index 354b3a2e91..ab91cd228c 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java @@ -27,8 +27,8 @@ import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -106,25 +106,25 @@ public void setUp() throws IOException { @Override public Store newStore() { - return newStore(null, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } @Override - public Store newStoreWithExpiry(Expiry expiry, TimeSource timeSource) { + public Store newStoreWithExpiry(ExpiryPolicy expiry, TimeSource timeSource) { return newStore(null, null, expiry, timeSource); } @Override public Store newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, Expirations.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); } - private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, Expiry expiry, TimeSource timeSource) { + private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { Serializer keySerializer = new JavaSerializer<>(getClass().getClassLoader()); Serializer valueSerializer = new JavaSerializer<>(getClass().getClassLoader()); Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), diff --git a/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java b/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java index a9000f6ea3..f46b0c1fe8 100644 --- a/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java @@ -28,21 +28,20 @@ import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.event.EventType; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.Serializable; +import java.time.Duration; import java.util.EnumSet; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; @@ -245,7 +244,7 @@ public void testEventFiringInCacheIterator() { CacheConfiguration cacheConfiguration = newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder() .heap(5L, EntryUnit.ENTRIES).build()) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))) + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration) .using(new TimeSourceConfiguration(testTimeSource)) @@ -282,7 +281,7 @@ public void testMultiThreadedSyncAsyncNotifications() throws InterruptedExceptio CacheConfiguration cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class, newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))) + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration) diff --git a/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java b/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java index e4cbb83594..bed2718b2b 100644 --- a/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java +++ b/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java @@ -19,19 +19,18 @@ import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.hamcrest.Matchers; import org.junit.After; import org.junit.Before; import org.junit.Test; +import java.time.Duration; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.Map; -import java.util.concurrent.TimeUnit; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.hamcrest.Matchers.nullValue; @@ -53,7 +52,7 @@ public void setUp() throws Exception { CacheManagerBuilder builder = CacheManagerBuilder.newCacheManagerBuilder().using(new TimeSourceConfiguration(manualTimeSource)); cacheManager = builder.build(true); CacheConfigurationBuilder objectObjectCacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); testCache = cacheManager.createCache("testCache", objectObjectCacheConfigurationBuilder.build()); } diff --git a/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java b/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java index 8ae5a9b0ef..944edc1cfb 100644 --- a/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java @@ -21,17 +21,14 @@ import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.persistence.CacheManagerPersistenceConfiguration; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.event.CacheEvent; -import org.ehcache.event.CacheEventListener; import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.event.EventType; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.impl.copy.SerializingCopier; import org.junit.After; @@ -41,6 +38,7 @@ import org.junit.rules.TemporaryFolder; import java.io.IOException; +import java.time.Duration; import java.util.EnumSet; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; @@ -60,7 +58,7 @@ public class ExpiryEventsTest { private static final CacheConfigurationBuilder byRefCacheConfigBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); private static final CacheConfigurationBuilder byValueCacheConfigBuilder = byRefCacheConfigBuilder.add(new DefaultCopierConfiguration<>( diff --git a/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java b/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java index 58871de167..cb167c1add 100644 --- a/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java @@ -15,6 +15,7 @@ */ package org.ehcache.integration.statistics; +import java.time.Duration; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -29,8 +30,7 @@ import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.core.spi.service.StatisticsService; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.impl.internal.statistics.DefaultStatisticsService; @@ -65,7 +65,7 @@ public void before() throws Exception { CacheConfiguration cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, String.class, resources) - .withExpiry(Expirations.timeToLiveExpiration(Duration.of(TIME_TO_EXPIRATION, TimeUnit.MILLISECONDS))) + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); StatisticsService statisticsService = new DefaultStatisticsService(); diff --git a/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java b/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java index 9e145356fa..adf0477310 100644 --- a/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java @@ -25,8 +25,7 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.time.TimeSource; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.persistence.CacheManagerPersistenceConfiguration; import org.ehcache.impl.internal.DefaultTimeSourceService; @@ -47,6 +46,7 @@ import javax.transaction.Transaction; import java.io.File; import java.io.IOException; +import java.time.Duration; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @@ -273,7 +273,7 @@ public void testExpiry() throws Exception { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) @@ -431,7 +431,7 @@ public void testConcurrentTx() throws Exception { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) @@ -496,7 +496,7 @@ public void testAtomicsWithoutLoaderWriter() throws Exception { .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB) ) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) @@ -524,7 +524,7 @@ public void testAtomicsWithLoaderWriter() throws Exception { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))) + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))) .withLoaderWriter(loaderWriter); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() @@ -674,7 +674,7 @@ public void testIterate() throws Throwable { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS))); + .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) diff --git a/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java b/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java index af358598f5..1ffe623b81 100644 --- a/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java +++ b/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java @@ -23,8 +23,7 @@ import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.management.SharedManagementService; import org.ehcache.management.registry.DefaultManagementRegistryConfiguration; @@ -41,6 +40,7 @@ import java.io.FileNotFoundException; import java.io.IOException; +import java.time.Duration; import java.util.Collection; import java.util.Scanner; import java.util.concurrent.TimeUnit; @@ -77,7 +77,7 @@ public void test_standalone_ehcache() throws IOException { .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .disk(2, MemoryUnit.MB, true)) - .withExpiry(Expirations.noExpiration()) + .withExpiry(ExpiryPolicies.noExpiration()) .build(); CacheConfiguration cacheConfiguration2 = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, @@ -85,7 +85,7 @@ public void test_standalone_ehcache() throws IOException { .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .disk(2, MemoryUnit.MB, true)) - .withExpiry(Expirations.timeToIdleExpiration(Duration.of(2, TimeUnit.HOURS))) + .withExpiry(ExpiryPolicies.timeToIdleExpiration(Duration.ofHours(2))) .build(); // ehcache cache manager diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java index e451539d78..91ced047ba 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java @@ -25,9 +25,8 @@ import org.ehcache.core.internal.store.StoreSupport; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.time.TimeSourceService; @@ -55,6 +54,7 @@ import org.terracotta.context.ContextManager; import java.io.IOException; +import java.time.Duration; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -778,18 +778,18 @@ public Store createStore(Configuration storeConfig, ServiceCo } // expiry - final Expiry configuredExpiry = storeConfig.getExpiry(); - Expiry> expiry = new Expiry>() { + final ExpiryPolicy configuredExpiry = storeConfig.getExpiry(); + ExpiryPolicy> expiry = new ExpiryPolicy>() { @Override public Duration getExpiryForCreation(K key, SoftLock softLock) { if (softLock.getTransactionId() != null) { // phase 1 prepare, create -> forever - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } else { // phase 2 commit, or during a TX's lifetime, create -> some time Duration duration; try { - duration = configuredExpiry.getExpiryForCreation(key, (V) softLock.getOldValue()); + duration = configuredExpiry.getExpiryForCreation(key, softLock.getOldValue()); } catch (RuntimeException re) { LOGGER.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return Duration.ZERO; @@ -802,7 +802,7 @@ public Duration getExpiryForCreation(K key, SoftLock softLock) { public Duration getExpiryForAccess(K key, final ValueSupplier> softLock) { if (softLock.value().getTransactionId() != null) { // phase 1 prepare, access -> forever - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } else { // phase 2 commit, or during a TX's lifetime, access -> some time Duration duration; @@ -821,7 +821,7 @@ public Duration getExpiryForUpdate(K key, ValueSupplier> o SoftLock oldSoftLock = oldSoftLockSupplier.value(); if (oldSoftLock.getTransactionId() == null) { // phase 1 prepare, update -> forever - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } else { // phase 2 commit, or during a TX's lifetime if (oldSoftLock.getOldValue() == null) { diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java index 8338b374a1..05c07048e8 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java @@ -24,7 +24,7 @@ import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; -import org.ehcache.expiry.Expirations; +import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.transactions.xa.configuration.XAStoreConfiguration; import org.ehcache.transactions.xa.txmgr.btm.BitronixTransactionManagerLookup; import org.ehcache.transactions.xa.txmgr.provider.LookupTransactionManagerProviderConfiguration; @@ -63,7 +63,7 @@ public void testXAWithStatefulSerializer() throws Exception { CacheConfigurationBuilder .newCacheConfigurationBuilder(Long.class, Person.class, ResourcePoolsBuilder.heap(5)) - .withExpiry(Expirations.noExpiration()).add(new XAStoreConfiguration("xaCache")) + .withExpiry(ExpiryPolicies.noExpiration()).add(new XAStoreConfiguration("xaCache")) .build()) .build(true)) { diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java index 85ca31621c..3efdc84316 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java @@ -29,9 +29,8 @@ import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -62,6 +61,7 @@ import org.junit.Test; import org.junit.rules.TestName; +import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Collections; @@ -73,13 +73,9 @@ import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; @@ -94,10 +90,10 @@ import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; +import static java.time.Duration.ofSeconds; import static java.util.Collections.emptySet; import static org.ehcache.core.internal.service.ServiceLocator.dependencySet; -import static org.ehcache.expiry.Duration.of; -import static org.ehcache.expiry.Expirations.timeToLiveExpiration; +import static org.ehcache.expiry.ExpiryPolicies.timeToLiveExpiration; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -126,7 +122,7 @@ public class XAStoreTest { private Serializer keySerializer; private Serializer> valueSerializer; private StoreEventDispatcher> eventDispatcher; - private final Expiry expiry = timeToLiveExpiration(of(1, TimeUnit.SECONDS)); + private final ExpiryPolicy expiry = timeToLiveExpiration(ofSeconds(1)); private Copier keyCopier; private Copier> valueCopier; @@ -140,7 +136,7 @@ public void setUp() { keyCopier = copyProvider.createKeyCopier(Long.class, keySerializer); valueCopier = copyProvider.createValueCopier(valueClass, valueSerializer); Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, - null, classLoader, Expirations.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + null, classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .build(), 0, keySerializer, valueSerializer); @@ -695,7 +691,7 @@ public void testReplace3Args() throws Exception { @Test public void testCompute() throws Exception { Store.Configuration> offHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, - null, classLoader, Expirations.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + null, classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .offheap(10, MemoryUnit.MB) .build(), 0, keySerializer, valueSerializer); @@ -871,7 +867,7 @@ public void testCompute() throws Exception { @Test public void testComputeIfAbsent() throws Exception { Store.Configuration> offHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, - classLoader, Expirations.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .offheap(10, MemoryUnit.MB) .build(), 0, keySerializer, valueSerializer); @@ -955,7 +951,7 @@ public void testExpiry() throws Exception { @Test public void testExpiryCreateException() throws Exception { - Expiry expiry = new Expiry() { + ExpiryPolicy expiry = new ExpiryPolicy() { @Override public Duration getExpiryForCreation(Object key, Object value) { @@ -995,11 +991,11 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier o @Test public void testExpiryAccessException() throws Exception { String uniqueXAResourceId = "testExpiryAccessException"; - Expiry expiry = new Expiry() { + ExpiryPolicy expiry = new ExpiryPolicy() { @Override public Duration getExpiryForCreation(Object key, Object value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override @@ -1007,12 +1003,12 @@ public Duration getExpiryForAccess(Object key, ValueSupplier v if (testTimeSource.getTimeMillis() > 0) { throw new RuntimeException(); } - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } }; Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, @@ -1045,16 +1041,16 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier o @Test public void testExpiryUpdateException() throws Exception{ - Expiry expiry = new Expiry() { + ExpiryPolicy expiry = new ExpiryPolicy() { @Override public Duration getExpiryForCreation(Object key, Object value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override public Duration getExpiryForAccess(Object key, ValueSupplier value) { - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } @Override @@ -1062,7 +1058,7 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier o if (testTimeSource.getTimeMillis() > 0) { throw new RuntimeException(); } - return Duration.INFINITE; + return ExpiryPolicy.INFINITE; } }; Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, @@ -1094,7 +1090,7 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier o @Test public void testBulkCompute() throws Exception { String uniqueXAResourceId = "testBulkCompute"; - Expiry expiry = Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS)); + ExpiryPolicy expiry = ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1)); Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, classLoader, expiry, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build(), 0, keySerializer, valueSerializer); @@ -1170,7 +1166,7 @@ public void testBulkCompute() throws Exception { @Test public void testBulkComputeIfAbsent() throws Exception { - Expiry expiry = Expirations.timeToLiveExpiration(new Duration(1, TimeUnit.SECONDS)); + ExpiryPolicy expiry = ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1)); Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, classLoader, expiry, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build(), 0, keySerializer, valueSerializer); @@ -1241,7 +1237,7 @@ public void testCustomEvictionAdvisor() throws Exception { return false; }; Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, - evictionAdvisor, classLoader, Expirations.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + evictionAdvisor, classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .build(), 0, keySerializer, valueSerializer); diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java index b19a4a985e..37da508b91 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java @@ -16,13 +16,13 @@ package org.ehcache.transactions.xa.internal; -import org.ehcache.expiry.Duration; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; +import java.time.Duration; import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.is; @@ -38,7 +38,7 @@ public void testSerialization() throws Exception { long now = System.currentTimeMillis(); XAValueHolder valueHolder = new XAValueHolder<>("value", now - 1000); - valueHolder.accessed(now, new Duration(100, TimeUnit.SECONDS)); + valueHolder.accessed(now, Duration.ofSeconds(100)); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(baos); diff --git a/xml/src/main/java/org/ehcache/xml/ConfigurationParser.java b/xml/src/main/java/org/ehcache/xml/ConfigurationParser.java index 93005f1c8b..cd5ee57bec 100644 --- a/xml/src/main/java/org/ehcache/xml/ConfigurationParser.java +++ b/xml/src/main/java/org/ehcache/xml/ConfigurationParser.java @@ -18,7 +18,6 @@ import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourceUnit; -import org.ehcache.config.SizedResourcePool; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.SizedResourcePoolImpl; @@ -760,7 +759,7 @@ interface Expiry { long value(); - TimeUnit unit(); + TemporalUnit unit(); } @@ -914,7 +913,7 @@ public long value() { } @Override - public TimeUnit unit() { + public TemporalUnit unit() { final TimeType time; if(isTTI()) { time = type.getTti(); @@ -922,7 +921,7 @@ public TimeUnit unit() { time = type.getTtl(); } if(time != null) { - return XmlModel.convertToJUCTimeUnit(time.getUnit()); + return XmlModel.convertToJavaTemporalUnit(time.getUnit()); } return null; } diff --git a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java index 6dcc1f9f3b..2b152baa4f 100644 --- a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java +++ b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java @@ -27,13 +27,14 @@ import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.builders.WriteBehindConfigurationBuilder; import org.ehcache.config.builders.WriteBehindConfigurationBuilder.BatchedWriteBehindConfigurationBuilder; +import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.internal.util.ClassLoading; import org.ehcache.event.CacheEventListener; import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; import org.ehcache.impl.config.event.CacheEventDispatcherFactoryConfiguration; @@ -71,6 +72,7 @@ import java.io.File; import java.io.IOException; import java.net.URL; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -329,17 +331,23 @@ private void parseConfiguration() } @SuppressWarnings("unchecked") - private Expiry getExpiry(ClassLoader cacheClassLoader, ConfigurationParser.Expiry parsedExpiry) + private ExpiryPolicy getExpiry(ClassLoader cacheClassLoader, ConfigurationParser.Expiry parsedExpiry) throws ClassNotFoundException, InstantiationException, IllegalAccessException { - final Expiry expiry; + final ExpiryPolicy expiry; if (parsedExpiry.isUserDef()) { - expiry = getInstanceOfName(parsedExpiry.type(), cacheClassLoader, Expiry.class); + ExpiryPolicy tmpExpiry; + try { + tmpExpiry = getInstanceOfName(parsedExpiry.type(), cacheClassLoader, ExpiryPolicy.class); + } catch (ClassCastException e) { + tmpExpiry = ExpiryUtils.convertToExpiryPolicy(getInstanceOfName(parsedExpiry.type(), cacheClassLoader, Expiry.class)); + } + expiry = tmpExpiry; } else if (parsedExpiry.isTTL()) { - expiry = Expirations.timeToLiveExpiration(new Duration(parsedExpiry.value(), parsedExpiry.unit())); + expiry = ExpiryPolicies.timeToLiveExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit())); } else if (parsedExpiry.isTTI()) { - expiry = Expirations.timeToIdleExpiration(new Duration(parsedExpiry.value(), parsedExpiry.unit())); + expiry = ExpiryPolicies.timeToIdleExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit())); } else { - expiry = Expirations.noExpiration(); + expiry = ExpiryPolicies.noExpiration(); } return expiry; } diff --git a/xml/src/main/java/org/ehcache/xml/XmlModel.java b/xml/src/main/java/org/ehcache/xml/XmlModel.java index d6e648f252..136a9577dd 100644 --- a/xml/src/main/java/org/ehcache/xml/XmlModel.java +++ b/xml/src/main/java/org/ehcache/xml/XmlModel.java @@ -61,4 +61,26 @@ public static TimeUnit convertToJUCTimeUnit(org.ehcache.xml.model.TimeUnit unit) throw new IllegalArgumentException("Unknown time unit: " + unit); } } + + public static TemporalUnit convertToJavaTemporalUnit(org.ehcache.xml.model.TimeUnit unit) { + switch (unit) { + case NANOS: + return ChronoUnit.NANOS; + case MICROS: + return ChronoUnit.MICROS; + case MILLIS: + return ChronoUnit.MILLIS; + case SECONDS: + return ChronoUnit.SECONDS; + case MINUTES: + return ChronoUnit.MINUTES; + case HOURS: + return ChronoUnit.HOURS; + case DAYS: + return ChronoUnit.DAYS; + default: + throw new IllegalArgumentException("Unknown time unit: " + unit); + } + } + } diff --git a/xml/src/main/resources/ehcache-core.xsd b/xml/src/main/resources/ehcache-core.xsd index 90d9eba8de..e1b60d2c6a 100644 --- a/xml/src/main/resources/ehcache-core.xsd +++ b/xml/src/main/resources/ehcache-core.xsd @@ -413,7 +413,7 @@ A fully qualified class name to a concrete type that implements - org.ehcache.expiry.Expiry and has a public default no argument constructor. + org.ehcache.expiry.ExpiryPolicy and has a public default no argument constructor. diff --git a/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java b/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java new file mode 100644 index 0000000000..ed99132cf6 --- /dev/null +++ b/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java @@ -0,0 +1,43 @@ +/* + * Copyright Terracotta, Inc. + * + * 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.pany.ehcache; + +import org.ehcache.ValueSupplier; +import org.ehcache.expiry.Duration; +import org.ehcache.expiry.Expiry; + +import java.util.concurrent.TimeUnit; + +/** + * @author Alex Snaps + */ +public class DeprecatedExpiry implements Expiry { + @Override + public Duration getExpiryForCreation(final Object key, final Object value) { + return Duration.of(42, TimeUnit.SECONDS); + } + + @Override + public Duration getExpiryForAccess(final Object key, final ValueSupplier value) { + return Duration.of(42, TimeUnit.SECONDS); + } + + @Override + public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + return Duration.of(42, TimeUnit.SECONDS); + } +} diff --git a/xml/src/test/java/com/pany/ehcache/MyExpiry.java b/xml/src/test/java/com/pany/ehcache/MyExpiry.java index c01a94dc65..99e793fd1d 100644 --- a/xml/src/test/java/com/pany/ehcache/MyExpiry.java +++ b/xml/src/test/java/com/pany/ehcache/MyExpiry.java @@ -17,27 +17,26 @@ package com.pany.ehcache; import org.ehcache.ValueSupplier; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; -import java.util.concurrent.TimeUnit; +import java.time.Duration; /** * @author Alex Snaps */ -public class MyExpiry implements Expiry { +public class MyExpiry implements ExpiryPolicy { @Override public Duration getExpiryForCreation(final Object key, final Object value) { - return new Duration(42, TimeUnit.SECONDS); + return Duration.ofSeconds(42); } @Override public Duration getExpiryForAccess(final Object key, final ValueSupplier value) { - return new Duration(42, TimeUnit.SECONDS); + return Duration.ofSeconds(42); } @Override public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { - return new Duration(42, TimeUnit.SECONDS); + return Duration.ofSeconds(42); } } diff --git a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java index aa2c9adb61..2a335a4178 100644 --- a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java +++ b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java @@ -24,9 +24,8 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.internal.util.ClassLoading; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; import org.ehcache.impl.config.event.DefaultCacheEventListenerConfiguration; @@ -70,6 +69,7 @@ import java.io.File; import java.net.URL; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -189,8 +189,8 @@ public void testOneCacheConfigWithTemplate() throws Exception { final CacheConfigurationBuilder example = xmlConfig.newCacheConfigurationBuilderFromTemplate("example", String.class, String.class, newResourcePoolsBuilder().heap(5, EntryUnit.ENTRIES)); - assertThat(example.build().getExpiry(), - equalTo((Expiry) Expirations.timeToLiveExpiration(new Duration(30, TimeUnit.SECONDS)))); + assertThat(example.build().getExpiryPolicy(), + equalTo((ExpiryPolicy) ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(30)))); try { xmlConfig.newCacheConfigurationBuilderFromTemplate("example", String.class, Number.class); @@ -212,23 +212,28 @@ public void testOneCacheConfigWithTemplate() throws Exception { public void testExpiryIsParsed() throws Exception { final XmlConfiguration xmlConfiguration = new XmlConfiguration(XmlConfigurationTest.class.getResource("/configs/expiry-caches.xml")); - Expiry expiry = xmlConfiguration.getCacheConfigurations().get("none").getExpiry(); - Expiry value = Expirations.noExpiration(); + ExpiryPolicy expiry = xmlConfiguration.getCacheConfigurations().get("none").getExpiryPolicy(); + ExpiryPolicy value = ExpiryPolicies.noExpiration(); assertThat(expiry, is(value)); - expiry = xmlConfiguration.getCacheConfigurations().get("notSet").getExpiry(); - value = Expirations.noExpiration(); + expiry = xmlConfiguration.getCacheConfigurations().get("notSet").getExpiryPolicy(); + value = ExpiryPolicies.noExpiration(); assertThat(expiry, is(value)); - expiry = xmlConfiguration.getCacheConfigurations().get("class").getExpiry(); + expiry = xmlConfiguration.getCacheConfigurations().get("class").getExpiryPolicy(); assertThat(expiry, CoreMatchers.instanceOf(com.pany.ehcache.MyExpiry.class)); - expiry = xmlConfiguration.getCacheConfigurations().get("tti").getExpiry(); - value = Expirations.timeToIdleExpiration(new Duration(500, TimeUnit.MILLISECONDS)); + expiry = xmlConfiguration.getCacheConfigurations().get("deprecatedClass").getExpiryPolicy(); + assertThat(expiry.getExpiryForCreation(null, null), is(Duration.ofSeconds(42))); + assertThat(expiry.getExpiryForAccess(null, null), is(Duration.ofSeconds(42))); + assertThat(expiry.getExpiryForUpdate(null, null, null), is(Duration.ofSeconds(42))); + + expiry = xmlConfiguration.getCacheConfigurations().get("tti").getExpiryPolicy(); + value = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(500)); assertThat(expiry, equalTo(value)); - expiry = xmlConfiguration.getCacheConfigurations().get("ttl").getExpiry(); - value = Expirations.timeToLiveExpiration(new Duration(30, TimeUnit.SECONDS)); + expiry = xmlConfiguration.getCacheConfigurations().get("ttl").getExpiryPolicy(); + value = ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(30)); assertThat(expiry, equalTo(value)); } diff --git a/xml/src/test/resources/configs/expiry-caches.xml b/xml/src/test/resources/configs/expiry-caches.xml index c23f4a4eed..84b3771ed7 100644 --- a/xml/src/test/resources/configs/expiry-caches.xml +++ b/xml/src/test/resources/configs/expiry-caches.xml @@ -28,6 +28,15 @@ 5 + + java.lang.String + java.lang.String + + com.pany.ehcache.DeprecatedExpiry + + 5 + + java.lang.String java.lang.String From 5feeb52b61a28ff9ea23c01eb0155286fa7aaf70 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Tue, 12 Dec 2017 21:08:57 +0100 Subject: [PATCH 070/779] Fix #2068 Move expiry builders in the regular builders package Still left a NO_EXPIRY field in the ExpiryPolicy interface cause it gets used a lot internally. --- .../ParsesConfigurationExtensionTest.java | 2 +- .../jsr107/ConfigurationMergerTest.java | 4 +- .../java/org/ehcache/expiry/Expirations.java | 8 +- .../java/org/ehcache/expiry/ExpiryPolicy.java | 44 +++-- .../client/internal/store/ClusteredStore.java | 4 +- .../client/BasicClusteredCacheExpiryTest.java | 4 +- .../client/ClusteredCacheExpirationTest.java | 6 +- ...ClusterStateRepositoryReplicationTest.java | 2 +- .../StateRepositoryWhitelistingTest.java | 2 +- .../store/ClusteredStoreProviderTest.java | 4 +- .../internal/store/ClusteredStoreTest.java | 1 - .../operations/ExpiryChainResolverTest.java | 64 +++---- .../org/ehcache/internal/TestExpiries.java | 85 +++++++++ .../store/StoreComputeIfAbsentTest.java | 5 +- .../internal/store/StoreComputeTest.java | 7 +- .../store/StoreExpiryEventListenerTest.java | 4 +- .../ehcache/internal/store/StoreGetTest.java | 5 +- .../internal/store/StorePutIfAbsentTest.java | 6 +- .../ehcache/internal/store/StorePutTest.java | 8 +- .../tier/AuthoritativeTierGetAndFault.java | 4 +- .../core/EhcacheRuntimeConfiguration.java | 12 +- .../core/config/BaseCacheConfiguration.java | 3 +- .../core/EhcacheBasicPutIfAbsentTest.java | 4 +- ...eWithLoaderWriterBasicPutIfAbsentTest.java | 3 +- ...cacheWithLoaderWriterBasicReplaceTest.java | 3 +- ...WithLoaderWriterBasicReplaceValueTest.java | 3 +- .../config/builders/ExpiryPolicyBuilder.java | 180 ++++++++---------- .../builders/UserManagedCacheBuilder.java | 3 +- .../CacheConfigurationBuilderTest.java | 5 +- .../builders/ExpiryPolicyBuilderTest.java | 20 +- .../builders/UserManagedCacheBuilderTest.java | 3 +- .../java/org/ehcache/docs/GettingStarted.java | 4 +- .../PooledExecutorWriteBehindTest.java | 4 +- .../writebehind/WriteBehindEvictionTest.java | 4 +- .../writebehind/WriteBehindTest.java | 4 +- .../DefaultCacheStatisticsTest.java | 4 +- .../statistics/DefaultTierStatisticsTest.java | 4 +- .../disk/OffHeapDiskStoreProviderTest.java | 4 +- .../store/disk/OffHeapDiskStoreSPITest.java | 8 +- .../store/disk/OffHeapDiskStoreTest.java | 2 +- .../store/heap/BaseOnHeapStoreTest.java | 54 +++--- .../ByteSizedOnHeapStoreByRefSPITest.java | 8 +- .../ByteSizedOnHeapStoreByValueSPITest.java | 8 +- .../heap/OnHeapStoreBulkMethodsTest.java | 6 +- .../store/heap/OnHeapStoreByRefSPITest.java | 8 +- .../store/heap/OnHeapStoreByValueSPITest.java | 8 +- .../store/heap/OnHeapStoreByValueTest.java | 4 +- .../OnHeapStoreCachingTierByRefSPITest.java | 4 +- .../OnHeapStoreCachingTierByValueSPITest.java | 4 +- .../store/heap/OnHeapStoreEvictionTest.java | 6 +- .../store/heap/OnHeapStoreKeyCopierTest.java | 4 +- .../heap/OnHeapStoreValueCopierTest.java | 4 +- .../heap/bytesized/ByteAccountingTest.java | 32 ++-- .../bytesized/OnHeapStoreBulkMethodsTest.java | 6 +- .../OnHeapStoreCachingTierByRefSPITest.java | 4 +- .../OnHeapStoreCachingTierByValueSPITest.java | 4 +- .../bytesized/OnHeapStoreEvictionTest.java | 4 +- .../heap/bytesized/OversizeMappingTest.java | 4 +- .../offheap/AbstractOffHeapStoreTest.java | 49 ++--- .../store/offheap/OffHeapStoreSPITest.java | 8 +- .../tiering/CompoundCachingTierSPITest.java | 4 +- .../TieredStoreFlushWhileShutdownTest.java | 4 +- .../store/tiering/TieredStoreMutatorTest.java | 4 +- .../store/tiering/TieredStoreSPITest.java | 8 +- .../tiering/TieredStoreWith3TiersSPITest.java | 8 +- .../integration/EventNotificationTest.java | 6 +- .../integration/ExpiryEhcacheTestBase.java | 4 +- .../ehcache/integration/ExpiryEventsTest.java | 5 +- .../statistics/TierCalculationTest.java | 5 +- .../transactions/xa/XACacheTest.java | 13 +- .../settings/EhcacheSettingsProviderTest.java | 7 +- .../integration/StatefulSerializerTest.java | 4 +- .../transactions/xa/internal/XAStoreTest.java | 16 +- .../org/ehcache/xml/XmlConfiguration.java | 8 +- .../org/ehcache/xml/XmlConfigurationTest.java | 13 +- 75 files changed, 486 insertions(+), 398 deletions(-) create mode 100644 core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java rename api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java => impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java (50%) rename api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java => impl/src/test/java/org/ehcache/config/builders/ExpiryPolicyBuilderTest.java (77%) diff --git a/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java b/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java index 060633ba13..b35e19064c 100644 --- a/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java +++ b/107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java @@ -83,7 +83,7 @@ public void testXmlExample() throws ClassNotFoundException, SAXException, Instan assertThat(runtimeConfiguration.getResourcePools().getPoolForResource(ResourceType.Core.HEAP).getSize(), equalTo(200L)); final ExpiryPolicy expiry = runtimeConfiguration.getExpiryPolicy(); - assertThat(expiry.getClass().getName(), equalTo("org.ehcache.expiry.ExpiryPolicies$TimeToIdleExpiryPolicy")); + assertThat(expiry.getClass().getName(), equalTo("org.ehcache.config.builders.ExpiryPolicyBuilder$TimeToIdleExpiryPolicy")); assertThat(expiry.getExpiryForAccess(42L, null), equalTo(Duration.ofMinutes(2))); assertThat(runtimeConfiguration.getEvictionAdvisor(), instanceOf(com.pany.ehcache.MyEvictionAdvisor.class)); diff --git a/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java b/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java index 6226a26293..9f091a4535 100644 --- a/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java +++ b/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java @@ -17,8 +17,8 @@ package org.ehcache.jsr107; import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.spi.service.ServiceUtils; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; @@ -163,7 +163,7 @@ public void loadsTemplateWhenNameFound() throws Exception { public void jsr107ExpiryGetsOverriddenByTemplate() throws Exception { when(jsr107Service.getTemplateNameForCache("cache")).thenReturn("cacheTemplate"); when(xmlConfiguration.newCacheConfigurationBuilderFromTemplate("cacheTemplate", Object.class, Object.class)).thenReturn( - newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMinutes(5))) + newCacheConfigurationBuilder(Object.class, Object.class, heap(10)).withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMinutes(5))) ); MutableConfiguration configuration = new MutableConfiguration<>(); diff --git a/api/src/main/java/org/ehcache/expiry/Expirations.java b/api/src/main/java/org/ehcache/expiry/Expirations.java index b4b79fb4b6..ef6c711d12 100644 --- a/api/src/main/java/org/ehcache/expiry/Expirations.java +++ b/api/src/main/java/org/ehcache/expiry/Expirations.java @@ -30,7 +30,7 @@ public final class Expirations { * * @return the no expiry instance * - * @deprecated Use {@link ExpiryPolicies#noExpiration()} instead + * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#noExpiration()} instead */ @Deprecated public static Expiry noExpiration() { @@ -43,7 +43,7 @@ public static Expiry noExpiration() { * @param timeToLive the TTL duration * @return a TTL expiry * - * @deprecated Use {@link ExpiryPolicies#timeToLiveExpiration(java.time.Duration)} instead + * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#timeToLiveExpiration(java.time.Duration)} instead */ @Deprecated public static Expiry timeToLiveExpiration(Duration timeToLive) { @@ -59,7 +59,7 @@ public static Expiry timeToLiveExpiration(Duration timeToLive) { * @param timeToIdle the TTI duration * @return a TTI expiry * - * @deprecated Use {@link ExpiryPolicies#timeToIdleExpiration(java.time.Duration)} instead + * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#timeToIdleExpiration(java.time.Duration)} instead */ @Deprecated public static Expiry timeToIdleExpiration(Duration timeToIdle) { @@ -78,7 +78,7 @@ public static Expiry timeToIdleExpiration(Duration timeToIdle) { * @param the value type for the cache * @return an {@link Expiry} builder * - * @deprecated Use {@link ExpiryPolicies#builder()} instead + * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#expiry()} instead */ @Deprecated public static ExpiryBuilder builder() { diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java index 0fe4b7a4eb..6324c5a731 100644 --- a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java +++ b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java @@ -27,26 +27,44 @@ * to indicate that access can require computation (such as deserialization). *

* {@link Duration#isNegative() Negative duration} are not supported, expiry policy implementation returning such a - * duration will result in immediate expiry, as if the duration was {@link java.time.Duration#ZERO zero}. + * duration will result in immediate expiry, as if the duration was {@link Duration#ZERO zero}. *

* NOTE: Some cache configurations (eg. caches with eventual consistency) may use local (ie. non-consistent) state * to decide whether to call {@link #getExpiryForUpdate(Object, ValueSupplier, Object)} vs. * {@link #getExpiryForCreation(Object, Object)}. For these cache configurations it is advised to return the same * value for both of these methods *

- * See {@link ExpiryPolicies} for helper methods to create common {@code ExpiryPolicy} instances. * * @param the key type for the cache * @param the value type for the cache * - * @see ExpiryPolicies */ public interface ExpiryPolicy { /** - * A {@link java.time.Duration duration} that represents an infinite time. + * A {@link Duration duration} that represents an infinite time. */ - java.time.Duration INFINITE = java.time.Duration.ofSeconds(Long.MAX_VALUE); + Duration INFINITE = Duration.ofSeconds(Long.MAX_VALUE); + + /** + * An {@code ExpiryPolicy} that represents a no expiration policy + */ + ExpiryPolicy NO_EXPIRY = new ExpiryPolicy() { + @Override + public Duration getExpiryForCreation(Object key, Object value) { + return INFINITE; + } + + @Override + public Duration getExpiryForAccess(Object key, ValueSupplier value) { + return null; + } + + @Override + public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + return null; + } + }; /** * Returns the lifetime of an entry when it is initially added to a {@link org.ehcache.Cache Cache}. @@ -54,44 +72,44 @@ public interface ExpiryPolicy { * This method must not return {@code null}. *

* Exceptions thrown from this method will be swallowed and result in the expiry duration being - * {@link java.time.Duration#ZERO ZERO}. + * {@link Duration#ZERO ZERO}. * * @param key the key of the newly added entry * @param value the value of the newly added entry * @return a non-null {@code Duration} */ - java.time.Duration getExpiryForCreation(K key, V value); + Duration getExpiryForCreation(K key, V value); /** - * Returns the expiration {@link java.time.Duration duration} (relative to the current time) when an existing entry + * Returns the expiration {@link Duration duration} (relative to the current time) when an existing entry * is accessed from a {@link org.ehcache.Cache Cache}. *

* Returning {@code null} indicates that the expiration time remains unchanged. *

* Exceptions thrown from this method will be swallowed and result in the expiry duration being - * {@link java.time.Duration#ZERO ZERO}. + * {@link Duration#ZERO ZERO}. * * @param key the key of the accessed entry * @param value a value supplier for the accessed entry * @return an expiration {@code Duration}, {@code null} means unchanged */ - java.time.Duration getExpiryForAccess(K key, ValueSupplier value); + Duration getExpiryForAccess(K key, ValueSupplier value); /** - * Returns the expiration {@link java.time.Duration duration} (relative to the current time) when an existing entry + * Returns the expiration {@link Duration duration} (relative to the current time) when an existing entry * is updated in a {@link org.ehcache.Cache Cache}. *

* Returning {@code null} indicates that the expiration time remains unchanged. *

* Exceptions thrown from this method will be swallowed and result in the expiry duration being - * {@link java.time.Duration#ZERO ZERO}. + * {@link Duration#ZERO ZERO}. * * @param key the key of the updated entry * @param oldValue a value supplier for the previous value of the entry * @param newValue the new value of the entry * @return an expiration {@code Duration}, {@code null} means unchanged */ - java.time.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue); + Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue); } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java index 56854debc3..5cfbd0a75b 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java @@ -37,6 +37,7 @@ import org.ehcache.clustered.common.Consistency; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.config.ResourceType; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.CacheConfigurationChangeListener; import org.ehcache.core.Ehcache; import org.ehcache.core.events.CacheEventListenerConfiguration; @@ -52,7 +53,6 @@ import org.ehcache.core.spi.time.TimeSourceService; import org.ehcache.core.statistics.StoreOperationOutcomes.EvictionOutcome; import org.ehcache.core.statistics.TierOperationOutcomes; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -634,7 +634,7 @@ private ClusteredStore createStoreInternal(Configuration stor ChainResolver resolver; ExpiryPolicy expiry = storeConfig.getExpiry(); - if (ExpiryPolicies.noExpiration().equals(expiry)) { + if (ExpiryPolicyBuilder.noExpiration().equals(expiry)) { resolver = new EternalChainResolver<>(codec); } else { resolver = new ExpiryChainResolver<>(codec, expiry); diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/BasicClusteredCacheExpiryTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/BasicClusteredCacheExpiryTest.java index 758446a373..7d88e1f4ea 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/BasicClusteredCacheExpiryTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/BasicClusteredCacheExpiryTest.java @@ -23,9 +23,9 @@ import org.ehcache.clustered.client.internal.UnitTestConnectionService; import org.ehcache.clustered.common.Consistency; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.junit.After; import org.junit.Before; @@ -53,7 +53,7 @@ public class BasicClusteredCacheExpiryTest { .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB))) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1L))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1L))) .add(ClusteredStoreConfigurationBuilder.withConsistency(Consistency.STRONG))); @Before diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/ClusteredCacheExpirationTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/ClusteredCacheExpirationTest.java index 43197a484e..494ca3c17b 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/ClusteredCacheExpirationTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/ClusteredCacheExpirationTest.java @@ -24,12 +24,12 @@ import org.ehcache.clustered.client.internal.UnitTestConnectionService; import org.ehcache.clustered.common.Consistency; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.service.StatisticsService; import org.ehcache.core.statistics.TierStatistics; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.impl.internal.statistics.DefaultStatisticsService; @@ -70,7 +70,7 @@ private CacheManagerBuilder cacheManagerBuilder(ExpiryPo } private ExpiryPolicy oneSecondExpiration() { - return ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1)); + return ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1)); } @Before @@ -117,7 +117,7 @@ public void testGetExpirationPropagatedToHigherTiers() throws CachePersistenceEx @Test public void testGetNoExpirationPropagatedToHigherTiers() throws CachePersistenceException { - CacheManagerBuilder clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicies.noExpiration()); + CacheManagerBuilder clusteredCacheManagerBuilder = cacheManagerBuilder(ExpiryPolicyBuilder.noExpiration()); try(PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true)) { diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java index 3c82a07808..d272f45a5b 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java @@ -48,8 +48,8 @@ import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.Eviction.noAdvice; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; -import static org.ehcache.expiry.ExpiryPolicies.noExpiration; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java index 24c1b46934..86c392aa60 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java @@ -48,8 +48,8 @@ import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.Eviction.noAdvice; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; -import static org.ehcache.expiry.ExpiryPolicies.noExpiration; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java index 193046e7f6..9d53056236 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreProviderTest.java @@ -25,12 +25,12 @@ import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.config.ResourcePoolsImpl; import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.store.disk.OffHeapDiskStore; import org.ehcache.impl.internal.store.heap.OnHeapStore; @@ -169,7 +169,7 @@ public ClassLoader getClassLoader() { @Override public ExpiryPolicy getExpiry() { - return ExpiryPolicies.noExpiration(); + return ExpiryPolicyBuilder.noExpiration(); } @Override diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java index 82441274d0..b7e041a94b 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java @@ -35,7 +35,6 @@ import org.ehcache.core.spi.store.StoreAccessTimeoutException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.statistics.StoreOperationOutcomes; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.store.HashUtils; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java index d2edfb7792..c7f57c7858 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverTest.java @@ -21,7 +21,7 @@ import org.ehcache.clustered.client.internal.store.operations.codecs.OperationsCodec; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.clustered.common.internal.store.Element; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.impl.serialization.LongSerializer; import org.ehcache.impl.serialization.StringSerializer; import org.hamcrest.Description; @@ -57,7 +57,7 @@ public void testResolveMaintainsOtherKeysInOrder() throws Exception { new PutOperation<>(2L, "Suresh", 0L), new PutOperation<>(2L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -74,7 +74,7 @@ public void testResolveMaintainsOtherKeysInOrder() throws Exception { @Test public void testResolveEmptyChain() throws Exception { Chain chain = getChainFromOperations(); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -89,7 +89,7 @@ public void testResolveChainWithNonExistentKey() throws Exception { new PutOperation<>(2L, "Suresh", 0L), new PutOperation<>(2L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 3L, 0L); Result result = resolvedChain.getResolvedResult(3L); assertNull(result); @@ -101,7 +101,7 @@ public void testResolveSinglePut() throws Exception { Operation expected = new PutOperation<>(1L, "Albin", 0L); Chain chain = getChainFromOperations(expected); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -117,7 +117,7 @@ public void testResolvePutsOnly() throws Exception { new PutOperation<>(1L, "Suresh", 0L), new PutOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -129,7 +129,7 @@ public void testResolvePutsOnly() throws Exception { public void testResolveSingleRemove() throws Exception { Chain chain = getChainFromOperations(new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -143,7 +143,7 @@ public void testResolveRemovesOnly() throws Exception { new RemoveOperation<>(1L, 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -157,7 +157,7 @@ public void testPutAndRemove() throws Exception { new PutOperation<>(1L, "Albin", 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertNull(result); @@ -169,7 +169,7 @@ public void testResolvePutIfAbsentOnly() throws Exception { Operation expected = new PutOperation<>(1L, "Mathew", 0L); Chain chain = getChainFromOperations(new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -184,7 +184,7 @@ public void testResolvePutIfAbsentsOnly() throws Exception { new PutIfAbsentOperation<>(1L, "Suresh", 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -199,7 +199,7 @@ public void testResolvePutIfAbsentSucceeds() throws Exception { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); Result result = resolvedChain.getResolvedResult(1L); assertEquals(expected, result); @@ -210,7 +210,7 @@ public void testResolvePutIfAbsentSucceeds() throws Exception { public void testResolveForSingleOperationDoesNotCompact() { Chain chain = getChainFromOperations(new PutOperation<>(1L, "Albin", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); assertThat(resolvedChain.isCompacted(), is(false)); assertThat(resolvedChain.getCompactionCount(), is(0)); @@ -232,7 +232,7 @@ public void testResolveForMultiplesOperationsAlwaysCompact() { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(2L, "Albin", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 0L); assertThat(resolvedChain.isCompacted(), is(true)); assertThat(resolvedChain.getCompactionCount(), is(8)); @@ -246,7 +246,7 @@ public void testResolveForMultipleOperationHasCorrectIsFirstAndTimeStamp() { new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "AlbinAfterRemove", 3)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.timeToLiveExpiration(Duration.ofHours(1))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofHours(1))); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 3); Operation operation = codec.decode(resolvedChain.getCompactedChain().iterator().next().getPayload()); @@ -271,7 +271,7 @@ public void testResolveForMultipleOperationHasCorrectIsFirstAndTimeStampWithExpi new PutOperation<>(1L, "Albin4", 3L) ); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1L))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1L))); ResolvedChain resolvedChain = resolver.resolve(chain, 1L, 3L); Operation operation = codec.decode(resolvedChain.getCompactedChain().iterator().next().getPayload()); @@ -298,7 +298,7 @@ public void testResolveDoesNotDecodeOtherKeyOperationValues() throws Exception { CountingLongSerializer keySerializer = new CountingLongSerializer(); CountingStringSerializer valueSerializer = new CountingStringSerializer(); OperationsCodec customCodec = new OperationsCodec<>(keySerializer, valueSerializer); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicies.timeToIdleExpiration(Duration.ofSeconds(5))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(5))); resolver.resolve(chain, 1L, 0L); assertThat(keySerializer.decodeCount, is(3)); @@ -317,7 +317,7 @@ public void testResolveDecodesOperationValueOnlyOnDemand() throws Exception { CountingLongSerializer keySerializer = new CountingLongSerializer(); CountingStringSerializer valueSerializer = new CountingStringSerializer(); OperationsCodec customCodec = new OperationsCodec<>(keySerializer, valueSerializer); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicies.timeToIdleExpiration(Duration.ofSeconds(5))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(5))); resolver.resolve(chain, 1L, 0L); assertThat(keySerializer.decodeCount, is(3)); @@ -336,7 +336,7 @@ public void testCompactingTwoKeys() throws Exception { new PutOperation<>(2L, "Suresh", 0L), new PutOperation<>(2L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); @@ -349,7 +349,7 @@ public void testCompactingTwoKeys() throws Exception { @Test public void testCompactEmptyChain() throws Exception { Chain chain = (new ChainBuilder()).build(); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compacted = resolver.applyOperation(chain, 0L); assertThat(compacted, emptyIterable()); } @@ -360,7 +360,7 @@ public void testCompactSinglePut() throws Exception { new PutOperation<>(1L, "Albin", 0L) ); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compacted = resolver.applyOperation(chain, 0L); assertThat(compacted, contains(operation(new PutOperation<>(1L, "Albin", 0L)))); @@ -373,7 +373,7 @@ public void testCompactMultiplePuts() throws Exception { new PutOperation<>(1L, "Suresh", 0L), new PutOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Mathew", 0L)))); } @@ -382,7 +382,7 @@ public void testCompactMultiplePuts() throws Exception { public void testCompactSingleRemove() throws Exception { Chain chain = getChainFromOperations(new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, emptyIterable()); } @@ -393,7 +393,7 @@ public void testCompactMultipleRemoves() throws Exception { new RemoveOperation<>(1L, 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, emptyIterable()); } @@ -404,7 +404,7 @@ public void testCompactPutAndRemove() throws Exception { new PutOperation<>(1L, "Albin", 0L), new RemoveOperation<>(1L, 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, emptyIterable()); } @@ -413,7 +413,7 @@ public void testCompactPutAndRemove() throws Exception { public void testCompactSinglePutIfAbsent() throws Exception { Chain chain = getChainFromOperations(new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Mathew", 0L)))); } @@ -425,7 +425,7 @@ public void testCompactMultiplePutIfAbsents() throws Exception { new PutIfAbsentOperation<>(1L, "Suresh", 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin", 0L)))); } @@ -437,7 +437,7 @@ public void testCompactPutIfAbsentAfterRemove() throws Exception { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(1L, "Mathew", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Mathew", 0L)))); } @@ -458,7 +458,7 @@ public void testCompactForMultipleKeysAndOperations() { new RemoveOperation<>(1L, 0L), new PutIfAbsentOperation<>(2L, "Albin", 0L)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 0L); assertThat(compactedChain, contains(operation(new PutOperation<>(2L, "Albin", 0L)))); } @@ -471,7 +471,7 @@ public void testCompactHasCorrectTimeStamp() { new RemoveOperation<>(1L, 2), new PutOperation<>(1L, "Albin3", 3)); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.noExpiration()); Chain compactedChain = resolver.applyOperation(chain, 3); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin3", 3)))); @@ -486,7 +486,7 @@ public void testCompactHasCorrectWithExpiry() { new PutOperation<>(1L, "Albin4", 3L) ); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1L))); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(codec, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1L))); Chain compactedChain = resolver.applyOperation(chain, 3L); assertThat(compactedChain, contains(operation(new PutOperation<>(1L, "Albin4", 3L)))); @@ -502,7 +502,7 @@ public void testCompactDecodesOperationValueOnlyOnDemand() throws Exception { CountingLongSerializer keySerializer = new CountingLongSerializer(); CountingStringSerializer valueSerializer = new CountingStringSerializer(); OperationsCodec customCodec = new OperationsCodec<>(keySerializer, valueSerializer); - ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicies.noExpiration()); + ExpiryChainResolver resolver = new ExpiryChainResolver<>(customCodec, ExpiryPolicyBuilder.noExpiration()); resolver.applyOperation(chain, 0L); assertThat(keySerializer.decodeCount, is(3)); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java b/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java new file mode 100644 index 0000000000..1ac7fba865 --- /dev/null +++ b/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java @@ -0,0 +1,85 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.internal; + +import org.ehcache.ValueSupplier; +import org.ehcache.expiry.ExpiryPolicy; + +import java.time.Duration; + +/** + * TestExpiries + */ +public class TestExpiries { + + public static ExpiryPolicy tTI(Duration duration) { + return new ExpiryPolicy() { + @Override + public Duration getExpiryForCreation(K key, V value) { + return duration; + } + + @Override + public Duration getExpiryForAccess(K key, ValueSupplier value) { + return duration; + } + + @Override + public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + return duration; + } + }; + } + + public static ExpiryPolicy tTL(Duration duration) { + return new ExpiryPolicy() { + @Override + public Duration getExpiryForCreation(K key, V value) { + return duration; + } + + @Override + public Duration getExpiryForAccess(K key, ValueSupplier value) { + return null; + } + + @Override + public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + return duration; + } + }; + } + + public static ExpiryPolicy custom(Duration creation, Duration access, Duration update) { + return new ExpiryPolicy() { + @Override + public Duration getExpiryForCreation(K key, V value) { + return creation; + } + + @Override + public Duration getExpiryForAccess(K key, ValueSupplier value) { + return access; + } + + @Override + public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + return update; + } + }; + } +} diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java index a01dc5eca8..b12916a0dc 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java @@ -17,7 +17,8 @@ import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; @@ -199,7 +200,7 @@ public void testException() throws Exception { @SPITest public void testComputeIfAbsentValuePresentExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(ExpiryPolicy.INFINITE, Duration.ZERO, null), timeSource); K key = factory.createKey(250928L); V value = factory.createValue(2059820L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java index 1bd5dc40cc..fcd632d07f 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java @@ -17,7 +17,8 @@ import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; @@ -193,7 +194,7 @@ public void testException() throws Exception { @SPITest public void testComputeExpiresOnAccess() throws Exception { TestTimeSource timeSource = new TestTimeSource(10042L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(ExpiryPolicy.INFINITE, Duration.ZERO, null), timeSource); final K key = factory.createKey(1042L); final V value = factory.createValue(1340142L); @@ -211,7 +212,7 @@ public void testComputeExpiresOnAccess() throws Exception { @SPITest public void testComputeExpiresOnUpdate() throws Exception { TestTimeSource timeSource = new TestTimeSource(10042L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setUpdate(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(ExpiryPolicy.INFINITE, null, Duration.ZERO), timeSource); final K key = factory.createKey(1042L); final V value = factory.createValue(1340142L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java index 82d9c5f0b2..3b3dc624d4 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java @@ -22,7 +22,7 @@ import org.ehcache.event.EventType; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; @@ -59,7 +59,7 @@ public StoreExpiryEventListenerTest(StoreFactory factory) { @Before public void setUp() { timeSource = new TestTimeSource(); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1)), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.tTL(Duration.ofMillis(1)), timeSource); } @After diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java index 6067cff545..2749193376 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java @@ -18,7 +18,8 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; @@ -153,7 +154,7 @@ public void wrongKeyTypeThrowsException() @SPITest public void testGetExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(ExpiryPolicy.INFINITE, Duration.ZERO, null), timeSource); K key = factory.createKey(250928L); V value = factory.createValue(2059820L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java index be87f0ea90..b22c512085 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java @@ -18,7 +18,8 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; @@ -31,7 +32,6 @@ import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; - /** * Test the {@link Store#putIfAbsent(Object, Object)} contract of the * {@link Store Store} interface. @@ -179,7 +179,7 @@ public void wrongValueTypeThrowsException() @SPITest public void testPutIfAbsentValuePresentExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setAccess(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(ExpiryPolicy.INFINITE, Duration.ZERO, null), timeSource); K key = factory.createKey(250928L); V value = factory.createValue(2059820L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java index f6ba11a498..686de8f584 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java @@ -18,7 +18,8 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; @@ -31,7 +32,6 @@ import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; - /** * Test the {@link Store#put(Object, Object)} contract of the * {@link Store Store} interface. @@ -182,7 +182,7 @@ public void indicatesValueReplaced() throws LegalSPITesterException { public void indicatesValueReplacedWhenUpdateExpires() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(1000L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setUpdate(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(ExpiryPolicy.INFINITE, null, Duration.ZERO), timeSource); K key = factory.createKey(42L); V value = factory.createValue(42L); @@ -203,7 +203,7 @@ public void indicatesValueReplacedWhenUpdateExpires() throws LegalSPITesterExcep public void indicatesOperationNoOp() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(1000L); - kvStore = factory.newStoreWithExpiry(ExpiryPolicies.builder().setCreate(Duration.ZERO).build(), timeSource); + kvStore = factory.newStoreWithExpiry(TestExpiries.custom(Duration.ZERO, null, null), timeSource); K key = factory.createKey(42L); try { diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java index d0e5d9b92b..07a05de242 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java @@ -17,7 +17,7 @@ package org.ehcache.internal.tier; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.spi.test.After; @@ -101,7 +101,7 @@ public void marksTheMappingAsNotEvictableAndReturnsValue() throws LegalSPITester @Ignore public void marksTheMappingAsNotExpirable() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(); - tier = factory.newStoreWithExpiry(ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(1)), timeSource); + tier = factory.newStoreWithExpiry(TestExpiries.tTI(Duration.ofMillis(1L)), timeSource); K key = factory.createKey(1); V value = factory.createValue(1); diff --git a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java index 88c7b39ac1..5fd8540214 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java +++ b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java @@ -184,12 +184,22 @@ public String readableString() { serviceConfigurationsToStringBuilder.append(" None"); } + String expiryPolicy = ""; + + if (expiryPolicy != null) { + if (ExpiryPolicy.NO_EXPIRY == expiry) { + expiryPolicy = "NoExpiryPolicy"; + } else { + expiryPolicy = expiry.toString(); + } + } + return "keyType: " + keyType.getName() + "\n" + "valueType: " + valueType.getName() + "\n" + "serviceConfigurations:" + serviceConfigurationsToStringBuilder.toString().replace("\n", "\n ") + "\n" + "evictionAdvisor: " + ((evictionAdvisor != null) ? evictionAdvisor.getClass().getName() : "None") + "\n" + - "expiry: " + ((expiry != null) ? expiry.getClass().getSimpleName() : "") + "\n" + + "expiry: " + expiryPolicy + "\n" + "resourcePools: " + "\n " + ((resourcePools instanceof HumanReadable) ? ((HumanReadable)resourcePools).readableString() : "").replace("\n", "\n "); } } diff --git a/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java b/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java index 894fbdadda..89a324f56a 100644 --- a/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java +++ b/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java @@ -24,7 +24,6 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.expiry.Expiry; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; @@ -72,7 +71,7 @@ public BaseCacheConfiguration(Class keyType, Class valueType, if (expiry != null) { this.expiry = expiry; } else { - this.expiry = ExpiryPolicies.noExpiration(); + this.expiry = ExpiryPolicy.NO_EXPIRY; } this.resourcePools = resourcePools; this.serviceConfigurations = Collections.unmodifiableCollection(Arrays.asList(serviceConfigurations)); diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java index 2cafbc8b63..1087836108 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java @@ -24,7 +24,7 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.hamcrest.Matchers; import org.junit.Test; import org.slf4j.LoggerFactory; @@ -175,7 +175,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessException() throws Exception */ private Ehcache getEhcache() { CacheConfiguration config = new BaseCacheConfiguration<>(String.class, String.class, null, null, - ExpiryPolicies.noExpiration(), ResourcePoolsHelper.createHeapOnlyPools()); + ExpiryPolicy.NO_EXPIRY, ResourcePoolsHelper.createHeapOnlyPools()); final Ehcache ehcache = new Ehcache<>(config, this.store, cacheEventDispatcher, LoggerFactory.getLogger(Ehcache.class + "-" + "EhcacheBasicPutIfAbsentTest")); ehcache.init(); assertThat("cache not initialized", ehcache.getStatus(), Matchers.is(Status.AVAILABLE)); diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java index 297d87f315..80b03fdaa8 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java @@ -23,7 +23,6 @@ import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -476,7 +475,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionCacheLoaderWriterExc * @return a new {@code Ehcache} instance */ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter) { - return getEhcache(cacheLoaderWriter, ExpiryPolicies.noExpiration()); + return getEhcache(cacheLoaderWriter, ExpiryPolicy.NO_EXPIRY); } private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java index 17ffdaf9fe..2b73b8cfad 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java @@ -22,7 +22,6 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -543,7 +542,7 @@ public void testReplaceWithImmediatelyExpiredEntry() throws Exception { * @return a new {@code EhcacheWithLoaderWriter} instance */ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter) { - return getEhcache(cacheLoaderWriter, ExpiryPolicies.noExpiration()); + return getEhcache(cacheLoaderWriter, ExpiryPolicy.NO_EXPIRY); } private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java index 5e59491ab2..1fe7fe1efd 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java @@ -22,7 +22,6 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -919,7 +918,7 @@ public void testReplaceWithImmediatelyExpiredEntry() throws Exception { * @return a new {@code EhcacheWithLoaderWriter} instance */ private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter) { - return getEhcache(cacheLoaderWriter, ExpiryPolicies.noExpiration()); + return getEhcache(cacheLoaderWriter, ExpiryPolicy.NO_EXPIRY); } private EhcacheWithLoaderWriter getEhcache(final CacheLoaderWriter cacheLoaderWriter, ExpiryPolicy expiry) { diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java b/impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java similarity index 50% rename from api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java rename to impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java index 7aa75ae6c0..e543ca5a48 100644 --- a/api/src/main/java/org/ehcache/expiry/ExpiryPolicies.java +++ b/impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java @@ -13,16 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ehcache.expiry; +package org.ehcache.config.builders; import org.ehcache.ValueSupplier; +import org.ehcache.config.Builder; +import org.ehcache.expiry.ExpiryPolicy; +import java.time.Duration; import java.util.Objects; /** - * Utility class for getting predefined {@link ExpiryPolicy} instances. + * Builder and utilities for getting predefined {@link ExpiryPolicy} instances. */ -public final class ExpiryPolicies { +public final class ExpiryPolicyBuilder implements Builder>{ /** * Get an {@link ExpiryPolicy} instance for a non expiring (ie. "eternal") cache. @@ -30,16 +33,16 @@ public final class ExpiryPolicies { * @return the no expiry instance */ public static ExpiryPolicy noExpiration() { - return NoExpiryPolicy.INSTANCE; + return ExpiryPolicy.NO_EXPIRY; } /** - * Get a time-to-live (TTL) {@link ExpiryPolicy} instance for the given {@link java.time.Duration}. + * Get a time-to-live (TTL) {@link ExpiryPolicy} instance for the given {@link Duration}. * * @param timeToLive the TTL duration * @return a TTL expiry */ - public static ExpiryPolicy timeToLiveExpiration(java.time.Duration timeToLive) { + public static ExpiryPolicy timeToLiveExpiration(Duration timeToLive) { Objects.requireNonNull(timeToLive, "TTL duration cannot be null"); if (timeToLive.isNegative()) { throw new IllegalArgumentException("TTL duration cannot be negative"); @@ -48,12 +51,12 @@ public static ExpiryPolicy timeToLiveExpiration(java.time.Durati } /** - * Get a time-to-idle (TTI) {@link ExpiryPolicy} instance for the given {@link java.time.Duration}. + * Get a time-to-idle (TTI) {@link ExpiryPolicy} instance for the given {@link Duration}. * * @param timeToIdle the TTI duration * @return a TTI expiry */ - public static ExpiryPolicy timeToIdleExpiration(java.time.Duration timeToIdle) { + public static ExpiryPolicy timeToIdleExpiration(Duration timeToIdle) { Objects.requireNonNull(timeToIdle, "TTI duration cannot be null"); if (timeToIdle.isNegative()) { throw new IllegalArgumentException("TTI duration cannot be negative"); @@ -66,45 +69,95 @@ public static ExpiryPolicy timeToIdleExpiration(java.time.Durati * Unspecified values will be set to {@link ExpiryPolicy#INFINITE INFINITE} for create and {@code null} for access and update, matching * the {@link #noExpiration()} no expiration} expiry. * - * @param the key type for the cache - * @param the value type for the cache * @return an {@link ExpiryPolicy} builder */ - public static ExpiryPolicyBuilder builder() { - return new ExpiryPolicyBuilder<>(); + public static ExpiryPolicyBuilder expiry() { + return new ExpiryPolicyBuilder(); } + private Duration create = ExpiryPolicy.INFINITE; + private Duration access = null; + private Duration update = null; - private ExpiryPolicies() { - // + private ExpiryPolicyBuilder() {} + + /** + * Set TTL since creation + * + * @param create TTL since creation + * @return this builder + */ + public ExpiryPolicyBuilder create(Duration create) { + Objects.requireNonNull(create, "Create duration cannot be null"); + if (create.isNegative()) { + throw new IllegalArgumentException("Create duration must be positive"); + } + this.create = create; + return this; + } + + /** + * Set TTL since last access + * + * @param access TTL since last access + * @return this builder + */ + public ExpiryPolicyBuilder access(Duration access) { + if (access != null && access.isNegative()) { + throw new IllegalArgumentException("Access duration must be positive"); + } + this.access = access; + return this; + } + + /** + * Set TTL since last update + * + * @param update TTL since last update + * @return this builder + */ + public ExpiryPolicyBuilder update(Duration update) { + if (update != null && update.isNegative()) { + throw new IllegalArgumentException("Update duration must be positive"); + } + this.update = update; + return this; + } + + /** + * + * @return an {@link ExpiryPolicy} + */ + public ExpiryPolicy build() { + return new BaseExpiryPolicy(create, access, update); } /** * Simple implementation of the {@link ExpiryPolicy} interface allowing to set constants to each expiry types. */ - private static class BaseExpiryPolicy implements ExpiryPolicy { + private static class BaseExpiryPolicy implements ExpiryPolicy { - private final java.time.Duration create; - private final java.time.Duration access; - private final java.time.Duration update; + private final Duration create; + private final Duration access; + private final Duration update; - BaseExpiryPolicy(java.time.Duration create, java.time.Duration access, java.time.Duration update) { + BaseExpiryPolicy(Duration create, Duration access, Duration update) { this.create = create; this.access = access; this.update = update; } @Override - public java.time.Duration getExpiryForCreation(K key, V value) { + public Duration getExpiryForCreation(Object key, Object value) { return create; } @Override - public java.time.Duration getExpiryForAccess(K key, ValueSupplier value) { + public Duration getExpiryForAccess(Object key, ValueSupplier value) { return access; } @Override - public java.time.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { return update; } @@ -140,90 +193,15 @@ public String toString() { } } - private static class TimeToLiveExpiryPolicy extends BaseExpiryPolicy { - TimeToLiveExpiryPolicy(java.time.Duration ttl) { + private static final class TimeToLiveExpiryPolicy extends BaseExpiryPolicy { + TimeToLiveExpiryPolicy(Duration ttl) { super(ttl, null, ttl); } } - private static class TimeToIdleExpiryPolicy extends BaseExpiryPolicy { - TimeToIdleExpiryPolicy(java.time.Duration tti) { + private static final class TimeToIdleExpiryPolicy extends BaseExpiryPolicy { + TimeToIdleExpiryPolicy(Duration tti) { super(tti, tti, tti); } } - - private static class NoExpiryPolicy extends BaseExpiryPolicy { - - private static final ExpiryPolicy INSTANCE = new NoExpiryPolicy(); - - private NoExpiryPolicy() { - super(ExpiryPolicy.INFINITE, null, null); - } - } - - /** - * Builder to create a simple {@link Expiry}. - * - * @param Key type of the cache entries - * @param Value type of the cache entries - */ - public static final class ExpiryPolicyBuilder { - - private java.time.Duration create = ExpiryPolicy.INFINITE; - private java.time.Duration access = null; - private java.time.Duration update = null; - - private ExpiryPolicyBuilder() {} - - /** - * Set TTL since creation - * - * @param create TTL since creation - * @return this builder - */ - public ExpiryPolicyBuilder setCreate(java.time.Duration create) { - Objects.requireNonNull(create, "Create duration cannot be null"); - if (create.isNegative()) { - throw new IllegalArgumentException("Create duration must be positive"); - } - this.create = create; - return this; - } - - /** - * Set TTL since last access - * - * @param access TTL since last access - * @return this builder - */ - public ExpiryPolicyBuilder setAccess(java.time.Duration access) { - if (access != null && access.isNegative()) { - throw new IllegalArgumentException("Access duration must be positive"); - } - this.access = access; - return this; - } - - /** - * Set TTL since last update - * - * @param update TTL since last update - * @return this builder - */ - public ExpiryPolicyBuilder setUpdate(java.time.Duration update) { - if (update != null && update.isNegative()) { - throw new IllegalArgumentException("Update duration must be positive"); - } - this.update = update; - return this; - } - - /** - * - * @return an {@link Expiry} - */ - public ExpiryPolicy build() { - return new BaseExpiryPolicy<>(create, access, update); - } - } } diff --git a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java index 62067fa058..6f4e2b50b7 100644 --- a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java @@ -47,7 +47,6 @@ import org.ehcache.core.spi.store.heap.SizeOfEngineProvider; import org.ehcache.event.CacheEventListener; import org.ehcache.expiry.Expiry; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.serializer.DefaultSerializerConfiguration; @@ -110,7 +109,7 @@ public class UserManagedCacheBuilder> imp private String id; private final Set services = new HashSet<>(); private final Set> serviceCreationConfigurations = new HashSet<>(); - private ExpiryPolicy expiry = ExpiryPolicies.noExpiration(); + private ExpiryPolicy expiry = ExpiryPolicy.NO_EXPIRY; private ClassLoader classLoader = ClassLoading.getDefaultClassLoader(); private EvictionAdvisor evictionAdvisor; private CacheLoaderWriter cacheLoaderWriter; diff --git a/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java b/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java index ae46129c48..8b32862a58 100644 --- a/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java @@ -20,7 +20,6 @@ import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.service.ServiceUtils; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; @@ -220,7 +219,7 @@ public Long copyForWrite(Object obj) { public void testNothing() { final CacheConfigurationBuilder builder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, CharSequence.class, heap(10)); - final ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(ExpiryPolicy.INFINITE); + final ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToIdleExpiration(ExpiryPolicy.INFINITE); builder .withEvictionAdvisor((key, value) -> value.charAt(0) == 'A') @@ -234,7 +233,7 @@ public void testOffheapGetsAddedToCacheConfiguration() { ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)); - final ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(ExpiryPolicy.INFINITE); + final ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToIdleExpiration(ExpiryPolicy.INFINITE); CacheConfiguration config = builder .withEvictionAdvisor((key, value) -> value.charAt(0) == 'A') diff --git a/api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java b/impl/src/test/java/org/ehcache/config/builders/ExpiryPolicyBuilderTest.java similarity index 77% rename from api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java rename to impl/src/test/java/org/ehcache/config/builders/ExpiryPolicyBuilderTest.java index 1071212c4f..189e1cc82b 100644 --- a/api/src/test/java/org/ehcache/expiry/ExpiryPoliciesTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/ExpiryPolicyBuilderTest.java @@ -13,19 +13,26 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ehcache.expiry; +package org.ehcache.config.builders; + +import org.ehcache.expiry.ExpiryPolicy; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.nullValue; +import static org.hamcrest.Matchers.sameInstance; -public class ExpiryPoliciesTest { +/** + * ExpiryPolicyBuilderTest + */ +public class ExpiryPolicyBuilderTest { @Test public void testNoExpiration() { - ExpiryPolicy expiry = ExpiryPolicies.noExpiration(); + ExpiryPolicy expiry = ExpiryPolicyBuilder.noExpiration(); + assertThat(expiry, sameInstance(ExpiryPolicy.NO_EXPIRY)); assertThat(expiry.getExpiryForCreation(this, this), equalTo(ExpiryPolicy.INFINITE)); assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue()); assertThat(expiry.getExpiryForUpdate(this, () -> this, this), nullValue()); @@ -34,7 +41,7 @@ public void testNoExpiration() { @Test public void testTTIExpiration() { java.time.Duration duration = java.time.Duration.ofSeconds(1L); - ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(duration); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToIdleExpiration(duration); assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration)); assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(duration)); assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration)); @@ -43,7 +50,7 @@ public void testTTIExpiration() { @Test public void testTTLExpiration() { java.time.Duration duration = java.time.Duration.ofSeconds(1L); - ExpiryPolicy expiry = ExpiryPolicies.timeToLiveExpiration(duration); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToLiveExpiration(duration); assertThat(expiry.getExpiryForCreation(this, this), equalTo(duration)); assertThat(expiry.getExpiryForAccess(this, () -> this), nullValue()); assertThat(expiry.getExpiryForUpdate(this, () -> this, this), equalTo(duration)); @@ -54,10 +61,9 @@ public void testExpiration() { java.time.Duration creation = java.time.Duration.ofSeconds(1L); java.time.Duration access = java.time.Duration.ofSeconds(2L); java.time.Duration update = java.time.Duration.ofSeconds(3L); - ExpiryPolicy expiry = ExpiryPolicies.builder().setCreate(creation).setAccess(access).setUpdate(update).build(); + ExpiryPolicy expiry = ExpiryPolicyBuilder.expiry().create(creation).access(access).update(update).build(); assertThat(expiry.getExpiryForCreation(this, this), equalTo(creation)); assertThat(expiry.getExpiryForAccess(this, () -> this), equalTo(access)); assertThat(expiry.getExpiryForUpdate(this, () -> this,this), equalTo(update)); } - } diff --git a/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java b/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java index 29350a4724..2d0a12014b 100644 --- a/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/UserManagedCacheBuilderTest.java @@ -21,7 +21,6 @@ import org.ehcache.UserManagedCache; import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.event.EventType; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.impl.internal.spi.event.DefaultCacheEventListenerProviderTest; @@ -80,7 +79,7 @@ public void testInvalidListenerConfig() { @Test public void testTypedCacheWithExpirationPolicy() { try (UserManagedCache cache = UserManagedCacheBuilder.newUserManagedCacheBuilder(String.class, String.class) - .withExpiry(ExpiryPolicies.timeToIdleExpiration(Duration.ofSeconds(30))) + .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(30))) .build(true)) { assertThat(cache, notNullValue()); } diff --git a/impl/src/test/java/org/ehcache/docs/GettingStarted.java b/impl/src/test/java/org/ehcache/docs/GettingStarted.java index 044dfbed82..2679e4ee1f 100644 --- a/impl/src/test/java/org/ehcache/docs/GettingStarted.java +++ b/impl/src/test/java/org/ehcache/docs/GettingStarted.java @@ -23,13 +23,13 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.builders.WriteBehindConfigurationBuilder; import org.ehcache.config.builders.CacheEventListenerConfigurationBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.docs.plugs.ListenerObject; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.serialization.JavaSerializer; import org.ehcache.docs.plugs.OddKeysEvictionAdvisor; @@ -244,7 +244,7 @@ public void expiry() throws Exception { // tag::expiry[] CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(100)) // <1> - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(20))) // <2> + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(20))) // <2> .build(); // end::expiry[] } diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java index 33464a039e..73a2063be7 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/PooledExecutorWriteBehindTest.java @@ -18,7 +18,7 @@ import java.time.Duration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.impl.config.executor.PooledExecutionServiceConfiguration; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; @@ -34,7 +34,7 @@ public class PooledExecutorWriteBehindTest extends AbstractWriteBehindTestBase { @Override protected CacheConfigurationBuilder configurationBuilder() { return newCacheConfigurationBuilder(String.class, String.class, heap(100)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java index 7e2cb833dc..cbb5b5d667 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindEvictionTest.java @@ -19,7 +19,7 @@ import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; @@ -34,7 +34,7 @@ public class WriteBehindEvictionTest extends AbstractWriteBehindTestBase { @Override protected CacheConfigurationBuilder configurationBuilder() { return newCacheConfigurationBuilder(String.class, String.class, heap(10)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(100))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(100))); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java index 106ad91ad1..f3f81399ce 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTest.java @@ -19,7 +19,7 @@ import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; @@ -34,7 +34,7 @@ public class WriteBehindTest extends AbstractWriteBehindTestBase { @Override protected CacheConfigurationBuilder configurationBuilder() { return newCacheConfigurationBuilder(String.class, String.class, heap(100)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java index 86c5ab608c..1e375edcbd 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java @@ -21,8 +21,8 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.InternalCache; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.internal.TestTimeSource; import org.junit.After; @@ -48,7 +48,7 @@ public void before() { CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(10)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java index af74987fe2..27113b5fa0 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java @@ -22,7 +22,7 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.internal.TestTimeSource; import org.junit.After; @@ -48,7 +48,7 @@ public void before() { CacheConfiguration cacheConfiguration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder().heap(10)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java index 6cc487992a..4db6acc73d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreProviderTest.java @@ -23,11 +23,11 @@ import org.ehcache.config.ResourceType; import org.ehcache.config.ResourceUnit; import org.ehcache.config.SizedResourcePool; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.DefaultTimeSourceService; import org.ehcache.impl.serialization.LongSerializer; @@ -118,7 +118,7 @@ public ClassLoader getClassLoader() { @Override public ExpiryPolicy getExpiry() { - return ExpiryPolicies.noExpiration(); + return ExpiryPolicyBuilder.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java index e2703c4029..c8a04670ff 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreSPITest.java @@ -19,11 +19,11 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.SizedResourcePool; import org.ehcache.config.units.MemoryUnit; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -83,12 +83,12 @@ public void setUp() throws Exception { @Override public AuthoritativeTier newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public AuthoritativeTier newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -98,7 +98,7 @@ public AuthoritativeTier newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java index 6d4bb1127f..f25432f728 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java @@ -76,11 +76,11 @@ import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; import static org.ehcache.config.builders.CacheManagerBuilder.persistence; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.ehcache.config.units.MemoryUnit.MB; import static org.ehcache.core.internal.service.ServiceLocator.dependencySet; -import static org.ehcache.expiry.ExpiryPolicies.noExpiration; import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_DISK_SEGMENTS; import static org.ehcache.impl.config.store.disk.OffHeapDiskStoreConfiguration.DEFAULT_WRITER_CONCURRENCY; import static org.ehcache.impl.internal.spi.TestServiceProvider.providerContaining; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java index 43931944fa..b3bff8a817 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java @@ -19,10 +19,10 @@ import org.ehcache.ValueSupplier; import org.ehcache.config.Eviction; import org.ehcache.config.EvictionAdvisor; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.store.heap.holders.CopiedOnHeapValueHolder; @@ -54,10 +54,8 @@ import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.expiry; import static org.ehcache.impl.internal.util.Matchers.holding; import static org.ehcache.impl.internal.util.Matchers.valueHeld; import static org.hamcrest.MatcherAssert.assertThat; @@ -196,7 +194,7 @@ public void testGetExpired() throws Exception { StoreEventSink eventSink = getStoreEventSink(); StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); assertThat(store.get("key").value(), equalTo("value")); timeSource.advanceTime(1); @@ -212,7 +210,7 @@ public void testGetExpired() throws Exception { public void testGetNoExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(2))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(2))); StoreEventSink eventSink = getStoreEventSink(); store.put("key", "value"); timeSource.advanceTime(1); @@ -224,7 +222,7 @@ public void testGetNoExpired() throws Exception { @Test public void testAccessTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration()); store.put("key", "value"); long first = store.get("key").lastAccessTime(TimeUnit.MILLISECONDS); @@ -254,7 +252,7 @@ public void testContainsKeyExpired() throws Exception { StoreEventSink eventSink = getStoreEventSink(); StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -295,7 +293,7 @@ public void testPutOverwrite() throws Exception { @Test public void testCreateTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration()); assertThat(store.containsKey("key"), is(false)); store.put("key", "value"); ValueHolder valueHolder = store.get("key"); @@ -338,7 +336,7 @@ public void testPutIfAbsentValuePresent() throws Exception { @Test public void testPutIfAbsentUpdatesAccessTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration()); assertThat(store.get("key"), nullValue()); store.putIfAbsent("key", "value"); long first = store.get("key").lastAccessTime(TimeUnit.MILLISECONDS); @@ -351,7 +349,7 @@ public void testPutIfAbsentUpdatesAccessTime() throws Exception { public void testPutIfAbsentExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); ValueHolder prev = store.putIfAbsent("key", "value2"); @@ -405,7 +403,7 @@ public void testRemoveTwoArgExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); assertThat(store.get("key").value(), equalTo("value")); @@ -447,7 +445,7 @@ public void testReplaceTwoArgExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -494,7 +492,7 @@ public void testReplaceThreeArgExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -535,7 +533,7 @@ public void testIterator() throws Exception { public void testIteratorExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key1", "value1"); store.put("key2", "value2"); store.put("key3", "value3"); @@ -553,7 +551,7 @@ public void testIteratorExpired() throws Exception { @Test public void testIteratorDoesNotUpdateAccessTime() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration()); store.put("key1", "value1"); store.put("key2", "value2"); @@ -569,7 +567,7 @@ public void testIteratorDoesNotUpdateAccessTime() throws Exception { @Test public void testComputeReplaceTrue() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration()); StoreEventSink eventSink = getStoreEventSink(); StoreEventDispatcher eventDispatcher = getStoreEventDispatcher(); @@ -592,7 +590,7 @@ public void testComputeReplaceTrue() throws Exception { @Test public void testComputeReplaceFalse() throws Exception { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.noExpiration()); + OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.noExpiration()); store.put("key", "value"); ValueHolder installedHolder = store.get("key"); @@ -692,7 +690,7 @@ public void testComputeExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreEventSink eventSink = getStoreEventSink(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); ValueHolder newValue = store.compute("key", (mappedKey, mappedValue) -> { @@ -711,7 +709,7 @@ public void testComputeExpired() throws Exception { public void testComputeWhenExpireOnCreate() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(1000L); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.builder().setCreate(Duration.ZERO).build()); + OnHeapStore store = newStore(timeSource, expiry().create(Duration.ZERO).build()); ValueHolder result = store.compute("key", (key, value) -> "value", () -> false); assertThat(result, nullValue()); @@ -721,7 +719,7 @@ public void testComputeWhenExpireOnCreate() throws Exception { public void testComputeWhenExpireOnUpdate() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(1000L); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); + OnHeapStore store = newStore(timeSource, expiry().update(Duration.ZERO).build()); store.put("key", "value"); ValueHolder result = store.compute("key", (key, value) -> "newValue", () -> false); @@ -732,7 +730,7 @@ public void testComputeWhenExpireOnUpdate() throws Exception { public void testComputeWhenExpireOnAccess() throws Exception { TestTimeSource timeSource = new TestTimeSource(); timeSource.advanceTime(1000L); - OnHeapStore store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); + OnHeapStore store = newStore(timeSource, expiry().access(Duration.ZERO).build()); store.put("key", "value"); ValueHolder result = store.compute("key", (key, value) -> value, () -> false); @@ -804,7 +802,7 @@ public void testComputeIfAbsentException() throws Exception { public void testComputeIfAbsentExpired() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); timeSource.advanceTime(1); @@ -910,7 +908,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o public void testGetOrComputeIfAbsentExpiresOnHit() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); @SuppressWarnings("unchecked") CachingTier.InvalidationListener invalidationListener = mock(CachingTier.InvalidationListener.class); store.setInvalidationListener(invalidationListener); @@ -932,7 +930,7 @@ public void testGetOrComputeIfAbsentExpiresOnHit() throws Exception { public void testGetOfComputeIfAbsentExpiresWithLoaderWriter() throws Exception { TestTimeSource timeSource = new TestTimeSource(); OnHeapStore store = newStore(timeSource, - ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); @SuppressWarnings("unchecked") CachingTier.InvalidationListener invalidationListener = mock(CachingTier.InvalidationListener.class); store.setInvalidationListener(invalidationListener); @@ -1217,7 +1215,7 @@ public void testEvictionDoneUnderEvictedKeyLockScope() throws Exception { @Test(timeout = 2000L) public void testIteratorExpiryHappensUnderExpiredKeyLockScope() throws Exception { TestTimeSource testTimeSource = new TestTimeSource(); - final OnHeapStore store = newStore(testTimeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10))); + final OnHeapStore store = newStore(testTimeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10))); store.put("key", "value"); @@ -1335,11 +1333,11 @@ protected StoreEventDispatcher getStoreEventDispatcher() { } protected OnHeapStore newStore() { - return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice()); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicyBuilder.noExpiration(), Eviction.noAdvice()); } protected OnHeapStore newStore(EvictionAdvisor evictionAdvisor) { - return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), evictionAdvisor); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicyBuilder.noExpiration(), evictionAdvisor); } protected OnHeapStore newStore(TimeSource timeSource, ExpiryPolicy expiry) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java index ac5cff597b..b86e82de0d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByRefSPITest.java @@ -18,9 +18,9 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -57,12 +57,12 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -72,7 +72,7 @@ public Store newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @SuppressWarnings("unchecked") diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java index 04f610b240..c3a3cc3325 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/ByteSizedOnHeapStoreByValueSPITest.java @@ -18,9 +18,9 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -62,12 +62,12 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -77,7 +77,7 @@ public Store newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java index 6df8c6fe5a..b22f899844 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java @@ -16,8 +16,8 @@ package org.ehcache.impl.internal.store.heap; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -54,7 +54,7 @@ public class OnHeapStoreBulkMethodsTest { protected Store.Configuration mockStoreConfig() { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(CharSequence.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build()); @@ -73,7 +73,7 @@ protected OnHeapStore newStore() { public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(Number.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java index 4fce95e584..75514c7a7e 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByRefSPITest.java @@ -18,9 +18,9 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -63,12 +63,12 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -78,7 +78,7 @@ public Store newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @SuppressWarnings("unchecked") diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java index 9b4bfc9b5b..d06f9c3f35 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueSPITest.java @@ -18,9 +18,9 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -68,12 +68,12 @@ public void setUp() { @Override public Store newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -83,7 +83,7 @@ public Store newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java index 7e5f3725ea..1f3643042a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java @@ -21,7 +21,7 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.core.spi.store.StoreAccessException; @@ -70,7 +70,7 @@ public Long copyForWrite(Long obj) { @Test public void testKeyCopierCalledOnGetOrComputeIfAbsent() throws Exception { LongCopier keyCopier = new LongCopier(); - OnHeapStore store = newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice(), + OnHeapStore store = newStore(SystemTimeSource.INSTANCE, ExpiryPolicyBuilder.noExpiration(), Eviction.noAdvice(), keyCopier, new SerializingCopier<>(new JavaSerializer<>(ClassLoader.getSystemClassLoader())), 100); ValueHolder computed = store.getOrComputeIfAbsent(1L, key -> new AbstractValueHolder(-1, -1) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java index 94cb8dadd3..0b7a0fd43e 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByRefSPITest.java @@ -17,9 +17,9 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -71,7 +71,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, null, null); + ClassLoader.getSystemClassLoader(), ExpiryPolicyBuilder.noExpiration(), buildResourcePools(capacity), 0, null, null); return new OnHeapStore(config, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java index 8507da9f93..8ebf981299 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreCachingTierByValueSPITest.java @@ -17,9 +17,9 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -74,7 +74,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, + ClassLoader.getSystemClassLoader(), ExpiryPolicyBuilder.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); return new OnHeapStore<>(config, SystemTimeSource.INSTANCE, defaultCopier, defaultCopier, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java index f4a3ee90ef..e9a84a589b 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java @@ -17,11 +17,11 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.event.EventType; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -106,7 +106,7 @@ public void testEvictionCandidateLimits() throws Exception { TestTimeSource timeSource = new TestTimeSource(); StoreConfigurationImpl configuration = new StoreConfigurationImpl<>( String.class, String.class, noAdvice(), - getClass().getClassLoader(), ExpiryPolicies.noExpiration(), heap(1).build(), 1, null, null); + getClass().getClassLoader(), ExpiryPolicyBuilder.noExpiration(), heap(1).build(), 1, null, null); TestStoreEventDispatcher eventDispatcher = new TestStoreEventDispatcher<>(); final String firstKey = "daFirst"; eventDispatcher.addEventListener(event -> { @@ -149,7 +149,7 @@ public ClassLoader getClassLoader() { @Override public ExpiryPolicy getExpiry() { - return ExpiryPolicies.noExpiration(); + return ExpiryPolicyBuilder.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java index f1ffaeb098..575cacd21a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java @@ -17,9 +17,9 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.Cache; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -79,7 +79,7 @@ public void setUp() { when(configuration.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()); when(configuration.getKeyType()).thenReturn(Key.class); when(configuration.getValueType()).thenReturn(String.class); - when(configuration.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); + when(configuration.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration()); @SuppressWarnings("unchecked") Store.Configuration config = configuration; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java index f93c12a173..da8e3bf87f 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java @@ -17,9 +17,9 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.Cache; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -79,7 +79,7 @@ public void setUp() { when(configuration.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build()); when(configuration.getKeyType()).thenReturn(Long.class); when(configuration.getValueType()).thenReturn(Value.class); - when(configuration.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); + when(configuration.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration()); @SuppressWarnings("unchecked") Store.Configuration config = configuration; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java index 39f830d79f..edcd9504a5 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java @@ -18,12 +18,12 @@ import org.ehcache.config.Eviction; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.event.EventType; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.heap.LimitExceededException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; @@ -46,8 +46,8 @@ import java.time.Duration; import java.util.Arrays; -import java.util.concurrent.TimeUnit; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.expiry; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.ehcache.internal.store.StoreCreationEventListenerTest.eventType; import static org.hamcrest.MatcherAssert.assertThat; @@ -77,11 +77,11 @@ public class ByteAccountingTest { OnHeapStoreForTests newStore() { - return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice()); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicyBuilder.noExpiration(), Eviction.noAdvice()); } OnHeapStoreForTests newStore(int capacity) { - return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice(), capacity); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicyBuilder.noExpiration(), Eviction.noAdvice(), capacity); } OnHeapStoreForTests newStore(TimeSource timeSource, ExpiryPolicy expiry) { @@ -170,7 +170,7 @@ public void testPutUpdate() throws StoreAccessException { @Test public void testPutExpiryOnCreate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setCreate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().create(Duration.ZERO).build()); store.put(KEY, VALUE); @@ -180,7 +180,7 @@ public void testPutExpiryOnCreate() throws StoreAccessException { @Test public void testPutExpiryOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().update(Duration.ZERO).build()); store.put(KEY, VALUE); store.put(KEY, "otherValue"); @@ -237,7 +237,7 @@ public void testRemoveTwoArgExpired() throws StoreAccessException { @Test public void testRemoveTwoArgExpiresOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().access(Duration.ZERO).build()); store.put(KEY, VALUE); store.remove(KEY, "whatever value, it expires on access"); @@ -279,7 +279,7 @@ public void testReplaceTwoArgExpired() throws StoreAccessException { @Test public void testReplaceTwoArgExpiresOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().update(Duration.ZERO).build()); store.put(KEY, VALUE); store.replace(KEY, "whatever value, it expires on update"); @@ -321,7 +321,7 @@ public void testReplaceThreeArgExpired() throws StoreAccessException { @Test public void testReplaceThreeArgExpiresOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().update(Duration.ZERO).build()); store.put(KEY, VALUE); store.replace(KEY, VALUE, "whatever value, it expires on update"); @@ -354,7 +354,7 @@ public void testPutIfAbsentOverExpired() throws StoreAccessException { @Test public void testPutIfAbsentExpiresOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(1000L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().access(Duration.ZERO).build()); store.put(KEY, VALUE); store.putIfAbsent(KEY, "another value ... whatever"); @@ -417,7 +417,7 @@ public void testCompute() throws StoreAccessException { @Test public void testComputeExpiryOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().access(Duration.ZERO).build()); store.put(KEY, VALUE); store.compute(KEY, (s, s2) -> s2, () -> false); @@ -428,7 +428,7 @@ public void testComputeExpiryOnAccess() throws StoreAccessException { @Test public void testComputeExpiryOnUpdate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setUpdate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().update(Duration.ZERO).build()); store.put(KEY, VALUE); store.compute(KEY, (s, s2) -> s2); @@ -452,7 +452,7 @@ public void testComputeIfAbsent() throws StoreAccessException { @Test public void testComputeIfAbsentExpireOnCreate() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setCreate(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().create(Duration.ZERO).build()); store.computeIfAbsent(KEY, s -> VALUE); @@ -462,7 +462,7 @@ public void testComputeIfAbsentExpireOnCreate() throws StoreAccessException { @Test public void testComputeIfAbsentExpiryOnAccess() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(100L); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); + OnHeapStoreForTests store = newStore(timeSource, expiry().access(Duration.ZERO).build()); store.put(KEY, VALUE); store.computeIfAbsent(KEY, s -> { @@ -476,7 +476,7 @@ public void testComputeIfAbsentExpiryOnAccess() throws StoreAccessException { @Test public void testExpiry() throws StoreAccessException { TestTimeSource timeSource = new TestTimeSource(); - OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(1))); + OnHeapStoreForTests store = newStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put(KEY, VALUE); assertThat(store.getCurrentUsageInBytes(), is(SIZE_OF_KEY_VALUE_PAIR)); @@ -515,7 +515,7 @@ public void testEviction() throws StoreAccessException { } private ExpiryPolicy ttlCreation600ms() { - return ExpiryPolicies.builder().setCreate(Duration.ofMillis(600L)).build(); + return expiry().create(Duration.ofMillis(600L)).build(); } static long getSize(String key, String value) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java index 9b82807dc3..7de06463df 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java @@ -16,8 +16,8 @@ package org.ehcache.impl.internal.store.heap.bytesized; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -46,7 +46,7 @@ public class OnHeapStoreBulkMethodsTest extends org.ehcache.impl.internal.store. protected Store.Configuration mockStoreConfig() { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(CharSequence.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(100, MemoryUnit.KB).build()); @@ -65,7 +65,7 @@ protected OnHeapStore newStore() { public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { @SuppressWarnings("rawtypes") Store.Configuration config = mock(Store.Configuration.class); - when(config.getExpiry()).thenReturn(ExpiryPolicies.noExpiration()); + when(config.getExpiry()).thenReturn(ExpiryPolicyBuilder.noExpiration()); when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(Number.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(100, MemoryUnit.KB).build()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java index ba70889ac1..aac90a0c98 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByRefSPITest.java @@ -17,9 +17,9 @@ package org.ehcache.impl.internal.store.heap.bytesized; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -69,7 +69,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, null, null); + ClassLoader.getSystemClassLoader(), ExpiryPolicyBuilder.noExpiration(), buildResourcePools(capacity), 0, null, null); return new OnHeapStore(config, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new DefaultSizeOfEngine(Long.MAX_VALUE, Long.MAX_VALUE), NullStoreEventDispatcher.nullStoreEventDispatcher()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java index 9a33df716f..10dc7eb4e3 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreCachingTierByValueSPITest.java @@ -17,9 +17,9 @@ package org.ehcache.impl.internal.store.heap.bytesized; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -72,7 +72,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, + ClassLoader.getSystemClassLoader(), ExpiryPolicyBuilder.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); return new OnHeapStore<>(config, SystemTimeSource.INSTANCE, defaultCopier, defaultCopier, new DefaultSizeOfEngine(Long.MAX_VALUE, Long.MAX_VALUE), NullStoreEventDispatcher.nullStoreEventDispatcher()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java index 059c566f07..ad47607fb7 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreEvictionTest.java @@ -17,9 +17,9 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.time.TimeSource; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; import org.ehcache.core.spi.store.Store; @@ -58,7 +58,7 @@ public ClassLoader getClassLoader() { @Override public ExpiryPolicy getExpiry() { - return ExpiryPolicies.noExpiration(); + return ExpiryPolicyBuilder.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java index 95841408e5..5636fd05bb 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java @@ -19,8 +19,8 @@ import org.ehcache.config.Eviction; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.DefaultSizeOfEngine; @@ -48,7 +48,7 @@ public class OversizeMappingTest { private static final String OVER_SIZED_VALUE = new String(new byte[1000]); OnHeapStoreForTests newStore() { - return newStore(SystemTimeSource.INSTANCE, ExpiryPolicies.noExpiration(), Eviction.noAdvice(), 100); + return newStore(SystemTimeSource.INSTANCE, ExpiryPolicyBuilder.noExpiration(), Eviction.noAdvice(), 100); } private OnHeapStoreForTests newStore(final TimeSource timeSource, final ExpiryPolicy expiry, final EvictionAdvisor evictionAdvisor, diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java index cae9c1d5d9..cbd8b9cd74 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java @@ -19,6 +19,7 @@ import org.ehcache.Cache; import org.ehcache.ValueSupplier; import org.ehcache.config.EvictionAdvisor; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.event.EventType; import org.ehcache.core.spi.store.StoreAccessException; @@ -29,7 +30,6 @@ import org.ehcache.core.spi.store.events.StoreEventListener; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.core.statistics.StoreOperationOutcomes; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.hamcrest.Description; import org.hamcrest.Matcher; @@ -51,6 +51,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.expiry; import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.ehcache.impl.internal.util.Matchers.valueHeld; import static org.ehcache.impl.internal.util.StatisticsTestUtils.validateStats; @@ -88,7 +89,7 @@ public void after() { @Test public void testGetAndRemoveNoValue() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.noExpiration()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration()); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.MISS)); @@ -96,7 +97,7 @@ public void testGetAndRemoveNoValue() throws Exception { @Test public void testGetAndRemoveValue() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.noExpiration()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration()); offHeapStore.put("1", "one"); assertThat(offHeapStore.getAndRemove("1").value(), equalTo("one")); @@ -106,7 +107,7 @@ public void testGetAndRemoveValue() throws Exception { @Test public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); @@ -124,7 +125,7 @@ public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { @Test public void testInstallMapping() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).value(), equalTo("one")); @@ -142,7 +143,7 @@ public void testInstallMapping() throws Exception { @Test public void testInvalidateKeyAbsent() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); final AtomicReference> invalidated = new AtomicReference<>(); offHeapStore.setInvalidationListener((key, valueHolder) -> invalidated.set(valueHolder)); @@ -154,7 +155,7 @@ public void testInvalidateKeyAbsent() throws Exception { @Test public void testInvalidateKeyPresent() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("1", "one"); @@ -170,7 +171,7 @@ public void testInvalidateKeyPresent() throws Exception { @Test public void testClear() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("1", "one"); offHeapStore.put("2", "two"); @@ -184,7 +185,7 @@ public void testClear() throws Exception { @Test public void testWriteBackOfValueHolder() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); offHeapStore.put("key1", "value1"); timeSource.advanceTime(10); @@ -198,7 +199,7 @@ public void testWriteBackOfValueHolder() throws StoreAccessException { @Test public void testEvictionAdvisor() throws StoreAccessException { - ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L)); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)); EvictionAdvisor evictionAdvisor = (key, value) -> true; performEvictionTest(timeSource, expiry, evictionAdvisor); @@ -206,7 +207,7 @@ public void testEvictionAdvisor() throws StoreAccessException { @Test public void testBrokenEvictionAdvisor() throws StoreAccessException { - ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L)); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)); EvictionAdvisor evictionAdvisor = (key, value) -> { throw new UnsupportedOperationException("Broken advisor!"); }; @@ -216,7 +217,7 @@ public void testBrokenEvictionAdvisor() throws StoreAccessException { @Test public void testFlushUpdatesAccessStats() throws StoreAccessException { - ExpiryPolicy expiry = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(15L)); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L)); offHeapStore = createAndInitStore(timeSource, expiry); try { final String key = "foo"; @@ -240,7 +241,7 @@ public void testFlushUpdatesAccessStats() throws StoreAccessException { @Test public void testFlushUpdatesHits() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.noExpiration()); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration()); final String key = "foo1"; final String value = "bar1"; offHeapStore.put(key, value); @@ -255,7 +256,7 @@ public void testFlushUpdatesHits() throws StoreAccessException { @Test public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); final List expiredKeys = new ArrayList<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { @@ -279,7 +280,7 @@ public void testExpiryEventFiredOnExpiredCachedEntry() throws StoreAccessExcepti @Test public void testGetWithExpiryOnAccess() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.builder().setAccess(Duration.ZERO).build()); + offHeapStore = createAndInitStore(timeSource, expiry().access(Duration.ZERO).build()); offHeapStore.put("key", "value"); final AtomicReference expired = new AtomicReference<>(); offHeapStore.getStoreEventSource().addEventListener(event -> { @@ -368,7 +369,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o @Test public void testGetAndFaultOnExpiredEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); try { offHeapStore.put("key", "value"); timeSource.advanceTime(20L); @@ -385,7 +386,7 @@ public void testGetAndFaultOnExpiredEntry() throws StoreAccessException { public void testComputeExpiresOnAccess() throws StoreAccessException { timeSource.advanceTime(1000L); offHeapStore = createAndInitStore(timeSource, - ExpiryPolicies.builder().setAccess(Duration.ZERO).setUpdate(Duration.ZERO).build()); + expiry().access(Duration.ZERO).update(Duration.ZERO).build()); offHeapStore.put("key", "value"); Store.ValueHolder result = offHeapStore.compute("key", (s, s2) -> s2, () -> false); @@ -398,7 +399,7 @@ public void testComputeExpiresOnUpdate() throws StoreAccessException { timeSource.advanceTime(1000L); offHeapStore = createAndInitStore(timeSource, - ExpiryPolicies.builder().setAccess(Duration.ZERO).setUpdate(Duration.ZERO).build()); + expiry().access(Duration.ZERO).update(Duration.ZERO).build()); offHeapStore.put("key", "value"); Store.ValueHolder result = offHeapStore.compute("key", (s, s2) -> "newValue", () -> false); @@ -408,7 +409,7 @@ public void testComputeExpiresOnUpdate() throws StoreAccessException { @Test public void testComputeOnExpiredEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); offHeapStore.put("key", "value"); timeSource.advanceTime(20L); @@ -423,7 +424,7 @@ public void testComputeOnExpiredEntry() throws StoreAccessException { @Test public void testComputeIfAbsentOnExpiredEntry() throws StoreAccessException { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(10L))); offHeapStore.put("key", "value"); timeSource.advanceTime(20L); @@ -437,7 +438,7 @@ public void testComputeIfAbsentOnExpiredEntry() throws StoreAccessException { @Test public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); offHeapStore.put("key2", "value2"); @@ -466,7 +467,7 @@ public void testIteratorDoesNotSkipOrExpiresEntries() throws Exception { @Test public void testIteratorWithSingleExpiredEntry() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); @@ -480,7 +481,7 @@ public void testIteratorWithSingleExpiredEntry() throws Exception { @Test public void testIteratorWithSingleNonExpiredEntry() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); offHeapStore.put("key1", "value1"); @@ -493,7 +494,7 @@ public void testIteratorWithSingleNonExpiredEntry() throws Exception { @Test public void testIteratorOnEmptyStore() throws Exception { - offHeapStore = createAndInitStore(timeSource, ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(10L))); + offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(10L))); Store.Iterator>> iterator = offHeapStore.iterator(); assertFalse(iterator.hasNext()); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java index 72926b27d1..7546e92beb 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/OffHeapStoreSPITest.java @@ -18,11 +18,11 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.SizedResourcePool; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.events.TestStoreEventDispatcher; import org.ehcache.core.spi.time.SystemTimeSource; @@ -55,12 +55,12 @@ public void setUp() { authoritativeTierFactory = new AuthoritativeTierFactory() { @Override public AuthoritativeTier newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public AuthoritativeTier newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -70,7 +70,7 @@ public AuthoritativeTier newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java index ea91370275..088b0a08b9 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTierSPITest.java @@ -17,11 +17,11 @@ package org.ehcache.impl.internal.store.tiering; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.events.StoreEventDispatcher; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; @@ -77,7 +77,7 @@ public CachingTier newCachingTier(long capacity) { private CachingTier newCachingTier(Long capacity) { Store.Configuration config = new StoreConfigurationImpl<>(getKeyType(), getValueType(), null, - ClassLoader.getSystemClassLoader(), ExpiryPolicies.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); + ClassLoader.getSystemClassLoader(), ExpiryPolicyBuilder.noExpiration(), buildResourcePools(capacity), 0, new JavaSerializer<>(getSystemClassLoader()), new JavaSerializer<>(getSystemClassLoader())); StoreEventDispatcher eventDispatcher = NullStoreEventDispatcher.nullStoreEventDispatcher(); OffHeapStore offHeapStore = new OffHeapStore<>(config, SystemTimeSource.INSTANCE, eventDispatcher, 10 * 1024 * 1024); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java index d7d8f2c398..e9872d2af9 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreFlushWhileShutdownTest.java @@ -19,8 +19,8 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.spi.service.DiskResourceService; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.config.units.EntryUnit; @@ -80,7 +80,7 @@ public ClassLoader getClassLoader() { @Override public ExpiryPolicy getExpiry() { - return ExpiryPolicies.noExpiration(); + return ExpiryPolicyBuilder.noExpiration(); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java index 48c1389b05..879f4aff7d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java @@ -16,6 +16,7 @@ package org.ehcache.impl.internal.store.tiering; import org.ehcache.config.ResourcePools; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.internal.store.StoreConfigurationImpl; @@ -26,7 +27,6 @@ import org.ehcache.core.spi.time.SystemTimeSource; import org.ehcache.docs.plugs.StringCopier; import org.ehcache.core.events.NullStoreEventDispatcher; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; import org.ehcache.impl.internal.store.basic.NopStore; import org.ehcache.impl.internal.store.heap.OnHeapStore; @@ -173,7 +173,7 @@ public void setUp() throws Exception { // Not relevant to the test, just used to instantiate the OnHeapStore Store.Configuration config = new StoreConfigurationImpl<>(String.class, String.class, - null, getClass().getClassLoader(), ExpiryPolicies.noExpiration(), resourcePools, 0, null, null); + null, getClass().getClassLoader(), ExpiryPolicyBuilder.noExpiration(), resourcePools, 0, null, null); // Here again, all parameters are useless, we only care about the beforeCompletingTheFault implementation CachingTier cachingTier = new OnHeapStore<>(config, SystemTimeSource.INSTANCE, diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java index d3105e8c93..37ee936b26 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java @@ -20,13 +20,13 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.SizedResourcePool; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.IdentityCopier; @@ -105,12 +105,12 @@ public void setUp() throws IOException { @Override public Store newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -120,7 +120,7 @@ public Store newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java index ab91cd228c..2f5260a8b7 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java @@ -20,6 +20,7 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.SizedResourcePool; import org.ehcache.core.spi.service.DiskResourceService; @@ -27,7 +28,6 @@ import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.CachePersistenceException; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.ehcache.impl.copy.IdentityCopier; @@ -106,12 +106,12 @@ public void setUp() throws IOException { @Override public Store newStore() { - return newStore(null, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override public Store newStoreWithCapacity(long capacity) { - return newStore(capacity, null, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(capacity, null, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } @Override @@ -121,7 +121,7 @@ public Store newStoreWithExpiry(ExpiryPolicy newStoreWithEvictionAdvisor(EvictionAdvisor evictionAdvisor) { - return newStore(null, evictionAdvisor, ExpiryPolicies.noExpiration(), SystemTimeSource.INSTANCE); + return newStore(null, evictionAdvisor, ExpiryPolicyBuilder.noExpiration(), SystemTimeSource.INSTANCE); } private Store newStore(Long capacity, EvictionAdvisor evictionAdvisor, ExpiryPolicy expiry, TimeSource timeSource) { diff --git a/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java b/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java index f46b0c1fe8..be991fff9c 100644 --- a/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/EventNotificationTest.java @@ -18,6 +18,7 @@ import org.ehcache.Cache; import org.ehcache.CacheManager; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.EhcacheWithLoaderWriter; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheManagerBuilder; @@ -28,7 +29,6 @@ import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.event.EventType; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.junit.Test; import org.slf4j.Logger; @@ -244,7 +244,7 @@ public void testEventFiringInCacheIterator() { CacheConfiguration cacheConfiguration = newCacheConfigurationBuilder(Long.class, String.class, newResourcePoolsBuilder() .heap(5L, EntryUnit.ENTRIES).build()) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration) .using(new TimeSourceConfiguration(testTimeSource)) @@ -281,7 +281,7 @@ public void testMultiThreadedSyncAsyncNotifications() throws InterruptedExceptio CacheConfiguration cacheConfiguration = newCacheConfigurationBuilder(Number.class, Number.class, newResourcePoolsBuilder().heap(10L, EntryUnit.ENTRIES)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))) .build(); CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("cache", cacheConfiguration) diff --git a/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java b/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java index bed2718b2b..0d88be9df1 100644 --- a/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java +++ b/integration-test/src/test/java/org/ehcache/integration/ExpiryEhcacheTestBase.java @@ -19,7 +19,7 @@ import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.hamcrest.Matchers; import org.junit.After; @@ -52,7 +52,7 @@ public void setUp() throws Exception { CacheManagerBuilder builder = CacheManagerBuilder.newCacheManagerBuilder().using(new TimeSourceConfiguration(manualTimeSource)); cacheManager = builder.build(true); CacheConfigurationBuilder objectObjectCacheConfigurationBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))); testCache = cacheManager.createCache("testCache", objectObjectCacheConfigurationBuilder.build()); } diff --git a/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java b/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java index 944edc1cfb..6c8c90d383 100644 --- a/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/ExpiryEventsTest.java @@ -20,8 +20,8 @@ import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.persistence.CacheManagerPersistenceConfiguration; import org.ehcache.config.units.EntryUnit; @@ -42,7 +42,6 @@ import java.util.EnumSet; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.TimeUnit; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; import static org.hamcrest.MatcherAssert.assertThat; @@ -58,7 +57,7 @@ public class ExpiryEventsTest { private static final CacheConfigurationBuilder byRefCacheConfigBuilder = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))); private static final CacheConfigurationBuilder byValueCacheConfigBuilder = byRefCacheConfigBuilder.add(new DefaultCopierConfiguration<>( diff --git a/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java b/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java index cb167c1add..a6997c6c8d 100644 --- a/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java @@ -20,7 +20,6 @@ import java.util.HashMap; import java.util.Iterator; import java.util.Map; -import java.util.concurrent.TimeUnit; import org.assertj.core.data.MapEntry; import org.ehcache.Cache; @@ -28,9 +27,9 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.core.spi.service.StatisticsService; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.impl.internal.statistics.DefaultStatisticsService; @@ -65,7 +64,7 @@ public void before() throws Exception { CacheConfiguration cacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, String.class, resources) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) .build(); StatisticsService statisticsService = new DefaultStatisticsService(); diff --git a/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java b/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java index adf0477310..8bdd9c4b26 100644 --- a/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/transactions/xa/XACacheTest.java @@ -22,10 +22,11 @@ import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.time.TimeSource; -import org.ehcache.expiry.ExpiryPolicies; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.persistence.CacheManagerPersistenceConfiguration; import org.ehcache.impl.internal.DefaultTimeSourceService; @@ -273,7 +274,7 @@ public void testExpiry() throws Exception { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) @@ -431,7 +432,7 @@ public void testConcurrentTx() throws Exception { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) @@ -496,7 +497,7 @@ public void testAtomicsWithoutLoaderWriter() throws Exception { .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB) ) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) @@ -524,7 +525,7 @@ public void testAtomicsWithLoaderWriter() throws Exception { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))) + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))) .withLoaderWriter(loaderWriter); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() @@ -674,7 +675,7 @@ public void testIterate() throws Throwable { newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .offheap(10, MemoryUnit.MB)) - .withExpiry(ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1))); + .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1))); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("txCache1", cacheConfigurationBuilder.add(new XAStoreConfiguration("txCache1")).build()) diff --git a/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java b/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java index 1ffe623b81..bb1a52ebce 100644 --- a/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java +++ b/management/src/test/java/org/ehcache/management/providers/settings/EhcacheSettingsProviderTest.java @@ -21,9 +21,9 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.management.SharedManagementService; import org.ehcache.management.registry.DefaultManagementRegistryConfiguration; @@ -43,7 +43,6 @@ import java.time.Duration; import java.util.Collection; import java.util.Scanner; -import java.util.concurrent.TimeUnit; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.junit.Assert.assertEquals; @@ -77,7 +76,7 @@ public void test_standalone_ehcache() throws IOException { .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .disk(2, MemoryUnit.MB, true)) - .withExpiry(ExpiryPolicies.noExpiration()) + .withExpiry(ExpiryPolicyBuilder.noExpiration()) .build(); CacheConfiguration cacheConfiguration2 = CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class, String.class, @@ -85,7 +84,7 @@ public void test_standalone_ehcache() throws IOException { .heap(10, EntryUnit.ENTRIES) .offheap(1, MemoryUnit.MB) .disk(2, MemoryUnit.MB, true)) - .withExpiry(ExpiryPolicies.timeToIdleExpiration(Duration.ofHours(2))) + .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofHours(2))) .build(); // ehcache cache manager diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java index 05c07048e8..5ab7c6d9d6 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/integration/StatefulSerializerTest.java @@ -23,8 +23,8 @@ import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.transactions.xa.configuration.XAStoreConfiguration; import org.ehcache.transactions.xa.txmgr.btm.BitronixTransactionManagerLookup; import org.ehcache.transactions.xa.txmgr.provider.LookupTransactionManagerProviderConfiguration; @@ -63,7 +63,7 @@ public void testXAWithStatefulSerializer() throws Exception { CacheConfigurationBuilder .newCacheConfigurationBuilder(Long.class, Person.class, ResourcePoolsBuilder.heap(5)) - .withExpiry(ExpiryPolicies.noExpiration()).add(new XAStoreConfiguration("xaCache")) + .withExpiry(ExpiryPolicyBuilder.noExpiration()).add(new XAStoreConfiguration("xaCache")) .build()) .build(true)) { diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java index 3efdc84316..b057655e23 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java @@ -21,6 +21,7 @@ import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourceType; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; @@ -29,7 +30,6 @@ import org.ehcache.core.internal.service.ServiceLocator; import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.store.Store; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; import org.ehcache.core.events.NullStoreEventDispatcher; @@ -92,8 +92,8 @@ import static java.time.Duration.ofSeconds; import static java.util.Collections.emptySet; +import static org.ehcache.config.builders.ExpiryPolicyBuilder.timeToLiveExpiration; import static org.ehcache.core.internal.service.ServiceLocator.dependencySet; -import static org.ehcache.expiry.ExpiryPolicies.timeToLiveExpiration; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; @@ -136,7 +136,7 @@ public void setUp() { keyCopier = copyProvider.createKeyCopier(Long.class, keySerializer); valueCopier = copyProvider.createValueCopier(valueClass, valueSerializer); Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, - null, classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + null, classLoader, ExpiryPolicyBuilder.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .build(), 0, keySerializer, valueSerializer); @@ -691,7 +691,7 @@ public void testReplace3Args() throws Exception { @Test public void testCompute() throws Exception { Store.Configuration> offHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, - null, classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + null, classLoader, ExpiryPolicyBuilder.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .offheap(10, MemoryUnit.MB) .build(), 0, keySerializer, valueSerializer); @@ -867,7 +867,7 @@ public void testCompute() throws Exception { @Test public void testComputeIfAbsent() throws Exception { Store.Configuration> offHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, - classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + classLoader, ExpiryPolicyBuilder.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .offheap(10, MemoryUnit.MB) .build(), 0, keySerializer, valueSerializer); @@ -1090,7 +1090,7 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier o @Test public void testBulkCompute() throws Exception { String uniqueXAResourceId = "testBulkCompute"; - ExpiryPolicy expiry = ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1)); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1)); Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, classLoader, expiry, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build(), 0, keySerializer, valueSerializer); @@ -1166,7 +1166,7 @@ public void testBulkCompute() throws Exception { @Test public void testBulkComputeIfAbsent() throws Exception { - ExpiryPolicy expiry = ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(1)); + ExpiryPolicy expiry = ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(1)); Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, null, classLoader, expiry, ResourcePoolsBuilder.newResourcePoolsBuilder().heap(10, EntryUnit.ENTRIES).build(), 0, keySerializer, valueSerializer); @@ -1237,7 +1237,7 @@ public void testCustomEvictionAdvisor() throws Exception { return false; }; Store.Configuration> onHeapConfig = new StoreConfigurationImpl<>(Long.class, valueClass, - evictionAdvisor, classLoader, ExpiryPolicies.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() + evictionAdvisor, classLoader, ExpiryPolicyBuilder.noExpiration(), ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .build(), 0, keySerializer, valueSerializer); diff --git a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java index 2b152baa4f..1993916c93 100644 --- a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java +++ b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java @@ -24,6 +24,7 @@ import org.ehcache.config.Builder; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheEventListenerConfigurationBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.builders.WriteBehindConfigurationBuilder; import org.ehcache.config.builders.WriteBehindConfigurationBuilder.BatchedWriteBehindConfigurationBuilder; @@ -33,7 +34,6 @@ import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.expiry.Expiry; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; @@ -343,11 +343,11 @@ private void parseConfiguration() } expiry = tmpExpiry; } else if (parsedExpiry.isTTL()) { - expiry = ExpiryPolicies.timeToLiveExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit())); + expiry = ExpiryPolicyBuilder.timeToLiveExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit())); } else if (parsedExpiry.isTTI()) { - expiry = ExpiryPolicies.timeToIdleExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit())); + expiry = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.of(parsedExpiry.value(), parsedExpiry.unit())); } else { - expiry = ExpiryPolicies.noExpiration(); + expiry = ExpiryPolicyBuilder.noExpiration(); } return expiry; } diff --git a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java index 2a335a4178..44ec0951f8 100644 --- a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java +++ b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java @@ -21,10 +21,10 @@ import org.ehcache.config.ResourceType; import org.ehcache.config.ResourceUnit; import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.internal.util.ClassLoading; -import org.ehcache.expiry.ExpiryPolicies; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; @@ -82,7 +82,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -190,7 +189,7 @@ public void testOneCacheConfigWithTemplate() throws Exception { final CacheConfigurationBuilder example = xmlConfig.newCacheConfigurationBuilderFromTemplate("example", String.class, String.class, newResourcePoolsBuilder().heap(5, EntryUnit.ENTRIES)); assertThat(example.build().getExpiryPolicy(), - equalTo((ExpiryPolicy) ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(30)))); + equalTo((ExpiryPolicy) ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(30)))); try { xmlConfig.newCacheConfigurationBuilderFromTemplate("example", String.class, Number.class); @@ -213,11 +212,11 @@ public void testExpiryIsParsed() throws Exception { final XmlConfiguration xmlConfiguration = new XmlConfiguration(XmlConfigurationTest.class.getResource("/configs/expiry-caches.xml")); ExpiryPolicy expiry = xmlConfiguration.getCacheConfigurations().get("none").getExpiryPolicy(); - ExpiryPolicy value = ExpiryPolicies.noExpiration(); + ExpiryPolicy value = ExpiryPolicyBuilder.noExpiration(); assertThat(expiry, is(value)); expiry = xmlConfiguration.getCacheConfigurations().get("notSet").getExpiryPolicy(); - value = ExpiryPolicies.noExpiration(); + value = ExpiryPolicyBuilder.noExpiration(); assertThat(expiry, is(value)); expiry = xmlConfiguration.getCacheConfigurations().get("class").getExpiryPolicy(); @@ -229,11 +228,11 @@ public void testExpiryIsParsed() throws Exception { assertThat(expiry.getExpiryForUpdate(null, null, null), is(Duration.ofSeconds(42))); expiry = xmlConfiguration.getCacheConfigurations().get("tti").getExpiryPolicy(); - value = ExpiryPolicies.timeToIdleExpiration(Duration.ofMillis(500)); + value = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(500)); assertThat(expiry, equalTo(value)); expiry = xmlConfiguration.getCacheConfigurations().get("ttl").getExpiryPolicy(); - value = ExpiryPolicies.timeToLiveExpiration(Duration.ofSeconds(30)); + value = ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(30)); assertThat(expiry, equalTo(value)); } From b1f203d9fa973f936c2d575dabba67f0b8300111 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 20 Dec 2017 19:57:21 +0100 Subject: [PATCH 071/779] Issue #2068 Extract concept of infinite Will allow to refine it later and right now gets aligned with what was picked for the clustered timeouts. --- .../java/org/ehcache/expiry/ExpiryPolicy.java | 2 +- .../store/operations/ExpiryChainResolver.java | 3 ++- .../org/ehcache/core/config/ExpiryUtils.java | 17 +++++++++++++++++ .../core/spi/store/AbstractValueHolder.java | 3 ++- .../impl/internal/store/heap/OnHeapStore.java | 5 +++-- .../store/offheap/AbstractOffHeapStore.java | 5 +++-- 6 files changed, 28 insertions(+), 7 deletions(-) diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java index 6324c5a731..4c5557584c 100644 --- a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java +++ b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java @@ -44,7 +44,7 @@ public interface ExpiryPolicy { /** * A {@link Duration duration} that represents an infinite time. */ - Duration INFINITE = Duration.ofSeconds(Long.MAX_VALUE); + Duration INFINITE = Duration.ofNanos(Long.MAX_VALUE); /** * An {@code ExpiryPolicy} that represents a no expiration policy diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java index 650149bbb6..fb7c00df40 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolver.java @@ -23,6 +23,7 @@ import java.time.Duration; import static java.util.Objects.requireNonNull; +import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; /** * A specialized chain resolver for non-eternal caches. @@ -97,7 +98,7 @@ private long calculateExpiryTime(K key, PutOperation existing, Operation= 0; + } + public static Expiry convertToExpiry(ExpiryPolicy expiryPolicy) { + if (expiryPolicy == ExpiryPolicy.NO_EXPIRY) { + @SuppressWarnings("unchecked") + Expiry expiry = (Expiry) Expirations.noExpiration(); + return expiry; + } + return new Expiry() { @Override @@ -90,6 +101,12 @@ private static org.ehcache.expiry.Duration convertDuration(Duration duration) { } public static ExpiryPolicy convertToExpiryPolicy(Expiry expiry) { + if (expiry == Expirations.noExpiration()) { + @SuppressWarnings("unchecked") + ExpiryPolicy expiryPolicy = (ExpiryPolicy) ExpiryPolicy.NO_EXPIRY; + return expiryPolicy; + } + return new ExpiryPolicy() { @Override public Duration getExpiryForCreation(K key, V value) { diff --git a/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java b/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java index 1ea7cff683..fa864a810e 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java +++ b/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java @@ -23,6 +23,7 @@ import java.util.concurrent.atomic.AtomicLongFieldUpdater; import static java.lang.String.format; +import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; /** * @author Ludovic Orban @@ -82,7 +83,7 @@ private void updateExpirationTime(long update) { public void accessed(long now, Duration expiration) { final TimeUnit timeUnit = nativeTimeUnit(); if (expiration != null) { - if (expiration.getSeconds() == Long.MAX_VALUE) { + if (isExpiryDurationInfinite(expiration)) { setExpirationTime(Store.ValueHolder.NO_EXPIRE, null); } else { long newExpirationTime = ExpiryUtils.getExpirationMillis(now, expiration); diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index 936743d858..f745c38ab7 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -93,6 +93,7 @@ import java.util.function.Supplier; import static org.ehcache.config.Eviction.noAdvice; +import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; import static org.ehcache.core.exceptions.StorePassThroughException.handleRuntimeException; import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.terracotta.statistics.StatisticBuilder.operation; @@ -1355,7 +1356,7 @@ private OnHeapValueHolder newUpdateValueHolder(K key, OnHeapValueHolder ol if (duration == null) { expirationTime = oldValue.expirationTime(OnHeapValueHolder.TIME_UNIT); } else { - if (duration.getSeconds() == Long.MAX_VALUE) { + if (isExpiryDurationInfinite(duration)) { expirationTime = ValueHolder.NO_EXPIRE; } else { expirationTime = ExpiryUtils.getExpirationMillis(now, duration); @@ -1392,7 +1393,7 @@ private OnHeapValueHolder newCreateValueHolder(K key, V value, long now, Stor return null; } - long expirationTime = duration.getSeconds() == Long.MAX_VALUE ? ValueHolder.NO_EXPIRE : ExpiryUtils.getExpirationMillis(now, duration); + long expirationTime = isExpiryDurationInfinite(duration) ? ValueHolder.NO_EXPIRE : ExpiryUtils.getExpirationMillis(now, duration); OnHeapValueHolder holder = null; try { diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index a53e161ece..1f0daef25c 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -55,6 +55,7 @@ import org.terracotta.statistics.StatisticsManager; import org.terracotta.statistics.observer.OperationObserver; +import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; import static org.ehcache.core.exceptions.StorePassThroughException.handleRuntimeException; import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.terracotta.statistics.StatisticBuilder.operation; @@ -1033,7 +1034,7 @@ private OffHeapValueHolder newUpdatedValueHolder(K key, V value, OffHeapValue if (duration == null) { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, existing.expirationTime(OffHeapValueHolder.TIME_UNIT)); - } else if (duration.getSeconds() == Long.MAX_VALUE) { + } else if (isExpiryDurationInfinite(duration)) { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, OffHeapValueHolder.NO_EXPIRE); } else { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, ExpiryUtils.getExpirationMillis(now, duration)); @@ -1056,7 +1057,7 @@ private OffHeapValueHolder newCreateValueHolder(K key, V value, long now, Sto eventSink.created(key, value); - if (duration.getSeconds() == Long.MAX_VALUE) { + if (isExpiryDurationInfinite(duration)) { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, OffHeapValueHolder.NO_EXPIRE); } else { return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, ExpiryUtils.getExpirationMillis(now, duration)); From ee1038d0d91ada859d8d6e12913706cf0786050c Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Mon, 18 Dec 2017 14:34:38 -0500 Subject: [PATCH 072/779] Ehcache base class --- .../java/org/ehcache/jsr107/Eh107Cache.java | 5 +- .../clustered/replication/DuplicateTest.java | 7 +- .../main/java/org/ehcache/core/Ehcache.java | 486 +--------------- .../java/org/ehcache/core/EhcacheBase.java | 503 ++++++++++++++++ .../ehcache/core/EhcacheWithLoaderWriter.java | 536 ++---------------- .../java/org/ehcache/core/InternalCache.java | 2 +- .../ehcache/core/EhcacheBasicCrudBase.java | 2 +- 7 files changed, 568 insertions(+), 973 deletions(-) create mode 100644 core/src/main/java/org/ehcache/core/EhcacheBase.java diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java b/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java index a639c48752..316ad7a6c1 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java @@ -36,9 +36,6 @@ import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; -import java.util.function.BiFunction; -import java.util.function.Function; -import java.util.function.Supplier; import javax.cache.Cache; import javax.cache.CacheManager; @@ -84,7 +81,7 @@ class Eh107Cache implements Cache { registerEhcacheListeners(entry.getKey(), entry.getValue()); } - this.jsr107Cache = ehCache.getJsr107Cache(); + this.jsr107Cache = ehCache.createJsr107Cache(); } @Override diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java index 47b6c43122..73c52e6aac 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java @@ -27,7 +27,7 @@ import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.core.Ehcache; +import org.ehcache.core.EhcacheBase; import org.ehcache.core.internal.resilience.ResilienceStrategy; import org.ehcache.core.spi.store.StoreAccessException; import org.junit.After; @@ -104,7 +104,7 @@ public void duplicateAfterFailoverAreReturningTheCorrectResponse() throws Except //Perform put operations in another thread ExecutorService executorService = Executors.newSingleThreadExecutor(); try { - Future puts = executorService.submit((Runnable) () -> { + Future puts = executorService.submit(() -> { while (true) { int i = currentEntry.getAndIncrement(); if (i >= numEntries) { @@ -132,13 +132,12 @@ public void duplicateAfterFailoverAreReturningTheCorrectResponse() throws Except } private void switchResilienceStrategy(Cache cache) throws Exception { - Field field = Ehcache.class.getDeclaredField("resilienceStrategy"); + Field field = EhcacheBase.class.getDeclaredField("resilienceStrategy"); field.setAccessible(true); ResilienceStrategy newResilienceStrategy = (ResilienceStrategy) Proxy.newProxyInstance(cache.getClass().getClassLoader(), new Class[] { ResilienceStrategy.class}, (proxy, method, args) -> { - System.out.println("In there!!!!!!!!!!!!!!!!!!!!!!!!!"); fail("Failure on " + method.getName(), findStoreAccessException(args)); // 1 is always the exception return null; }); diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index c59583e01f..7eb2668abc 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -16,35 +16,20 @@ package org.ehcache.core; -import java.time.Duration; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; -import java.util.EnumMap; import java.util.HashMap; -import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.Map; -import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.LongAdder; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import org.ehcache.Cache; -import org.ehcache.Status; import org.ehcache.config.CacheConfiguration; -import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.core.events.CacheEventDispatcher; -import org.ehcache.core.internal.resilience.LoggingRobustResilienceStrategy; -import org.ehcache.core.internal.resilience.RecoveryCache; -import org.ehcache.core.internal.resilience.ResilienceStrategy; -import org.ehcache.core.spi.LifeCycled; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.PutStatus; import org.ehcache.core.spi.store.Store.RemoveStatus; @@ -52,7 +37,6 @@ import org.ehcache.core.spi.store.Store.ValueHolder; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.statistics.BulkOps; -import org.ehcache.core.statistics.CacheOperationOutcomes.ClearOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetAllOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome; @@ -67,12 +51,6 @@ import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.slf4j.Logger; -import org.terracotta.statistics.StatisticsManager; -import org.terracotta.statistics.observer.OperationObserver; - -import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; -import static org.terracotta.statistics.StatisticBuilder.operation; /** * Implementation of the {@link Cache} interface when no {@link CacheLoaderWriter} is involved. @@ -82,27 +60,7 @@ * * @see EhcacheWithLoaderWriter */ -public class Ehcache implements InternalCache { - - private final StatusTransitioner statusTransitioner; - - private final Store store; - private final ResilienceStrategy resilienceStrategy; - private final EhcacheRuntimeConfiguration runtimeConfiguration; - private final Jsr107CacheImpl jsr107Cache; - protected final Logger logger; - - private final OperationObserver getObserver = operation(GetOutcome.class).named("get").of(this).tag("cache").build(); - private final OperationObserver getAllObserver = operation(GetAllOutcome.class).named("getAll").of(this).tag("cache").build(); - private final OperationObserver putObserver = operation(PutOutcome.class).named("put").of(this).tag("cache").build(); - private final OperationObserver putAllObserver = operation(PutAllOutcome.class).named("putAll").of(this).tag("cache").build(); - private final OperationObserver removeObserver = operation(RemoveOutcome.class).named("remove").of(this).tag("cache").build(); - private final OperationObserver removeAllObserver = operation(RemoveAllOutcome.class).named("removeAll").of(this).tag("cache").build(); - private final OperationObserver conditionalRemoveObserver = operation(ConditionalRemoveOutcome.class).named("conditionalRemove").of(this).tag("cache").build(); - private final OperationObserver putIfAbsentObserver = operation(PutIfAbsentOutcome.class).named("putIfAbsent").of(this).tag("cache").build(); - private final OperationObserver replaceObserver = operation(ReplaceOutcome.class).named("replace").of(this).tag("cache").build(); - private final Map bulkMethodEntries = new EnumMap<>(BulkOps.class); - private final OperationObserver clearObserver = operation(ClearOutcome.class).named("clear").of(this).tag("cache").build(); +public class Ehcache extends EhcacheBase { /** * Creates a new {@code Ehcache} based on the provided parameters. @@ -117,43 +75,8 @@ public Ehcache(CacheConfiguration configuration, final Store store, } Ehcache(EhcacheRuntimeConfiguration runtimeConfiguration, Store store, - CacheEventDispatcher eventDispatcher, Logger logger, StatusTransitioner statusTransitioner) { - this.store = store; - runtimeConfiguration.addCacheConfigurationListener(store.getConfigurationChangeListeners()); - StatisticsManager.associate(store).withParent(this); - - if (store instanceof RecoveryCache) { - this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(castToRecoveryCache(store)); - } else { - this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(recoveryCache(store)); - } - - this.runtimeConfiguration = runtimeConfiguration; - runtimeConfiguration.addCacheConfigurationListener(eventDispatcher.getConfigurationChangeListeners()); - this.jsr107Cache = new Jsr107CacheImpl(); - - this.logger=logger; - this.statusTransitioner = statusTransitioner; - for (BulkOps bulkOp : BulkOps.values()) { - bulkMethodEntries.put(bulkOp, new LongAdder()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Map getBulkMethodEntries() { - return bulkMethodEntries; - } - - @SuppressWarnings("unchecked") - private RecoveryCache castToRecoveryCache(Store store) { - return (RecoveryCache) store; - } - - private V getNoLoader(K key) { - return get(key); + CacheEventDispatcher eventDispatcher, Logger logger, StatusTransitioner statusTransitioner) { + super(runtimeConfiguration, store, eventDispatcher, logger, statusTransitioner); } /** @@ -161,28 +84,7 @@ private V getNoLoader(K key) { */ @Override public V get(final K key) { - getObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - - try { - final Store.ValueHolder valueHolder = store.get(key); - - // Check for expiry first - if (valueHolder == null) { - getObserver.end(GetOutcome.MISS); - return null; - } else { - getObserver.end(GetOutcome.HIT); - return valueHolder.value(); - } - } catch (StoreAccessException e) { - try { - return resilienceStrategy.getFailure(key, e); - } finally { - getObserver.end(GetOutcome.FAILURE); - } - } + return getNoLoader(key); } /** @@ -215,34 +117,7 @@ public void put(final K key, final V value) { } } - private boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { - return newValueAlreadyExpired(logger, runtimeConfiguration.getExpiryPolicy(), key, oldValue, newValue); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsKey(final K key) { - statusTransitioner.checkAvailable(); - checkNonNull(key); - try { - return store.containsKey(key); - } catch (StoreAccessException e) { - return resilienceStrategy.containsKeyFailure(key, e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void remove(K key) { - removeInternal(key); // ignore return value; - } - - - private boolean removeInternal(final K key) { + protected boolean removeInternal(final K key) { removeObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); @@ -266,40 +141,7 @@ private boolean removeInternal(final K key) { return removed; } - /** - * {@inheritDoc} - */ - @Override - public void clear() { - this.clearObserver.begin(); - statusTransitioner.checkAvailable(); - try { - store.clear(); - this.clearObserver.end(ClearOutcome.SUCCESS); - } catch (StoreAccessException e) { - this.clearObserver.end(ClearOutcome.FAILURE); - resilienceStrategy.clearFailure(e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator> iterator() { - statusTransitioner.checkAvailable(); - return new CacheEntryIterator(false); - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAll(Set keys) throws BulkCacheLoadingException { - return getAllInternal(keys, true); - } - - private Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { + protected Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { getAllObserver.begin(); statusTransitioner.checkAvailable(); checkNonNullContent(keys); @@ -337,14 +179,6 @@ private Map getAllInternal(Set keys, boolean includeNulls) th } } - LinkedHashSet> nullValuesForKeys(final Iterable keys) { - final LinkedHashSet> entries = new LinkedHashSet<>(); - for (K key : keys) { - entries.add(new AbstractMap.SimpleEntry<>(key, null)); - } - return entries; - } - /** * {@inheritDoc} */ @@ -426,10 +260,9 @@ public V putIfAbsent(final K key, final V value) { statusTransitioner.checkAvailable(); checkNonNull(key, value); - boolean absent = false; try { ValueHolder inCache = store.putIfAbsent(key, value); - absent = (inCache == null); + boolean absent = (inCache == null); if (absent) { putIfAbsentObserver.end(PutIfAbsentOutcome.PUT); return null; @@ -439,7 +272,7 @@ public V putIfAbsent(final K key, final V value) { } } catch (StoreAccessException e) { try { - return resilienceStrategy.putIfAbsentFailure(key, value, null, e, absent); + return resilienceStrategy.putIfAbsentFailure(key, value, null, e, false); // FIXME: We can't know if it's absent or not } finally { putIfAbsentObserver.end(PutIfAbsentOutcome.FAILURE); } @@ -454,11 +287,10 @@ public boolean remove(final K key, final V value) { conditionalRemoveObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key, value); - RemoveStatus status = null; boolean removed = false; try { - status = store.remove(key, value); + RemoveStatus status = store.remove(key, value); switch (status) { case REMOVED: removed = true; @@ -475,7 +307,7 @@ public boolean remove(final K key, final V value) { } } catch (StoreAccessException e) { try { - return resilienceStrategy.removeFailure(key, value, e, removed); + return resilienceStrategy.removeFailure(key, value, e, false); // FIXME: We can't know if it's removed or not } finally { conditionalRemoveObserver.end(ConditionalRemoveOutcome.FAILURE); } @@ -518,11 +350,10 @@ public boolean replace(final K key, final V oldValue, final V newValue) { statusTransitioner.checkAvailable(); checkNonNull(key, oldValue, newValue); - ReplaceStatus status = null; boolean success = false; try { - status = store.replace(key, oldValue, newValue); + ReplaceStatus status = store.replace(key, oldValue, newValue); switch (status) { case HIT: success = true; @@ -541,86 +372,16 @@ public boolean replace(final K key, final V oldValue, final V newValue) { return success; } catch (StoreAccessException e) { try { - return resilienceStrategy.replaceFailure(key, oldValue, newValue, e, success); + return resilienceStrategy.replaceFailure(key, oldValue, newValue, e, false); // FIXME: We can't know if there was a match } finally { replaceObserver.end(ReplaceOutcome.FAILURE); } } } - /** - * {@inheritDoc} - */ - @Override - public CacheRuntimeConfiguration getRuntimeConfiguration() { - return runtimeConfiguration; - } - - /** - * {@inheritDoc} - */ - @Override - public void init() { - statusTransitioner.init().succeeded(); - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - statusTransitioner.close().succeeded(); - } - - /** - * {@inheritDoc} - */ @Override - public Status getStatus() { - return statusTransitioner.currentStatus(); - } - - /** - * {@inheritDoc} - */ - @Override - public void addHook(LifeCycled hook) { - statusTransitioner.addHook(hook); - } - - void removeHook(LifeCycled hook) { - statusTransitioner.removeHook(hook); - } - - private static void checkNonNull(Object thing) { - if(thing == null) { - throw new NullPointerException(); - } - } - - private static void checkNonNull(Object... things) { - for (Object thing : things) { - checkNonNull(thing); - } - } - - private void checkNonNullContent(Collection collectionOfThings) { - checkNonNull(collectionOfThings); - for (Object thing : collectionOfThings) { - checkNonNull(thing); - } - } - - private void addBulkMethodEntriesCount(BulkOps op, long count) { - bulkMethodEntries.get(op).add(count); - } - - /** - * {@inheritDoc} - */ - @Override - public Jsr107Cache getJsr107Cache() { - return jsr107Cache; + public Jsr107Cache createJsr107Cache() { + return new Jsr107CacheImpl(); } /** @@ -631,70 +392,7 @@ public CacheLoaderWriter getCacheLoaderWriter() { return null; } - private final class Jsr107CacheImpl implements Jsr107Cache { - @Override - public void loadAll(Set keys, boolean replaceExistingValues, Function, Map> loadFunction) { - if(keys.isEmpty()) { - return ; - } - if (replaceExistingValues) { - loadAllReplace(keys, loadFunction); - } else { - loadAllAbsent(keys, loadFunction); - } - } - - @Override - public Iterator> specIterator() { - return new SpecIterator<>(this, store); - } - - @Override - public V getNoLoader(K key) { - return Ehcache.this.getNoLoader(key); - } - - @Override - public Map getAll(Set keys) { - return Ehcache.this.getAllInternal(keys, false); - } - - private void loadAllAbsent(Set keys, final Function, Map> loadFunction) { - try { - store.bulkComputeIfAbsent(keys, absentKeys -> cacheLoaderWriterLoadAllForKeys(absentKeys, loadFunction).entrySet()); - } catch (StoreAccessException e) { - throw newCacheLoadingException(e); - } - } - - Map cacheLoaderWriterLoadAllForKeys(Iterable keys, Function, Map> loadFunction) { - try { - Map loaded = loadFunction.apply(keys); - - // put into a new map since we can't assume the 107 cache loader returns things ordered, or necessarily with all the desired keys - Map rv = new LinkedHashMap<>(); - for (K key : keys) { - rv.put(key, loaded.get(key)); - } - return rv; - } catch (Exception e) { - throw newCacheLoadingException(e); - } - } - - private void loadAllReplace(Set keys, final Function, Map> loadFunction) { - try { - store.bulkCompute(keys, entries -> { - Collection keys1 = new ArrayList<>(); - for (Map.Entry entry : entries) { - keys1.add(entry.getKey()); - } - return cacheLoaderWriterLoadAllForKeys(keys1, loadFunction).entrySet(); - }); - } catch (StoreAccessException e) { - throw newCacheLoadingException(e); - } - } + private final class Jsr107CacheImpl extends Jsr107CacheBase { @Override public void compute(K key, final BiFunction computeFunction, @@ -799,158 +497,6 @@ public V getAndPut(K key, final V value) { putObserver.end(PutOutcome.PUT); return returnValue; } - - @Override - public boolean remove(K key) { - return removeInternal(key); - } - - @Override - public void removeAll() { - Store.Iterator>> iterator = store.iterator(); - while (iterator.hasNext()) { - try { - Entry> next = iterator.next(); - remove(next.getKey()); - } catch (StoreAccessException cae) { - // skip - } - } - } - } - - private class CacheEntryIterator implements Iterator> { - - private final Store.Iterator>> iterator; - private final boolean quiet; - private Cache.Entry> current; - private Cache.Entry> next; - private StoreAccessException nextException; - - public CacheEntryIterator(boolean quiet) { - this.quiet = quiet; - this.iterator = store.iterator(); - advance(); - } - - private void advance() { - try { - while (iterator.hasNext()) { - next = iterator.next(); - if (getNoLoader(next.getKey()) != null) { - return; - } - } - next = null; - } catch (RuntimeException re) { - nextException = new StoreAccessException(re); - next = null; - } catch (StoreAccessException cae) { - nextException = cae; - next = null; - } - } - - @Override - public boolean hasNext() { - statusTransitioner.checkAvailable(); - return nextException != null || next != null; - } - - @Override - public Entry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - if (!quiet) getObserver.begin(); - if (nextException == null) { - if (!quiet) getObserver.end(org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome.HIT); - current = next; - advance(); - return new ValueHolderBasedEntry<>(current); - } else { - if (!quiet) getObserver.end(org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome.FAILURE); - StoreAccessException cae = nextException; - nextException = null; - return resilienceStrategy.iteratorFailure(cae); - } - } - - @Override - public void remove() { - statusTransitioner.checkAvailable(); - if (current == null) { - throw new IllegalStateException("No current element"); - } - Ehcache.this.remove(current.getKey(), current.getValue().value()); - current = null; - } - } - - private static RecoveryCache recoveryCache(final Store store) { - return new RecoveryCache() { - - @Override - public void obliterate() throws StoreAccessException { - store.clear(); - } - - @Override - public void obliterate(K key) throws StoreAccessException { - store.remove(key); - } - - @Override - public void obliterate(Iterable keys) throws StoreAccessException { - for (K key : keys) { - obliterate(key); - } - } - }; - } - - private static boolean newValueAlreadyExpired(Logger logger, ExpiryPolicy expiry, K key, V oldValue, V newValue) { - if (newValue == null) { - return false; - } - - Duration duration; - try { - if (oldValue == null) { - duration = expiry.getExpiryForCreation(key, newValue); - } else { - duration = expiry.getExpiryForUpdate(key, supplierOf(oldValue), newValue); - } - } catch (RuntimeException re) { - logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); - return true; - } - - if (duration != null && duration.isNegative()) { - return true; - } else { - return Duration.ZERO.equals(duration); - } - } - - private static class ValueHolderBasedEntry implements Cache.Entry { - private final Cache.Entry> storeEntry; - - ValueHolderBasedEntry(Cache.Entry> storeEntry) { - this.storeEntry = storeEntry; - } - - @Override - public K getKey() { - return storeEntry.getKey(); - } - - @Override - public V getValue() { - return storeEntry.getValue().value(); - } - } // The compute function that will return the keys to their NEW values, taking the keys to their old values as input; @@ -999,7 +545,7 @@ public Map getEntriesToRemap() { } private boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { - return Ehcache.newValueAlreadyExpired(logger, expiry, key, oldValue, newValue); + return EhcacheBase.newValueAlreadyExpired(logger, expiry, key, oldValue, newValue); } public AtomicInteger getActualPutCount() { diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java new file mode 100644 index 0000000000..c9ede1eceb --- /dev/null +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -0,0 +1,503 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core; + +import org.ehcache.Cache; +import org.ehcache.Status; +import org.ehcache.config.CacheRuntimeConfiguration; +import org.ehcache.core.events.CacheEventDispatcher; +import org.ehcache.core.internal.resilience.LoggingRobustResilienceStrategy; +import org.ehcache.core.internal.resilience.RecoveryCache; +import org.ehcache.core.internal.resilience.ResilienceStrategy; +import org.ehcache.core.spi.LifeCycled; +import org.ehcache.core.spi.store.Store; +import org.ehcache.core.spi.store.Store.ValueHolder; +import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.core.statistics.BulkOps; +import org.ehcache.core.statistics.CacheOperationOutcomes.ClearOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.GetAllOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.PutAllOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.PutIfAbsentOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.PutOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveAllOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; +import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; +import org.ehcache.spi.loaderwriter.CacheWritingException; +import org.slf4j.Logger; +import org.terracotta.statistics.StatisticsManager; +import org.terracotta.statistics.observer.OperationObserver; + +import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; +import java.util.EnumMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.atomic.LongAdder; +import java.util.function.Function; + +import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; +import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; +import static org.terracotta.statistics.StatisticBuilder.operation; + +/** + * Base implementation of the {@link Cache} interface that is common to all Ehcache implementation + */ +public abstract class EhcacheBase implements InternalCache { + + protected final Logger logger; + + protected final StatusTransitioner statusTransitioner; + + protected final Store store; + protected final ResilienceStrategy resilienceStrategy; + protected final EhcacheRuntimeConfiguration runtimeConfiguration; + + protected final OperationObserver getObserver = operation(GetOutcome.class).named("get").of(this).tag("cache").build(); + protected final OperationObserver getAllObserver = operation(GetAllOutcome.class).named("getAll").of(this).tag("cache").build(); + protected final OperationObserver putObserver = operation(PutOutcome.class).named("put").of(this).tag("cache").build(); + protected final OperationObserver putAllObserver = operation(PutAllOutcome.class).named("putAll").of(this).tag("cache").build(); + protected final OperationObserver removeObserver = operation(RemoveOutcome.class).named("remove").of(this).tag("cache").build(); + protected final OperationObserver removeAllObserver = operation(RemoveAllOutcome.class).named("removeAll").of(this).tag("cache").build(); + protected final OperationObserver conditionalRemoveObserver = operation(ConditionalRemoveOutcome.class).named("conditionalRemove").of(this).tag("cache").build(); + protected final OperationObserver putIfAbsentObserver = operation(PutIfAbsentOutcome.class).named("putIfAbsent").of(this).tag("cache").build(); + protected final OperationObserver replaceObserver = operation(ReplaceOutcome.class).named("replace").of(this).tag("cache").build(); + protected final OperationObserver clearObserver = operation(ClearOutcome.class).named("clear").of(this).tag("cache").build(); + + protected final Map bulkMethodEntries = new EnumMap<>(BulkOps.class); + + /** + * Creates a new {@code EhcacheBase} based on the provided parameters. + * + * @param runtimeConfiguration the cache configuration + * @param store the store to use + * @param eventDispatcher the event dispatcher + * @param logger the logger + */ + EhcacheBase(EhcacheRuntimeConfiguration runtimeConfiguration, Store store, + CacheEventDispatcher eventDispatcher, Logger logger, StatusTransitioner statusTransitioner) { + this.store = store; + runtimeConfiguration.addCacheConfigurationListener(store.getConfigurationChangeListeners()); + StatisticsManager.associate(store).withParent(this); + + if (store instanceof RecoveryCache) { + this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(castToRecoveryCache(store)); + } else { + this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(recoveryCache(store)); + } + + this.runtimeConfiguration = runtimeConfiguration; + runtimeConfiguration.addCacheConfigurationListener(eventDispatcher.getConfigurationChangeListeners()); + + this.logger = logger; + this.statusTransitioner = statusTransitioner; + for (BulkOps bulkOp : BulkOps.values()) { + bulkMethodEntries.put(bulkOp, new LongAdder()); + } + } + + @SuppressWarnings("unchecked") + private RecoveryCache castToRecoveryCache(Store store) { + return (RecoveryCache) store; + } + + private static RecoveryCache recoveryCache(final Store store) { + return new RecoveryCache() { + + @Override + public void obliterate() throws StoreAccessException { + store.clear(); + } + + @Override + public void obliterate(K key) throws StoreAccessException { + store.remove(key); + } + + @Override + public void obliterate(Iterable keys) throws StoreAccessException { + for (K key : keys) { + obliterate(key); + } + } + }; + } + + protected V getNoLoader(K key) { + getObserver.begin(); + statusTransitioner.checkAvailable(); + checkNonNull(key); + + try { + final Store.ValueHolder valueHolder = store.get(key); + + // Check for expiry first + if (valueHolder == null) { + getObserver.end(GetOutcome.MISS); + return null; + } else { + getObserver.end(GetOutcome.HIT); + return valueHolder.value(); + } + } catch (StoreAccessException e) { + try { + return resilienceStrategy.getFailure(key, e); + } finally { + getObserver.end(GetOutcome.FAILURE); + } + } + } + + /** + * {@inheritDoc} + */ + @Override + public boolean containsKey(final K key) { + statusTransitioner.checkAvailable(); + checkNonNull(key); + try { + return store.containsKey(key); + } catch (StoreAccessException e) { + return resilienceStrategy.containsKeyFailure(key, e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public void remove(K key) throws CacheWritingException { + removeInternal(key); // ignore return value; + } + + protected abstract boolean removeInternal(final K key); + + /** + * {@inheritDoc} + */ + @Override + public void clear() { + clearObserver.begin(); + statusTransitioner.checkAvailable(); + try { + store.clear(); + clearObserver.end(ClearOutcome.SUCCESS); + } catch (StoreAccessException e) { + clearObserver.end(ClearOutcome.FAILURE); + resilienceStrategy.clearFailure(e); + } + } + + /** + * {@inheritDoc} + */ + @Override + public Iterator> iterator() { + statusTransitioner.checkAvailable(); + return new CacheEntryIterator(false); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getAll(Set keys) throws BulkCacheLoadingException { + return getAllInternal(keys, true); + } + + protected abstract Map getAllInternal(Set keys, boolean b); + + + protected boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { + return newValueAlreadyExpired(logger, runtimeConfiguration.getExpiryPolicy(), key, oldValue, newValue); + } + + protected static boolean newValueAlreadyExpired(Logger logger, ExpiryPolicy expiry, K key, V oldValue, V newValue) { + if (newValue == null) { + return false; + } + + Duration duration; + try { + if (oldValue == null) { + duration = expiry.getExpiryForCreation(key, newValue); + } else { + duration = expiry.getExpiryForUpdate(key, supplierOf(oldValue), newValue); + } + } catch (RuntimeException re) { + logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); + return true; + } + + return Duration.ZERO.equals(duration); + } + + /** + * {@inheritDoc} + */ + @Override + public CacheRuntimeConfiguration getRuntimeConfiguration() { + return runtimeConfiguration; + } + + /** + * {@inheritDoc} + */ + @Override + public void init() { + statusTransitioner.init().succeeded(); + } + + /** + * {@inheritDoc} + */ + @Override + public void close() { + statusTransitioner.close().succeeded(); + } + + /** + * {@inheritDoc} + */ + @Override + public Status getStatus() { + return statusTransitioner.currentStatus(); + } + + /** + * {@inheritDoc} + */ + @Override + public void addHook(LifeCycled hook) { + statusTransitioner.addHook(hook); + } + + void removeHook(LifeCycled hook) { + statusTransitioner.removeHook(hook); + } + + protected void addBulkMethodEntriesCount(BulkOps op, long count) { + bulkMethodEntries.get(op).add(count); + } + + /** + * {@inheritDoc} + */ + @Override + public Map getBulkMethodEntries() { + return bulkMethodEntries; + } + + protected static void checkNonNull(Object thing) { + Objects.requireNonNull(thing); + } + + protected static void checkNonNull(Object... things) { + for (Object thing : things) { + checkNonNull(thing); + } + } + + protected void checkNonNullContent(Collection collectionOfThings) { + checkNonNull(collectionOfThings); + for (Object thing : collectionOfThings) { + checkNonNull(thing); + } + } + + protected abstract class Jsr107CacheBase implements Jsr107Cache { + + @Override + public void loadAll(Set keys, boolean replaceExistingValues, Function, Map> loadFunction) { + if(keys.isEmpty()) { + return ; + } + if (replaceExistingValues) { + loadAllReplace(keys, loadFunction); + } else { + loadAllAbsent(keys, loadFunction); + } + } + + @Override + public Iterator> specIterator() { + return new SpecIterator<>(this, store); + } + + @Override + public V getNoLoader(K key) { + return EhcacheBase.this.getNoLoader(key); + } + + @Override + public Map getAll(Set keys) { + return getAllInternal(keys, false); + } + + private void loadAllAbsent(Set keys, final Function, Map> loadFunction) { + try { + store.bulkComputeIfAbsent(keys, absentKeys -> cacheLoaderWriterLoadAllForKeys(absentKeys, loadFunction).entrySet()); + } catch (StoreAccessException e) { + throw newCacheLoadingException(e); + } + } + + Map cacheLoaderWriterLoadAllForKeys(Iterable keys, Function, Map> loadFunction) { + try { + Map loaded = loadFunction.apply(keys); + + // put into a new map since we can't assume the 107 cache loader returns things ordered, or necessarily with all the desired keys + Map rv = new LinkedHashMap<>(); + for (K key : keys) { + rv.put(key, loaded.get(key)); + } + return rv; + } catch (Exception e) { + throw newCacheLoadingException(e); + } + } + + private void loadAllReplace(Set keys, final Function, Map> loadFunction) { + try { + store.bulkCompute(keys, entries -> { + Collection keys1 = new ArrayList<>(); + for (Map.Entry entry : entries) { + keys1.add(entry.getKey()); + } + return cacheLoaderWriterLoadAllForKeys(keys1, loadFunction).entrySet(); + }); + } catch (StoreAccessException e) { + throw newCacheLoadingException(e); + } + } + + @Override + public boolean remove(K key) { + return EhcacheBase.this.removeInternal(key); + } + + @Override + public void removeAll() { + Store.Iterator>> iterator = store.iterator(); + while (iterator.hasNext()) { + try { + Entry> next = iterator.next(); + remove(next.getKey()); + } catch (StoreAccessException cae) { + // skip + } + } + } + + } + + private class CacheEntryIterator implements Iterator> { + + private final Store.Iterator>> iterator; + private final boolean quiet; + private Cache.Entry> current; + private Cache.Entry> next; + private StoreAccessException nextException; + + public CacheEntryIterator(boolean quiet) { + this.quiet = quiet; + this.iterator = store.iterator(); + advance(); + } + + private void advance() { + try { + while (iterator.hasNext()) { + next = iterator.next(); + if (getNoLoader(next.getKey()) != null) { + return; + } + } + next = null; + } catch (RuntimeException re) { + nextException = new StoreAccessException(re); + next = null; + } catch (StoreAccessException cae) { + nextException = cae; + next = null; + } + } + + @Override + public boolean hasNext() { + statusTransitioner.checkAvailable(); + return nextException != null || next != null; + } + + @Override + public Entry next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + + if (!quiet) getObserver.begin(); + if (nextException == null) { + if (!quiet) getObserver.end(GetOutcome.HIT); + current = next; + advance(); + return new ValueHolderBasedEntry<>(current); + } else { + if (!quiet) getObserver.end(GetOutcome.FAILURE); + StoreAccessException cae = nextException; + nextException = null; + return resilienceStrategy.iteratorFailure(cae); + } + } + + @Override + public void remove() { + statusTransitioner.checkAvailable(); + if (current == null) { + throw new IllegalStateException("No current element"); + } + EhcacheBase.this.remove(current.getKey(), current.getValue().value()); + current = null; + } + } + + private static class ValueHolderBasedEntry implements Cache.Entry { + private final Cache.Entry> storeEntry; + + ValueHolderBasedEntry(Cache.Entry> storeEntry) { + this.storeEntry = storeEntry; + } + + @Override + public K getKey() { + return storeEntry.getKey(); + } + + @Override + public V getValue() { + return storeEntry.getValue().value(); + } + + } +} + diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index 0f6b94611f..b9e866fce4 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -17,9 +17,7 @@ package org.ehcache.core; import org.ehcache.Cache; -import org.ehcache.Status; import org.ehcache.config.CacheConfiguration; -import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; @@ -27,11 +25,6 @@ import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; -import org.ehcache.expiry.Duration; -import org.ehcache.core.internal.resilience.LoggingRobustResilienceStrategy; -import org.ehcache.core.internal.resilience.RecoveryCache; -import org.ehcache.core.internal.resilience.ResilienceStrategy; -import org.ehcache.core.spi.LifeCycled; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -47,26 +40,19 @@ import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; import org.slf4j.Logger; -import org.terracotta.statistics.StatisticsManager; import org.terracotta.statistics.observer.OperationObserver; -import java.util.AbstractMap; -import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.EnumMap; import java.util.HashMap; import java.util.HashSet; -import java.util.Iterator; import java.util.LinkedHashMap; -import java.util.LinkedHashSet; import java.util.Map; -import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Set; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.LongAdder; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; @@ -74,7 +60,6 @@ import static org.ehcache.core.internal.util.Functions.memoize; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheWritingException; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.terracotta.statistics.StatisticBuilder.operation; /** @@ -85,31 +70,14 @@ * * @see Ehcache */ -public class EhcacheWithLoaderWriter implements InternalCache { +public class EhcacheWithLoaderWriter extends EhcacheBase { - private final StatusTransitioner statusTransitioner; + private static final Supplier REPLACE_FALSE = () -> Boolean.FALSE; - private final Store store; private final CacheLoaderWriter cacheLoaderWriter; - private final ResilienceStrategy resilienceStrategy; - private final EhcacheRuntimeConfiguration runtimeConfiguration; - private final Jsr107CacheImpl jsr107Cache; private final boolean useLoaderInAtomics; - protected final Logger logger; - - private final OperationObserver getObserver = operation(GetOutcome.class).named("get").of(this).tag("cache").build(); - private final OperationObserver getAllObserver = operation(GetAllOutcome.class).named("getAll").of(this).tag("cache").build(); - private final OperationObserver putObserver = operation(PutOutcome.class).named("put").of(this).tag("cache").build(); - private final OperationObserver putAllObserver = operation(PutAllOutcome.class).named("putAll").of(this).tag("cache").build(); - private final OperationObserver removeObserver = operation(RemoveOutcome.class).named("remove").of(this).tag("cache").build(); - private final OperationObserver removeAllObserver = operation(RemoveAllOutcome.class).named("removeAll").of(this).tag("cache").build(); - private final OperationObserver conditionalRemoveObserver = operation(ConditionalRemoveOutcome.class).named("conditionalRemove").of(this).tag("cache").build(); - private final OperationObserver cacheLoadingObserver = operation(CacheLoadingOutcome.class).named("cacheLoading").of(this).tag("cache").build(); - private final OperationObserver putIfAbsentObserver = operation(PutIfAbsentOutcome.class).named("putIfAbsent").of(this).tag("cache").build(); - private final OperationObserver replaceObserver = operation(ReplaceOutcome.class).named("replace").of(this).tag("cache").build(); - private final Map bulkMethodEntries = new EnumMap<>(BulkOps.class); - private static final Supplier REPLACE_FALSE = () -> Boolean.FALSE; + private final OperationObserver cacheLoadingObserver = operation(CacheLoadingOutcome.class).named("cacheLoading").of(this).tag("cache").build(); /** * Constructs a new {@code EhcacheWithLoaderWriter} based on the provided parameters. @@ -136,67 +104,10 @@ public EhcacheWithLoaderWriter(CacheConfiguration configuration, Store runtimeConfiguration, Store store, CacheLoaderWriter cacheLoaderWriter, CacheEventDispatcher eventDispatcher, boolean useLoaderInAtomics, Logger logger, StatusTransitioner statusTransitioner) { - this.store = store; - runtimeConfiguration.addCacheConfigurationListener(store.getConfigurationChangeListeners()); - StatisticsManager.associate(store).withParent(this); - if (cacheLoaderWriter == null) { - throw new NullPointerException("CacheLoaderWriter cannot be null."); - } - this.cacheLoaderWriter = cacheLoaderWriter; - if (store instanceof RecoveryCache) { - this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(castToRecoveryCache(store)); - } else { - this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(recoveryCache(store)); - } - - this.runtimeConfiguration = runtimeConfiguration; - runtimeConfiguration.addCacheConfigurationListener(eventDispatcher.getConfigurationChangeListeners()); - this.jsr107Cache = new Jsr107CacheImpl(); + super(runtimeConfiguration, store, eventDispatcher, logger, statusTransitioner); + this.cacheLoaderWriter = Objects.requireNonNull(cacheLoaderWriter, "CacheLoaderWriter cannot be null"); this.useLoaderInAtomics = useLoaderInAtomics; - this.logger=logger; - this.statusTransitioner = statusTransitioner; - for (BulkOps bulkOp : BulkOps.values()) { - bulkMethodEntries.put(bulkOp, new LongAdder()); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Map getBulkMethodEntries() { - return bulkMethodEntries; - } - - @SuppressWarnings("unchecked") - private RecoveryCache castToRecoveryCache(Store store) { - return (RecoveryCache) store; - } - - private V getNoLoader(K key) { - getObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - - try { - final Store.ValueHolder valueHolder = store.get(key); - - // Check for expiry first - if (valueHolder == null) { - getObserver.end(GetOutcome.MISS); - return null; - } else { - getObserver.end(GetOutcome.HIT); - return valueHolder.value(); - } - } catch (StoreAccessException e) { - try { - return resilienceStrategy.getFailure(key, e); - } finally { - getObserver.end(GetOutcome.FAILURE); - } - } } /** @@ -207,8 +118,9 @@ public V get(final K key) throws CacheLoadingException { getObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); + final Function mappingFunction = memoize(k -> { - V loaded = null; + V loaded; try { cacheLoadingObserver.begin(); loaded = cacheLoaderWriter.load(k); @@ -255,6 +167,7 @@ public void put(final K key, final V value) throws CacheWritingException { putObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key, value); + final BiFunction remappingFunction = memoize((key1, previousValue) -> { try { cacheLoaderWriter.write(key1, value); @@ -282,55 +195,7 @@ public void put(final K key, final V value) throws CacheWritingException { } } - private boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { - if (newValue == null) { - return false; - } - - final Duration duration; - if (oldValue == null) { - try { - duration = runtimeConfiguration.getExpiry().getExpiryForCreation(key, newValue); - } catch (RuntimeException re) { - logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); - return true; - } - } else { - try { - duration = runtimeConfiguration.getExpiry().getExpiryForUpdate(key, supplierOf(oldValue), newValue); - } catch (RuntimeException re) { - logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); - return true; - } - } - - return Duration.ZERO.equals(duration); - } - - /** - * {@inheritDoc} - */ - @Override - public boolean containsKey(final K key) { - statusTransitioner.checkAvailable(); - checkNonNull(key); - try { - return store.containsKey(key); - } catch (StoreAccessException e) { - return resilienceStrategy.containsKeyFailure(key, e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public void remove(K key) throws CacheWritingException { - removeInternal(key); // ignore return value; - } - - - private boolean removeInternal(final K key) throws CacheWritingException { + protected boolean removeInternal(final K key) throws CacheWritingException { removeObserver.begin(); statusTransitioner.checkAvailable(); checkNonNull(key); @@ -371,37 +236,7 @@ private boolean removeInternal(final K key) throws CacheWritingException { return modified.get(); } - /** - * {@inheritDoc} - */ - @Override - public void clear() { - statusTransitioner.checkAvailable(); - try { - store.clear(); - } catch (StoreAccessException e) { - resilienceStrategy.clearFailure(e); - } - } - - /** - * {@inheritDoc} - */ - @Override - public Iterator> iterator() { - statusTransitioner.checkAvailable(); - return new CacheEntryIterator(false); - } - - /** - * {@inheritDoc} - */ - @Override - public Map getAll(Set keys) throws BulkCacheLoadingException { - return getAllInternal(keys, true); - } - - private Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { + protected Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { getAllObserver.begin(); statusTransitioner.checkAvailable(); checkNonNullContent(keys); @@ -472,10 +307,7 @@ private Map getAllInternal(Set keys, boolean includeNulls) th } } catch (StoreAccessException e) { try { - Set toLoad = new HashSet<>(); - for (K key : keys) { - toLoad.add(key); - } + Set toLoad = new HashSet<>(keys); toLoad.removeAll(successes.keySet()); toLoad.removeAll(failures.keySet()); computeFunction.apply(toLoad); @@ -490,14 +322,6 @@ private Map getAllInternal(Set keys, boolean includeNulls) th } } - LinkedHashSet> nullValuesForKeys(final Iterable keys) { - final LinkedHashSet> entries = new LinkedHashSet<>(); - for (K key : keys) { - entries.add(new AbstractMap.SimpleEntry<>(key, null)); - } - return entries; - } - /** * {@inheritDoc} */ @@ -782,7 +606,7 @@ public V putIfAbsent(final K key, final V value) throws CacheWritingException { } } catch (StoreAccessException e) { try { - V loaded = null; + V loaded; try { loaded = mappingFunction.apply(key); } catch (StorePassThroughException f) { @@ -813,19 +637,9 @@ public boolean remove(final K key, final V value) throws CacheWritingException { final AtomicBoolean hit = new AtomicBoolean(); final AtomicBoolean removed = new AtomicBoolean(); final BiFunction remappingFunction = memoize((k, inCache) -> { - if (inCache == null) { - if (useLoaderInAtomics) { - try { - inCache = cacheLoaderWriter.load(key); - if (inCache == null) { - return null; - } - } catch (Exception e) { - throw new StorePassThroughException(newCacheLoadingException(e)); - } - } else { - return null; - } + inCache = loadFromLoaderWriter(key, inCache); + if(inCache == null) { + return null; } hit.set(true); @@ -883,19 +697,9 @@ public V replace(final K key, final V value) throws CacheLoadingException, Cache checkNonNull(key, value); final AtomicReference old = new AtomicReference<>(); final BiFunction remappingFunction = memoize((k, inCache) -> { - if (inCache == null) { - if (useLoaderInAtomics) { - try { - inCache = cacheLoaderWriter.load(key); - if (inCache == null) { - return null; - } - } catch (Exception e) { - throw new StorePassThroughException(newCacheLoadingException(e)); - } - } else { - return null; - } + inCache = loadFromLoaderWriter(key, inCache); + if(inCache == null) { + return null; } try { @@ -941,6 +745,24 @@ public V replace(final K key, final V value) throws CacheLoadingException, Cache } } + private V loadFromLoaderWriter(K key, V inCache) { + if (inCache == null) { + if (useLoaderInAtomics) { + try { + inCache = cacheLoaderWriter.load(key); + if (inCache == null) { + return null; + } + } catch (Exception e) { + throw new StorePassThroughException(newCacheLoadingException(e)); + } + } else { + return null; + } + } + return inCache; + } + /** * {@inheritDoc} */ @@ -954,19 +776,9 @@ public boolean replace(final K key, final V oldValue, final V newValue) throws C final AtomicBoolean hit = new AtomicBoolean(); final BiFunction remappingFunction = memoize((k, inCache) -> { - if (inCache == null) { - if (useLoaderInAtomics) { - try { - inCache = cacheLoaderWriter.load(key); - if (inCache == null) { - return null; - } - } catch (Exception e) { - throw new StorePassThroughException(newCacheLoadingException(e)); - } - } else { - return null; - } + inCache = loadFromLoaderWriter(key, inCache); + if(inCache == null) { + return null; } hit.set(true); @@ -1019,79 +831,9 @@ public boolean replace(final K key, final V oldValue, final V newValue) throws C } } - /** - * {@inheritDoc} - */ - @Override - public CacheRuntimeConfiguration getRuntimeConfiguration() { - return runtimeConfiguration; - } - - /** - * {@inheritDoc} - */ - @Override - public void init() { - statusTransitioner.init().succeeded(); - } - - /** - * {@inheritDoc} - */ - @Override - public void close() { - statusTransitioner.close().succeeded(); - } - - /** - * {@inheritDoc} - */ - @Override - public Status getStatus() { - return statusTransitioner.currentStatus(); - } - - /** - * {@inheritDoc} - */ - @Override - public void addHook(LifeCycled hook) { - statusTransitioner.addHook(hook); - } - - void removeHook(LifeCycled hook) { - statusTransitioner.removeHook(hook); - } - - private static void checkNonNull(Object thing) { - if(thing == null) { - throw new NullPointerException(); - } - } - - private static void checkNonNull(Object... things) { - for (Object thing : things) { - checkNonNull(thing); - } - } - - private void checkNonNullContent(Collection collectionOfThings) { - checkNonNull(collectionOfThings); - for (Object thing : collectionOfThings) { - checkNonNull(thing); - } - } - - private void addBulkMethodEntriesCount(BulkOps op, long count) { - bulkMethodEntries.get(op).add(count); - } - - /** - * {@inheritDoc} - */ @Override - public Jsr107Cache getJsr107Cache() { - return jsr107Cache; + public Jsr107Cache createJsr107Cache() { + return new Jsr107CacheImpl(); } /** @@ -1102,70 +844,7 @@ public CacheLoaderWriter getCacheLoaderWriter() { return this.cacheLoaderWriter; } - private final class Jsr107CacheImpl implements Jsr107Cache { - @Override - public void loadAll(Set keys, boolean replaceExistingValues, Function, Map> loadFunction) { - if(keys.isEmpty()) { - return ; - } - if (replaceExistingValues) { - loadAllReplace(keys, loadFunction); - } else { - loadAllAbsent(keys, loadFunction); - } - } - - @Override - public Iterator> specIterator() { - return new SpecIterator<>(this, store); - } - - @Override - public V getNoLoader(K key) { - return EhcacheWithLoaderWriter.this.getNoLoader(key); - } - - @Override - public Map getAll(Set keys) { - return EhcacheWithLoaderWriter.this.getAllInternal(keys, false); - } - - private void loadAllAbsent(Set keys, final Function, Map> loadFunction) { - try { - store.bulkComputeIfAbsent(keys, absentKeys -> cacheLoaderWriterLoadAllForKeys(absentKeys, loadFunction).entrySet()); - } catch (StoreAccessException e) { - throw newCacheLoadingException(e); - } - } - - Map cacheLoaderWriterLoadAllForKeys(Iterable keys, Function, Map> loadFunction) { - try { - Map loaded = loadFunction.apply(keys); - - // put into a new map since we can't assume the 107 cache loader returns things ordered, or necessarily with all the desired keys - Map rv = new LinkedHashMap<>(); - for (K key : keys) { - rv.put(key, loaded.get(key)); - } - return rv; - } catch (Exception e) { - throw newCacheLoadingException(e); - } - } - - private void loadAllReplace(Set keys, final Function, Map> loadFunction) { - try { - store.bulkCompute(keys, entries -> { - Collection keys1 = new ArrayList<>(); - for (Map.Entry entry : entries) { - keys1.add(entry.getKey()); - } - return cacheLoaderWriterLoadAllForKeys(keys1, loadFunction).entrySet(); - }); - } catch (StoreAccessException e) { - throw newCacheLoadingException(e); - } - } + private final class Jsr107CacheImpl extends Jsr107CacheBase { @Override public void compute(K key, final BiFunction computeFunction, @@ -1293,135 +972,6 @@ public V getAndPut(K key, final V value) { putObserver.end(PutOutcome.PUT); return returnValue; } - - @Override - public boolean remove(K key) { - return removeInternal(key); - } - - @Override - public void removeAll() { - Store.Iterator>> iterator = store.iterator(); - while (iterator.hasNext()) { - try { - Entry> next = iterator.next(); - remove(next.getKey()); - } catch (StoreAccessException cae) { - // skip - } - } - } - } - - private class CacheEntryIterator implements Iterator> { - - private final Store.Iterator>> iterator; - private final boolean quiet; - private Cache.Entry> current; - private Cache.Entry> next; - private StoreAccessException nextException; - - public CacheEntryIterator(boolean quiet) { - this.quiet = quiet; - this.iterator = store.iterator(); - advance(); - } - - private void advance() { - try { - while (iterator.hasNext()) { - next = iterator.next(); - if (getNoLoader(next.getKey()) != null) { - return; - } - } - next = null; - } catch (RuntimeException re) { - nextException = new StoreAccessException(re); - next = null; - } catch (StoreAccessException cae) { - nextException = cae; - next = null; - } - } - - @Override - public boolean hasNext() { - statusTransitioner.checkAvailable(); - return nextException != null || next != null; - } - - @Override - public Entry next() { - if (!hasNext()) { - throw new NoSuchElementException(); - } - - if (!quiet) getObserver.begin(); - if (nextException == null) { - if (!quiet) getObserver.end(GetOutcome.HIT); - current = next; - advance(); - return new ValueHolderBasedEntry<>(current); - } else { - if (!quiet) getObserver.end(GetOutcome.FAILURE); - StoreAccessException cae = nextException; - nextException = null; - return resilienceStrategy.iteratorFailure(cae); - } - } - - @Override - public void remove() { - statusTransitioner.checkAvailable(); - if (current == null) { - throw new IllegalStateException("No current element"); - } - EhcacheWithLoaderWriter.this.remove(current.getKey(), current.getValue().value()); - current = null; - } - } - - - private static RecoveryCache recoveryCache(final Store store) { - return new RecoveryCache() { - - @Override - public void obliterate() throws StoreAccessException { - store.clear(); - } - - @Override - public void obliterate(K key) throws StoreAccessException { - store.remove(key); - } - - @Override - public void obliterate(Iterable keys) throws StoreAccessException { - for (K key : keys) { - obliterate(key); - } - } - }; - } - - private static class ValueHolderBasedEntry implements Cache.Entry { - private final Cache.Entry> storeEntry; - - ValueHolderBasedEntry(Cache.Entry> storeEntry) { - this.storeEntry = storeEntry; - } - - @Override - public K getKey() { - return storeEntry.getKey(); - } - - @Override - public V getValue() { - return storeEntry.getValue().value(); - } - } } diff --git a/core/src/main/java/org/ehcache/core/InternalCache.java b/core/src/main/java/org/ehcache/core/InternalCache.java index 462999b604..f05edd63e8 100644 --- a/core/src/main/java/org/ehcache/core/InternalCache.java +++ b/core/src/main/java/org/ehcache/core/InternalCache.java @@ -44,7 +44,7 @@ public interface InternalCache extends UserManagedCache { * * @return Jsr107Cache */ - Jsr107Cache getJsr107Cache(); + Jsr107Cache createJsr107Cache(); /** * CacheLoaderWriter diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java index 6269d9da9e..99baf09644 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java @@ -220,7 +220,7 @@ protected static Supplier getBooleanSupplier() { protected final ResilienceStrategy setResilienceStrategySpy(final InternalCache ehcache) { assert ehcache != null; try { - final Field resilienceStrategyField = ehcache.getClass().getDeclaredField("resilienceStrategy"); + final Field resilienceStrategyField = EhcacheBase.class.getDeclaredField("resilienceStrategy"); resilienceStrategyField.setAccessible(true); @SuppressWarnings("unchecked") ResilienceStrategy resilienceStrategy = (ResilienceStrategy)resilienceStrategyField.get(ehcache); From 2fbcc59aba30c35ad313daab83b7ec7256988cca Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 20 Dec 2017 15:19:45 -0500 Subject: [PATCH 073/779] Remove deprecation warnings due to expiration --- ...Cache107ConfigurationIntegrationDocTest.java | 2 +- .../org/ehcache/config/CacheConfiguration.java | 4 ++-- .../java/org/ehcache/expiry/DurationTest.java | 1 + .../org/ehcache/expiry/ExpirationsTest.java | 1 + .../core/EhcacheRuntimeConfiguration.java | 4 ++-- .../core/config/BaseCacheConfiguration.java | 4 ++-- .../org/ehcache/core/config/ExpiryUtils.java | 13 ++++++------- .../builders/CacheConfigurationBuilder.java | 5 ++--- .../builders/UserManagedCacheBuilder.java | 5 ++--- .../builders/CacheManagerBuilderTest.java | 9 ++++++--- .../test/java/org/ehcache/docs/Ehcache3.java | 12 +++++------- .../java/org/ehcache/xml/XmlConfiguration.java | 5 ++--- .../java/com/pany/ehcache/DeprecatedExpiry.java | 17 ++++++++--------- .../org/ehcache/xml/XmlConfigurationTest.java | 4 ++-- 14 files changed, 42 insertions(+), 44 deletions(-) diff --git a/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java b/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java index 841d49f95e..a00c93186d 100644 --- a/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java +++ b/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java @@ -200,7 +200,7 @@ public void testWithoutEhcacheExplicitDependencyAndNoCodeChanges() throws Except CacheRuntimeConfiguration foosEhcacheConfig = (CacheRuntimeConfiguration)foosCache.getConfiguration( Eh107Configuration.class).unwrap(CacheRuntimeConfiguration.class); Client client1 = new Client("client1", 1); - foosEhcacheConfig.getExpiry().getExpiryForCreation(42L, client1).getLength(); // <8> + foosEhcacheConfig.getExpiryPolicy().getExpiryForCreation(42L, client1).toMinutes(); // <8> CompleteConfiguration foosConfig = foosCache.getConfiguration(CompleteConfiguration.class); diff --git a/api/src/main/java/org/ehcache/config/CacheConfiguration.java b/api/src/main/java/org/ehcache/config/CacheConfiguration.java index f7d744b700..e2082259a9 100644 --- a/api/src/main/java/org/ehcache/config/CacheConfiguration.java +++ b/api/src/main/java/org/ehcache/config/CacheConfiguration.java @@ -17,7 +17,7 @@ package org.ehcache.config; import org.ehcache.Cache; -import org.ehcache.expiry.Expiry; + import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; @@ -92,7 +92,7 @@ public interface CacheConfiguration { * @deprecated Use {@link #getExpiryPolicy()} */ @Deprecated - Expiry getExpiry(); + org.ehcache.expiry.Expiry getExpiry(); /** * The {@link ExpiryPolicy} rules for the {@link Cache}. diff --git a/api/src/test/java/org/ehcache/expiry/DurationTest.java b/api/src/test/java/org/ehcache/expiry/DurationTest.java index 635a288b90..3b694d479e 100644 --- a/api/src/test/java/org/ehcache/expiry/DurationTest.java +++ b/api/src/test/java/org/ehcache/expiry/DurationTest.java @@ -26,6 +26,7 @@ import org.junit.Test; +@SuppressWarnings("deprecation") public class DurationTest { @Test diff --git a/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java b/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java index 8816331321..223957c3c5 100644 --- a/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java +++ b/api/src/test/java/org/ehcache/expiry/ExpirationsTest.java @@ -23,6 +23,7 @@ import org.junit.Test; +@SuppressWarnings("deprecation") public class ExpirationsTest { @Test diff --git a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java index 5fd8540214..d6180a7af5 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java +++ b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java @@ -26,7 +26,6 @@ import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; import org.ehcache.event.EventType; -import org.ehcache.expiry.Expiry; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; @@ -100,8 +99,9 @@ public ClassLoader getClassLoader() { return this.classLoader; } + @SuppressWarnings("deprecation") @Override - public Expiry getExpiry() { + public org.ehcache.expiry.Expiry getExpiry() { return ExpiryUtils.convertToExpiry(expiry); } diff --git a/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java b/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java index 89a324f56a..c7089c3c2a 100644 --- a/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java +++ b/core/src/main/java/org/ehcache/core/config/BaseCacheConfiguration.java @@ -23,7 +23,6 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; -import org.ehcache.expiry.Expiry; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.service.ServiceConfiguration; @@ -120,8 +119,9 @@ public ClassLoader getClassLoader() { /** * {@inheritDoc} */ + @SuppressWarnings("deprecation") @Override - public Expiry getExpiry() { + public org.ehcache.expiry.Expiry getExpiry() { return ExpiryUtils.convertToExpiry(expiry); } diff --git a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java index dc63c5eef8..7e76e3553c 100644 --- a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java +++ b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java @@ -17,8 +17,6 @@ package org.ehcache.core.config; import org.ehcache.ValueSupplier; -import org.ehcache.expiry.Expirations; -import org.ehcache.expiry.Expiry; import org.ehcache.expiry.ExpiryPolicy; import java.time.Duration; @@ -29,21 +27,22 @@ /** * ExpiryUtils */ +@SuppressWarnings("deprecation") public class ExpiryUtils { public static boolean isExpiryDurationInfinite(Duration duration) { return duration.compareTo(ExpiryPolicy.INFINITE) >= 0; } - public static Expiry convertToExpiry(ExpiryPolicy expiryPolicy) { + public static org.ehcache.expiry.Expiry convertToExpiry(ExpiryPolicy expiryPolicy) { if (expiryPolicy == ExpiryPolicy.NO_EXPIRY) { @SuppressWarnings("unchecked") - Expiry expiry = (Expiry) Expirations.noExpiration(); + org.ehcache.expiry.Expiry expiry = (org.ehcache.expiry.Expiry) org.ehcache.expiry.Expirations.noExpiration(); return expiry; } - return new Expiry() { + return new org.ehcache.expiry.Expiry() { @Override public org.ehcache.expiry.Duration getExpiryForCreation(K key, V value) { @@ -100,8 +99,8 @@ private static org.ehcache.expiry.Duration convertDuration(Duration duration) { } } - public static ExpiryPolicy convertToExpiryPolicy(Expiry expiry) { - if (expiry == Expirations.noExpiration()) { + public static ExpiryPolicy convertToExpiryPolicy(org.ehcache.expiry.Expiry expiry) { + if (expiry == org.ehcache.expiry.Expirations.noExpiration()) { @SuppressWarnings("unchecked") ExpiryPolicy expiryPolicy = (ExpiryPolicy) ExpiryPolicy.NO_EXPIRY; return expiryPolicy; diff --git a/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java b/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java index 8cc7a15137..fe761351a5 100644 --- a/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java @@ -25,7 +25,6 @@ import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.config.store.StoreEventSourceConfiguration; import org.ehcache.core.spi.store.heap.SizeOfEngine; -import org.ehcache.expiry.Expiry; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.event.DefaultCacheEventDispatcherConfiguration; @@ -284,7 +283,7 @@ public CacheConfigurationBuilder withResourcePools(ResourcePoolsBuilder re } /** - * Adds {@link Expiry} configuration to the returned builder. + * Adds {@link org.ehcache.expiry.Expiry} configuration to the returned builder. *

* {@code Expiry} is what controls data freshness in a cache. * @@ -294,7 +293,7 @@ public CacheConfigurationBuilder withResourcePools(ResourcePoolsBuilder re * @deprecated Use {@link #withExpiry(ExpiryPolicy)} instead */ @Deprecated - public CacheConfigurationBuilder withExpiry(Expiry expiry) { + public CacheConfigurationBuilder withExpiry(org.ehcache.expiry.Expiry expiry) { if (expiry == null) { throw new NullPointerException("Null expiry"); } diff --git a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java index 6f4e2b50b7..5377e9fcfb 100644 --- a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java @@ -46,7 +46,6 @@ import org.ehcache.core.spi.store.heap.SizeOfEngine; import org.ehcache.core.spi.store.heap.SizeOfEngineProvider; import org.ehcache.event.CacheEventListener; -import org.ehcache.expiry.Expiry; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.serializer.DefaultSerializerConfiguration; @@ -446,7 +445,7 @@ public final UserManagedCacheBuilder withClassLoader(ClassLoader classL } /** - * Adds {@link Expiry} configuration to the returned builder. + * Adds {@link org.ehcache.expiry.Expiry} configuration to the returned builder. * * @param expiry the expiry to use * @return a new builer with the added expiry @@ -454,7 +453,7 @@ public final UserManagedCacheBuilder withClassLoader(ClassLoader classL * @deprecated Use {@link #withExpiry(ExpiryPolicy)} instead */ @Deprecated - public final UserManagedCacheBuilder withExpiry(Expiry expiry) { + public final UserManagedCacheBuilder withExpiry(org.ehcache.expiry.Expiry expiry) { if (expiry == null) { throw new NullPointerException("Null expiry"); } diff --git a/impl/src/test/java/org/ehcache/config/builders/CacheManagerBuilderTest.java b/impl/src/test/java/org/ehcache/config/builders/CacheManagerBuilderTest.java index a735f7ac07..9eb3724f28 100644 --- a/impl/src/test/java/org/ehcache/config/builders/CacheManagerBuilderTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/CacheManagerBuilderTest.java @@ -43,12 +43,15 @@ public class CacheManagerBuilderTest { @Test public void testIsExtensible() { - final AtomicInteger counter = new AtomicInteger(0); + AtomicInteger counter = new AtomicInteger(0); - final PersistentCacheManager cacheManager = newCacheManagerBuilder().with((CacheManagerConfiguration) other -> { + @SuppressWarnings("unchecked") + CacheManagerConfiguration managerConfiguration = other -> { counter.getAndIncrement(); return mock(CacheManagerBuilder.class); - }).build(true); + }; + + PersistentCacheManager cacheManager = newCacheManagerBuilder().with(managerConfiguration).build(true); assertThat(cacheManager).isNull(); assertThat(counter.get()).isEqualTo(1); diff --git a/impl/src/test/java/org/ehcache/docs/Ehcache3.java b/impl/src/test/java/org/ehcache/docs/Ehcache3.java index 18e2ede059..7bee442b26 100644 --- a/impl/src/test/java/org/ehcache/docs/Ehcache3.java +++ b/impl/src/test/java/org/ehcache/docs/Ehcache3.java @@ -21,14 +21,12 @@ import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; +import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.internal.TestTimeSource; import org.junit.Test; -import java.util.concurrent.TimeUnit; - +import java.time.Duration; public class Ehcache3 { @@ -41,7 +39,7 @@ public void ehcache3Expiry() throws Exception { CacheConfigurationBuilder configuration = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder .heap(100)) - .withExpiry(new Expiry() { // <1> + .withExpiry(new ExpiryPolicy() { // <1> @Override public Duration getExpiryForCreation(Long key, String value) { return getTimeToLiveDuration(key, value); // <2> @@ -80,11 +78,11 @@ public Duration getExpiryForUpdate(Long key, ValueSupplier old private Duration getTimeToLiveDuration(Long key, String value) { // Returns TTL of 10 seconds for keys less than 1000 if (key < 1000) { - return Duration.of(2, TimeUnit.SECONDS); + return Duration.ofSeconds(2); } // Otherwise return 5 seconds TTL - return Duration.of(1, TimeUnit.SECONDS); + return Duration.ofSeconds(5); } diff --git a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java index 1993916c93..38a4b5b20d 100644 --- a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java +++ b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java @@ -33,7 +33,6 @@ import org.ehcache.event.CacheEventListener; import org.ehcache.event.EventFiring; import org.ehcache.event.EventOrdering; -import org.ehcache.expiry.Expiry; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.config.copy.DefaultCopyProviderConfiguration; @@ -330,7 +329,7 @@ private void parseConfiguration() templates.putAll(configurationParser.getTemplates()); } - @SuppressWarnings("unchecked") + @SuppressWarnings({"unchecked", "deprecation"}) private ExpiryPolicy getExpiry(ClassLoader cacheClassLoader, ConfigurationParser.Expiry parsedExpiry) throws ClassNotFoundException, InstantiationException, IllegalAccessException { final ExpiryPolicy expiry; @@ -339,7 +338,7 @@ private void parseConfiguration() try { tmpExpiry = getInstanceOfName(parsedExpiry.type(), cacheClassLoader, ExpiryPolicy.class); } catch (ClassCastException e) { - tmpExpiry = ExpiryUtils.convertToExpiryPolicy(getInstanceOfName(parsedExpiry.type(), cacheClassLoader, Expiry.class)); + tmpExpiry = ExpiryUtils.convertToExpiryPolicy(getInstanceOfName(parsedExpiry.type(), cacheClassLoader, org.ehcache.expiry.Expiry.class)); } expiry = tmpExpiry; } else if (parsedExpiry.isTTL()) { diff --git a/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java b/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java index ed99132cf6..ec72519cd3 100644 --- a/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java +++ b/xml/src/test/java/com/pany/ehcache/DeprecatedExpiry.java @@ -17,27 +17,26 @@ package com.pany.ehcache; import org.ehcache.ValueSupplier; -import org.ehcache.expiry.Duration; -import org.ehcache.expiry.Expiry; import java.util.concurrent.TimeUnit; /** * @author Alex Snaps */ -public class DeprecatedExpiry implements Expiry { +@SuppressWarnings("deprecation") +public class DeprecatedExpiry implements org.ehcache.expiry.Expiry { @Override - public Duration getExpiryForCreation(final Object key, final Object value) { - return Duration.of(42, TimeUnit.SECONDS); + public org.ehcache.expiry.Duration getExpiryForCreation(final Object key, final Object value) { + return org.ehcache.expiry.Duration.of(42, TimeUnit.SECONDS); } @Override - public Duration getExpiryForAccess(final Object key, final ValueSupplier value) { - return Duration.of(42, TimeUnit.SECONDS); + public org.ehcache.expiry.Duration getExpiryForAccess(final Object key, final ValueSupplier value) { + return org.ehcache.expiry.Duration.of(42, TimeUnit.SECONDS); } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { - return Duration.of(42, TimeUnit.SECONDS); + public org.ehcache.expiry.Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + return org.ehcache.expiry.Duration.of(42, TimeUnit.SECONDS); } } diff --git a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java index 44ec0951f8..39b695adba 100644 --- a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java +++ b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java @@ -211,8 +211,8 @@ public void testOneCacheConfigWithTemplate() throws Exception { public void testExpiryIsParsed() throws Exception { final XmlConfiguration xmlConfiguration = new XmlConfiguration(XmlConfigurationTest.class.getResource("/configs/expiry-caches.xml")); - ExpiryPolicy expiry = xmlConfiguration.getCacheConfigurations().get("none").getExpiryPolicy(); - ExpiryPolicy value = ExpiryPolicyBuilder.noExpiration(); + ExpiryPolicy expiry = xmlConfiguration.getCacheConfigurations().get("none").getExpiryPolicy(); + ExpiryPolicy value = ExpiryPolicyBuilder.noExpiration(); assertThat(expiry, is(value)); expiry = xmlConfiguration.getCacheConfigurations().get("notSet").getExpiryPolicy(); From fadb399385b2259442ea20679ba81e5624c3a19d Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Wed, 27 Dec 2017 11:38:36 -0500 Subject: [PATCH 074/779] :arrow_up: Upgrade to new tc-core version --- gradle.properties | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gradle.properties b/gradle.properties index 07797c462d..7fac8f33e4 100644 --- a/gradle.properties +++ b/gradle.properties @@ -8,10 +8,10 @@ sizeofVersion = 0.3.0 ehcache2Version = 2.10.3 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre6 -terracottaApisVersion = 1.4.0-pre7 -terracottaCoreVersion = 5.4.0-pre13 -terracottaPassthroughTestingVersion = 1.4.0-pre8 +terracottaPlatformVersion = 5.4.0-pre8 +terracottaApisVersion = 1.4.0-pre8 +terracottaCoreVersion = 5.4.0-pre14 +terracottaPassthroughTestingVersion = 1.4.0-pre9 # Test lib versions junitVersion = 4.12 From 4a196870ef1978dc0a944582c0217f3338693b6f Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Tue, 2 Jan 2018 10:22:10 -0500 Subject: [PATCH 075/779] :bug: Close #2227: Ehcache 2 jar cannot be in the test classpath of a module because it contains a lot of shaded dependencies that are impacting the test classpath of Ehcache 3 --- .../docs/asciidoc/user/migration-guide.adoc | 27 +++++- gradle.properties | 1 - impl/build.gradle | 3 - .../test/java/org/ehcache/docs/Ehcache2.java | 86 ------------------- 4 files changed, 25 insertions(+), 92 deletions(-) delete mode 100644 impl/src/test/java/org/ehcache/docs/Ehcache2.java diff --git a/docs/src/docs/asciidoc/user/migration-guide.adoc b/docs/src/docs/asciidoc/user/migration-guide.adoc index f6d2ccdd74..091e347a14 100644 --- a/docs/src/docs/asciidoc/user/migration-guide.adoc +++ b/docs/src/docs/asciidoc/user/migration-guide.adoc @@ -25,9 +25,32 @@ Here we are creating a cache manager that has a default time-to-live (TTL) expir Before adding, we verify the expiry and set it on the `Element` only when different than the `Cache` expiry. -[source%nowrap,java,indent=0] +[source,java] ---- -include::{sourcedir34}/impl/src/test/java/org/ehcache/docs/Ehcache2.java[tag=CustomExpiryEhcache2] +int defaultCacheTTLInSeconds = 20; + +CacheManager cacheManager = initCacheManager(); +CacheConfiguration cacheConfiguration = new CacheConfiguration().name("cache") + .maxEntriesLocalHeap(100) + .timeToLiveSeconds(defaultCacheTTLInSeconds); // <1> +cacheManager.addCache(new Cache(cacheConfiguration)); + +Element element = new Element(10L, "Hello"); + +int ttlInSeconds = getTimeToLiveInSeconds((Long)element.getObjectKey(), (String)element.getObjectValue()); // <2> + +if (ttlInSeconds != defaultCacheTTLInSeconds) { // <3> + element.setTimeToLive(ttlInSeconds); +} + +cacheManager.getCache("cache").put(element); + +System.out.println(cacheManager.getCache("cache").get(10L).getObjectValue()); + +sleep(2100); // <4> + +// Now the returned element should be null, as the mapping is expired. +System.out.println(cacheManager.getCache("cache").get(10L)); ---- <1> Expiry duration defined at the cache level. diff --git a/gradle.properties b/gradle.properties index 7fac8f33e4..df52ccf164 100644 --- a/gradle.properties +++ b/gradle.properties @@ -5,7 +5,6 @@ statisticVersion = 1.5.0 jcacheVersion = 1.0.0 slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 -ehcache2Version = 2.10.3 # Terracotta clustered terracottaPlatformVersion = 5.4.0-pre8 diff --git a/impl/build.gradle b/impl/build.gradle index e980104840..aa23d8388e 100644 --- a/impl/build.gradle +++ b/impl/build.gradle @@ -23,9 +23,6 @@ dependencies { exclude group:'org.slf4j', module:'slf4j-api' } testCompile project(path: ':core-spi-test'), 'org.ow2.asm:asm-all:5.0.4' - testCompile (group: 'net.sf.ehcache', name: 'ehcache', version: parent.ehcache2Version) { - exclude group:'org.slf4j', module:'slf4j-api' - } } jar { diff --git a/impl/src/test/java/org/ehcache/docs/Ehcache2.java b/impl/src/test/java/org/ehcache/docs/Ehcache2.java deleted file mode 100644 index f64c78c40b..0000000000 --- a/impl/src/test/java/org/ehcache/docs/Ehcache2.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright Terracotta, Inc. - * - * 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 org.ehcache.docs; - -import net.sf.ehcache.CacheManager; -import net.sf.ehcache.Cache; -import net.sf.ehcache.Element; -import net.sf.ehcache.config.CacheConfiguration; -import org.junit.Test; - - -public class Ehcache2 { - - @Test - public void ehcache2Expiry() throws Exception { - // tag::CustomExpiryEhcache2[] - int defaultCacheTTLInSeconds = 20; - - CacheManager cacheManager = initCacheManager(); - CacheConfiguration cacheConfiguration = new CacheConfiguration().name("cache") - .maxEntriesLocalHeap(100) - .timeToLiveSeconds(defaultCacheTTLInSeconds); // <1> - cacheManager.addCache(new Cache(cacheConfiguration)); - - Element element = new Element(10L, "Hello"); - - int ttlInSeconds = getTimeToLiveInSeconds((Long)element.getObjectKey(), (String)element.getObjectValue()); // <2> - - if (ttlInSeconds != defaultCacheTTLInSeconds) { // <3> - element.setTimeToLive(ttlInSeconds); - } - - cacheManager.getCache("cache").put(element); - - System.out.println(cacheManager.getCache("cache").get(10L).getObjectValue()); - - sleep(2100); // <4> - - // Now the returned element should be null, as the mapping is expired. - System.out.println(cacheManager.getCache("cache").get(10L)); - // end::CustomExpiryEhcache2[] - } - - /** - * Returns the expiry in Seconds for the given key/value pair, based on some complex logic. - * @param key Cache Key - * @param value Cache Value - * @return - */ - private int getTimeToLiveInSeconds(Long key, String value) { - // Returns TTL of 10 seconds for keys less than 1000 - if (key < 1000) { - return 2; - } - - // Otherwise return 5 seconds TTL - return 1; - } - - - /** - * Initialize and return the cache manager. - * @return CacheManager - */ - private CacheManager initCacheManager() { - CacheManager cacheManager = new CacheManager(); - return cacheManager; - } - - private void sleep(int millisecondsToSleep) throws Exception { - Thread.sleep(millisecondsToSleep); - } -} From 041ea41733e4d1ba5913da45e1f77966a850431b Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 28 Dec 2017 16:54:47 -0500 Subject: [PATCH 076/779] Fix multiples issues in the code --- .../ehcache/jsr107/ConfigurationMerger.java | 2 +- .../jsr107/DefaultConfigurationResolver.java | 4 +- .../java/org/ehcache/jsr107/Eh107Cache.java | 37 +++++----- .../org/ehcache/jsr107/Eh107CacheManager.java | 3 +- .../jsr107/Eh107CompleteConfiguration.java | 2 +- .../jsr107/Eh107ReverseConfiguration.java | 2 +- .../org/ehcache/jsr107/ListenerResources.java | 2 +- .../ehcache/jsr107/MultiCacheException.java | 5 +- .../jsr107/config/Jsr107Configuration.java | 4 +- .../ehcache/config/CacheConfiguration.java | 2 +- .../PersistableResourceService.java | 2 - .../ClusteringServiceConfiguration.java | 12 ++-- .../clustered/client/config/Timeouts.java | 1 - .../config/ClusteredResourcePoolImpl.java | 10 --- .../SharedClusteredResourcePoolImpl.java | 5 -- .../ClusteredResourceConfigurationParser.java | 59 +++++++-------- .../ClusteringServiceConfigurationParser.java | 71 ++++++++++--------- .../lock/VoltronReadWriteLockClient.java | 1 - .../service/DefaultClusteringService.java | 6 +- .../client/internal/store/ChainBuilder.java | 4 +- .../client/internal/store/ClusteredStore.java | 19 ++--- .../store/CommonServerStoreProxy.java | 4 +- .../store/SimpleClusterTierClientEntity.java | 4 +- .../operations/EternalChainResolver.java | 2 - .../store/operations/OperationCode.java | 2 +- .../client/service/EntityBusyException.java | 2 +- .../common/internal/lock/LockMessaging.java | 10 +-- .../common/internal/messages/ChainCodec.java | 1 - .../internal/messages/EhcacheCodec.java | 6 +- .../messages/EntityConfigurationCodec.java | 15 ++-- .../internal/messages/ExceptionCodec.java | 3 +- .../messages/LifeCycleMessageCodec.java | 20 +++--- .../internal/messages/MessageCodecUtils.java | 2 - .../messages/ReconnectMessageCodec.java | 5 +- .../internal/util/ByteBufferInputStream.java | 2 +- .../clustered/operations/OperationsTool.java | 2 +- .../VoltronReadWriteLockActiveEntity.java | 1 - ...ltronReadWriteLockServerEntityService.java | 2 +- .../server/messages/LockSyncMessaging.java | 4 +- .../ClusterTierManagerActiveEntity.java | 1 - .../ClusterTierManagerPassiveEntity.java | 23 +++--- ...ClusterTierManagerServerEntityService.java | 4 +- .../server/EhcacheStateServiceImpl.java | 8 +-- .../messages/EhcacheDataSyncMessage.java | 1 - .../internal/messages/EhcacheServerCodec.java | 4 +- .../internal/messages/EhcacheSyncMessage.java | 2 - .../messages/EhcacheSyncMessageCodec.java | 3 +- .../PassiveReplicationMessageCodec.java | 1 - .../server/offheap/OffHeapChainMap.java | 5 +- .../offheap/OffHeapChainStorageEngine.java | 10 +-- .../server/repo/ServerStateRepository.java | 2 +- .../server/repo/StateRepositoryManager.java | 4 +- .../server/state/EhcacheStateService.java | 1 - .../state/EhcacheStateServiceProvider.java | 4 +- .../server/state/InvalidationTracker.java | 1 - .../server/state/ResourcePageSource.java | 9 ++- .../server/store/ClusterTierActiveEntity.java | 3 - .../store/ClusterTierPassiveEntity.java | 8 +-- .../MessageToTrackerSegmentFunction.java | 4 +- .../store/StoreBulkComputeIfAbsentTest.java | 1 - .../store/StoreCreationEventListenerTest.java | 3 - .../store/StoreEvictionEventListenerTest.java | 9 +-- .../store/StoreExpiryEventListenerTest.java | 4 +- .../store/StoreRemovalEventListenerTest.java | 2 - .../store/StoreRemoveKeyValueTest.java | 4 +- .../store/StoreUpdateEventListenerTest.java | 2 - .../internal/tier/AuthoritativeTierFlush.java | 1 - .../internal/tier/CachingTierClear.java | 5 -- .../tier/CachingTierGetOrComputeIfAbsent.java | 4 -- .../internal/tier/CachingTierInvalidate.java | 1 - .../internal/tier/CachingTierRemove.java | 6 -- .../java/org/ehcache/core/EhcacheManager.java | 11 ++- .../core/EhcacheRuntimeConfiguration.java | 12 ++-- .../org/ehcache/core/StatusTransitioner.java | 2 +- .../core/config/ResourcePoolsImpl.java | 20 +++--- .../core/internal/service/ServiceLocator.java | 5 +- .../core/internal/store/StoreSupport.java | 3 +- .../core/spi/service/ServiceFactory.java | 1 - .../core/spi/store/AbstractValueHolder.java | 6 +- .../org/ehcache/core/spi/store/Store.java | 2 +- .../org/ehcache/core/statistics/BulkOps.java | 2 +- .../statistics/CacheOperationOutcomes.java | 14 ++-- .../statistics/StoreOperationOutcomes.java | 2 +- .../ehcache/demos/peeper/PeeperServlet.java | 2 +- .../ehcache/demos/peeper/PeeperServlet.java | 2 +- .../builders/CacheConfigurationBuilder.java | 4 +- ...dExecutionServiceConfigurationBuilder.java | 6 +- .../config/builders/ResourcePoolsBuilder.java | 2 +- .../builders/UserManagedCacheBuilder.java | 6 +- .../impl/events/CacheEventDispatcherImpl.java | 1 - .../classes/ClassInstanceProvider.java | 2 +- .../ClassInstanceProviderConfiguration.java | 2 +- .../classes/commonslang/ClassUtils.java | 6 +- .../classes/commonslang/Validate.java | 1 - .../commonslang/reflect/ConstructorUtils.java | 4 +- .../commonslang/reflect/MemberUtils.java | 4 +- .../concurrent/ConcurrentHashMap.java | 9 ++- .../executor/OnDemandExecutionService.java | 2 +- .../executor/OutOfBandScheduledExecutor.java | 3 - .../executor/PooledExecutionService.java | 2 +- .../writebehind/StripedWriteBehind.java | 2 +- .../DefaultDiskResourceServiceFactory.java | 1 - .../internal/sizeof/DefaultSizeOfEngine.java | 3 +- .../spi/copy/DefaultCopyProvider.java | 2 +- .../impl/internal/statistics/StatsUtils.java | 10 +-- .../impl/internal/store/basic/NopStore.java | 24 +++---- .../internal/store/disk/OffHeapDiskStore.java | 6 +- .../internal/store/heap/KeyCopyBackend.java | 1 - .../store/offheap/AbstractOffHeapStore.java | 8 +-- .../offheap/BinaryOffHeapValueHolder.java | 3 +- .../store/offheap/HeuristicConfiguration.java | 15 ++-- .../store/offheap/LazyOffHeapValueHolder.java | 2 +- .../store/offheap/MemorySizeParser.java | 4 +- .../internal/store/offheap/OffHeapStore.java | 8 +-- .../store/tiering/CompoundCachingTier.java | 1 - .../internal/store/tiering/TieredStore.java | 18 +++-- .../internal/util/ByteBufferInputStream.java | 2 +- .../DefaultDiskResourceService.java | 4 +- .../persistence/FileBasedStateRepository.java | 1 + .../serialization/ByteArraySerializer.java | 4 +- .../impl/serialization/CharSerializer.java | 7 +- .../serialization/CompactJavaSerializer.java | 10 +-- .../impl/serialization/DoubleSerializer.java | 3 +- .../impl/serialization/FloatSerializer.java | 7 +- .../impl/serialization/IntegerSerializer.java | 7 +- .../impl/serialization/LongSerializer.java | 3 +- .../serialization/PlainJavaSerializer.java | 13 +--- .../TransientStateRepository.java | 2 +- .../concurrent/ConcurrentHashMapITest.java | 9 ++- .../util/ByteBufferInputStreamTest.java | 6 +- .../DefaultClusteringManagementService.java | 2 +- .../settings/ExposedCacheSettings.java | 2 +- .../statistics/EhcacheStatisticsProvider.java | 2 +- .../statistics/StandardEhcacheStatistics.java | 3 +- .../registry/DefaultCollectorService.java | 3 - .../DefaultManagementRegistryService.java | 1 - ...entRegistryServiceConfigurationParser.java | 8 +-- .../main/java/org/ehcache/spi/test/After.java | 9 ++- .../java/org/ehcache/spi/test/Before.java | 9 ++- .../java/org/ehcache/spi/test/Result.java | 3 +- .../xa/internal/EhcacheXAResource.java | 4 +- .../xa/internal/SoftLockSerializer.java | 4 +- .../xa/internal/StoreEventSourceWrapper.java | 1 - .../transactions/xa/internal/XAStore.java | 13 ++-- .../xa/internal/XAValueHolder.java | 4 +- .../xa/internal/journal/TransientJournal.java | 6 +- .../txmgr/btm/Ehcache3XAResourceHolder.java | 6 +- .../txmgr/btm/Ehcache3XAResourceProducer.java | 6 +- .../org/ehcache/xml/XmlConfiguration.java | 6 +- 149 files changed, 380 insertions(+), 516 deletions(-) diff --git a/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java b/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java index db33ef8ea2..ce3aeef11f 100644 --- a/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java +++ b/107/src/main/java/org/ehcache/jsr107/ConfigurationMerger.java @@ -81,7 +81,7 @@ ConfigHolder mergeConfigurations(String cacheName, Configuration templateBuilder = null; + CacheConfigurationBuilder templateBuilder; try { templateBuilder = xmlConfiguration.newCacheConfigurationBuilderFromTemplate(templateName, jsr107Configuration.getKeyType(), jsr107Configuration.getValueType()); diff --git a/107/src/main/java/org/ehcache/jsr107/DefaultConfigurationResolver.java b/107/src/main/java/org/ehcache/jsr107/DefaultConfigurationResolver.java index 0db6470554..a4e89bf738 100644 --- a/107/src/main/java/org/ehcache/jsr107/DefaultConfigurationResolver.java +++ b/107/src/main/java/org/ehcache/jsr107/DefaultConfigurationResolver.java @@ -27,9 +27,7 @@ class DefaultConfigurationResolver { static final String DEFAULT_CONFIG_PROPERTY_NAME = "ehcache.jsr107.config.default"; static URI resolveConfigURI(Properties cacheManagerProperties) { - Object config = null; - - config = cacheManagerProperties.get(DEFAULT_CONFIG_PROPERTY_NAME); + Object config = cacheManagerProperties.get(DEFAULT_CONFIG_PROPERTY_NAME); if (config == null) { config = System.getProperties().get(DEFAULT_CONFIG_PROPERTY_NAME); diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java b/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java index 316ad7a6c1..efb80fde4a 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107Cache.java @@ -135,14 +135,7 @@ public void loadAll(Set keys, boolean replaceExistingValues, Comple jsr107Cache.loadAll(keys, replaceExistingValues, this::loadAllFunction); } catch (Exception e) { final CacheLoaderException cle; - if (e instanceof CacheLoaderException) { - cle = (CacheLoaderException) e; - } else if (e.getCause() instanceof CacheLoaderException) { - cle = (CacheLoaderException) e.getCause(); - } else { - cle = new CacheLoaderException(e); - } - + cle = getCacheLoaderException(e); completionListener.onException(cle); return; } @@ -150,6 +143,18 @@ public void loadAll(Set keys, boolean replaceExistingValues, Comple completionListener.onCompletion(); } + private CacheLoaderException getCacheLoaderException(Exception e) { + CacheLoaderException cle; + if (e instanceof CacheLoaderException) { + cle = (CacheLoaderException) e; + } else if (e.getCause() instanceof CacheLoaderException) { + cle = (CacheLoaderException) e.getCause(); + } else { + cle = new CacheLoaderException(e); + } + return cle; + } + private Map loadAllFunction(Iterable keysIterable) { try { Map loadResult = cacheLoaderWriter.loadAllAlways(keysIterable); @@ -159,15 +164,7 @@ private Map loadAllFunction(Iterable keysIterable) { } return resultMap; } catch (Exception e) { - final CacheLoaderException cle; - if (e instanceof CacheLoaderException) { - cle = (CacheLoaderException) e; - } else if (e.getCause() instanceof CacheLoaderException) { - cle = (CacheLoaderException) e.getCause(); - } else { - cle = new CacheLoaderException(e); - } - + CacheLoaderException cle = getCacheLoaderException(e); throw cle; } } @@ -448,7 +445,7 @@ private void closeInternal(boolean destroy, MultiCacheException closeException) } private boolean syncedIsClose() { - if (((UserManagedCache)ehCache).getStatus() == Status.UNINITIALIZED && !hypotheticallyClosed.get()) { + if (ehCache.getStatus() == Status.UNINITIALIZED && !hypotheticallyClosed.get()) { close(); } return hypotheticallyClosed.get(); @@ -619,8 +616,8 @@ public T unwrap(Class clazz) { } } - private static enum MutableEntryOperation { - NONE, ACCESS, CREATE, LOAD, REMOVE, UPDATE; + private enum MutableEntryOperation { + NONE, ACCESS, CREATE, LOAD, REMOVE, UPDATE } private static final Object UNDEFINED = new Object(); diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java b/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java index d96e4a6516..5041aa7cad 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java @@ -52,7 +52,7 @@ class Eh107CacheManager implements CacheManager { private static final Logger LOG = LoggerFactory.getLogger(Eh107CacheManager.class); - private static MBeanServer MBEAN_SERVER = ManagementFactory.getPlatformMBeanServer(); + private static final MBeanServer MBEAN_SERVER = ManagementFactory.getPlatformMBeanServer(); private final Object cachesLock = new Object(); private final ConcurrentMap> caches = new ConcurrentHashMap<>(); @@ -162,6 +162,7 @@ public > Cache createCache(String cach synchronized (cachesLock) { if (config instanceof Eh107Configuration.Eh107ConfigurationWrapper) { + @SuppressWarnings("unchecked") Eh107Configuration.Eh107ConfigurationWrapper configurationWrapper = (Eh107Configuration.Eh107ConfigurationWrapper)config; CacheConfiguration unwrap = configurationWrapper.getCacheConfiguration(); final org.ehcache.Cache ehcache; diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107CompleteConfiguration.java b/107/src/main/java/org/ehcache/jsr107/Eh107CompleteConfiguration.java index 5dcfe8c74b..041da404fe 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107CompleteConfiguration.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107CompleteConfiguration.java @@ -207,7 +207,7 @@ public T unwrap(Class clazz) { return Unwrap.unwrap(clazz, this, ehcacheConfig); } - private Object writeReplace() throws ObjectStreamException { + private Object writeReplace() { throw new UnsupportedOperationException("Serialization of Ehcache provider configuration classes is not supported"); } diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107ReverseConfiguration.java b/107/src/main/java/org/ehcache/jsr107/Eh107ReverseConfiguration.java index a9199cefc1..c667c8a795 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107ReverseConfiguration.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107ReverseConfiguration.java @@ -102,7 +102,7 @@ public boolean isStoreByValue() { return storeByValueOnHeap; } - private Object writeReplace() throws ObjectStreamException { + private Object writeReplace() { throw new UnsupportedOperationException("Serialization of Ehcache provider configuration classes is not supported"); } } diff --git a/107/src/main/java/org/ehcache/jsr107/ListenerResources.java b/107/src/main/java/org/ehcache/jsr107/ListenerResources.java index d4fa873b92..d707e5ae3b 100644 --- a/107/src/main/java/org/ehcache/jsr107/ListenerResources.java +++ b/107/src/main/java/org/ehcache/jsr107/ListenerResources.java @@ -91,7 +91,7 @@ synchronized List> getEhcacheLi } @Override - public void close() throws IOException { + public void close() { MultiCacheException mce = new MultiCacheException(); CacheResources.close(listener, mce); CacheResources.close(filter, mce); diff --git a/107/src/main/java/org/ehcache/jsr107/MultiCacheException.java b/107/src/main/java/org/ehcache/jsr107/MultiCacheException.java index c3543dd478..de01400d52 100644 --- a/107/src/main/java/org/ehcache/jsr107/MultiCacheException.java +++ b/107/src/main/java/org/ehcache/jsr107/MultiCacheException.java @@ -20,7 +20,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; -import java.util.ListIterator; import javax.cache.CacheException; @@ -47,9 +46,7 @@ void addThrowable(Throwable t) { } if (t instanceof MultiCacheException) { - for (Throwable t2 : ((MultiCacheException)t).getThrowables()) { - throwables.add(t2); - } + throwables.addAll(((MultiCacheException) t).getThrowables()); } else { throwables.add(t); } diff --git a/107/src/main/java/org/ehcache/jsr107/config/Jsr107Configuration.java b/107/src/main/java/org/ehcache/jsr107/config/Jsr107Configuration.java index 13f6cc1ee9..84143757bc 100644 --- a/107/src/main/java/org/ehcache/jsr107/config/Jsr107Configuration.java +++ b/107/src/main/java/org/ehcache/jsr107/config/Jsr107Configuration.java @@ -37,8 +37,8 @@ public class Jsr107Configuration implements ServiceCreationConfiguration templates, boolean jsr107CompliantAtomics, ConfigurationElementState enableManagementAll, ConfigurationElementState enableStatisticsAll) { diff --git a/api/src/main/java/org/ehcache/config/CacheConfiguration.java b/api/src/main/java/org/ehcache/config/CacheConfiguration.java index e2082259a9..a00f258d72 100644 --- a/api/src/main/java/org/ehcache/config/CacheConfiguration.java +++ b/api/src/main/java/org/ehcache/config/CacheConfiguration.java @@ -83,7 +83,7 @@ public interface CacheConfiguration { ClassLoader getClassLoader(); /** - * The {@link Expiry} rules for the {@link Cache}. + * The {@link org.ehcache.expiry.Expiry} rules for the {@link Cache}. *

* The {@code Expiry} cannot be null. * diff --git a/api/src/main/java/org/ehcache/spi/persistence/PersistableResourceService.java b/api/src/main/java/org/ehcache/spi/persistence/PersistableResourceService.java index cede0787b1..41e9e12cd2 100644 --- a/api/src/main/java/org/ehcache/spi/persistence/PersistableResourceService.java +++ b/api/src/main/java/org/ehcache/spi/persistence/PersistableResourceService.java @@ -16,11 +16,9 @@ package org.ehcache.spi.persistence; -import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourceType; import org.ehcache.CachePersistenceException; -import java.util.Collection; import org.ehcache.config.CacheConfiguration; import org.ehcache.spi.service.MaintainableService; import org.ehcache.spi.service.PluralService; diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java index 0499bba666..692a9c0f57 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java @@ -31,8 +31,6 @@ import org.ehcache.clustered.common.ServerSideConfiguration; -import static org.ehcache.clustered.client.config.Timeouts.DEFAULT_OPERATION_TIMEOUT; - /** * Specifies the configuration for a {@link ClusteringService}. */ @@ -210,9 +208,13 @@ public String readableString() { private String readablePoolsString() { StringBuilder pools = new StringBuilder("resourcePools:\n"); - for(Map.Entry entry : serverConfiguration.getResourcePools().entrySet()) { - pools.append(" " + entry.getKey() + ": " + entry.getValue() + "\n"); - } + serverConfiguration.getResourcePools().forEach((key, value) -> { + pools.append(" "); + pools.append(key); + pools.append(": "); + pools.append(value); + pools.append("\n"); + }); return pools.toString(); } } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java index 44ba00bc09..df979b664c 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java @@ -20,7 +20,6 @@ import java.time.Duration; -import java.time.temporal.ChronoUnit; import java.util.function.LongSupplier; /** diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/ClusteredResourcePoolImpl.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/ClusteredResourcePoolImpl.java index 9d1da5223a..5e91d126a9 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/ClusteredResourcePoolImpl.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/ClusteredResourcePoolImpl.java @@ -38,16 +38,6 @@ public PoolAllocation getPoolAllocation() { return new PoolAllocation.Unknown(); } - @Override - public ClusteredResourceType getType() { - return super.getType(); - } - - @Override - public boolean isPersistent() { - return super.isPersistent(); - } - @Override public void validateUpdate(ResourcePool newPool) { throw new UnsupportedOperationException("Updating CLUSTERED resource is not supported"); diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/SharedClusteredResourcePoolImpl.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/SharedClusteredResourcePoolImpl.java index 2b312545b3..5f74e57cce 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/SharedClusteredResourcePoolImpl.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/SharedClusteredResourcePoolImpl.java @@ -46,11 +46,6 @@ public SharedClusteredResourcePoolImpl(final String sharedResourcePool) { this.sharedResourcePool = sharedResourcePool; } - @Override - public ClusteredResourceType getType() { - return super.getType(); - } - @Override public String getSharedResourcePool() { return this.sharedResourcePool; diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteredResourceConfigurationParser.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteredResourceConfigurationParser.java index 11903da55c..efc2838435 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteredResourceConfigurationParser.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteredResourceConfigurationParser.java @@ -52,39 +52,40 @@ public URI getNamespace() { protected ResourcePool parseResourceConfig(final Element fragment) { final String elementName = fragment.getLocalName(); - if ("clustered-shared".equals(elementName)) { - final String sharing = fragment.getAttribute("sharing"); - return new SharedClusteredResourcePoolImpl(sharing); + switch (elementName) { + case "clustered-shared": + final String sharing = fragment.getAttribute("sharing"); + return new SharedClusteredResourcePoolImpl(sharing); - } else if ("clustered-dedicated".equals(elementName)) { - // 'from' attribute is optional on 'clustered-dedicated' element - final Attr fromAttr = fragment.getAttributeNode("from"); - final String from = (fromAttr == null ? null : fromAttr.getValue()); + case "clustered-dedicated": + // 'from' attribute is optional on 'clustered-dedicated' element + final Attr fromAttr = fragment.getAttributeNode("from"); + final String from = (fromAttr == null ? null : fromAttr.getValue()); - final String unitValue = fragment.getAttribute("unit").toUpperCase(); - final MemoryUnit sizeUnits; - try { - sizeUnits = MemoryUnit.valueOf(unitValue); - } catch (IllegalArgumentException e) { - throw new XmlConfigurationException(String.format("XML configuration element <%s> 'unit' attribute '%s' is not valid", elementName, unitValue), e); - } + final String unitValue = fragment.getAttribute("unit").toUpperCase(); + final MemoryUnit sizeUnits; + try { + sizeUnits = MemoryUnit.valueOf(unitValue); + } catch (IllegalArgumentException e) { + throw new XmlConfigurationException(String.format("XML configuration element <%s> 'unit' attribute '%s' is not valid", elementName, unitValue), e); + } - final String sizeValue; - try { - sizeValue = fragment.getFirstChild().getNodeValue(); - } catch (DOMException e) { - throw new XmlConfigurationException(String.format("XML configuration element <%s> value is not valid", elementName), e); - } - final long size; - try { - size = Long.parseLong(sizeValue); - } catch (NumberFormatException e) { - throw new XmlConfigurationException(String.format("XML configuration element <%s> value '%s' is not valid", elementName, sizeValue), e); - } + final String sizeValue; + try { + sizeValue = fragment.getFirstChild().getNodeValue(); + } catch (DOMException e) { + throw new XmlConfigurationException(String.format("XML configuration element <%s> value is not valid", elementName), e); + } + final long size; + try { + size = Long.parseLong(sizeValue); + } catch (NumberFormatException e) { + throw new XmlConfigurationException(String.format("XML configuration element <%s> value '%s' is not valid", elementName, sizeValue), e); + } - return new DedicatedClusteredResourcePoolImpl(from, size, sizeUnits); - } else if("clustered".equals(elementName)) { - return new ClusteredResourcePoolImpl(); + return new DedicatedClusteredResourcePoolImpl(from, size, sizeUnits); + case "clustered": + return new ClusteredResourcePoolImpl(); } return null; } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java index 12d1c93454..f967887b96 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java @@ -54,7 +54,6 @@ import javax.xml.transform.stream.StreamSource; import static org.ehcache.clustered.client.internal.config.xml.ClusteredCacheConstants.*; -import static org.ehcache.xml.XmlModel.convertToJavaTemporalUnit; import static org.ehcache.xml.XmlModel.convertToJavaTimeUnit; /** @@ -113,43 +112,49 @@ public ServiceCreationConfiguration parseServiceCreationConfi for (int i = 0; i < childNodes.getLength(); i++) { final Node item = childNodes.item(i); if (Node.ELEMENT_NODE == item.getNodeType()) { - if ("connection".equals(item.getLocalName())) { - /* - * is a required element in the XSD - */ - final Attr urlAttribute = ((Element)item).getAttributeNode("url"); - final String urlValue = urlAttribute.getValue(); - try { - connectionUri = new URI(urlValue); - } catch (URISyntaxException e) { - throw new XmlConfigurationException( + switch (item.getLocalName()) { + case "connection": + /* + * is a required element in the XSD + */ + final Attr urlAttribute = ((Element) item).getAttributeNode("url"); + final String urlValue = urlAttribute.getValue(); + try { + connectionUri = new URI(urlValue); + } catch (URISyntaxException e) { + throw new XmlConfigurationException( String.format("Value of %s attribute on XML configuration element <%s> in <%s> is not a valid URI - '%s'", - urlAttribute.getName(), item.getNodeName(), fragment.getTagName(), connectionUri), e); - } + urlAttribute.getName(), item.getNodeName(), fragment.getTagName(), connectionUri), e); + } - } else if ("read-timeout".equals(item.getLocalName())) { - /* - * is an optional element - */ - getTimeout = processTimeout(fragment, item); + break; + case "read-timeout": + /* + * is an optional element + */ + getTimeout = processTimeout(fragment, item); - } else if ("write-timeout".equals(item.getLocalName())) { - /* - * is an optional element - */ - putTimeout = processTimeout(fragment, item); + break; + case "write-timeout": + /* + * is an optional element + */ + putTimeout = processTimeout(fragment, item); - } else if ("connection-timeout".equals(item.getLocalName())) { - /* - * is an optional element - */ - connectionTimeout = processTimeout(fragment, item); + break; + case "connection-timeout": + /* + * is an optional element + */ + connectionTimeout = processTimeout(fragment, item); - } else if ("server-side-config".equals(item.getLocalName())) { - /* - * is an optional element - */ - serverConfig = processServerSideConfig(item); + break; + case "server-side-config": + /* + * is an optional element + */ + serverConfig = processServerSideConfig(item); + break; } } } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockClient.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockClient.java index 24c9cbe7a8..1c9c6ab212 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockClient.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockClient.java @@ -24,7 +24,6 @@ import org.terracotta.connection.entity.Entity; import org.terracotta.entity.EndpointDelegate; import org.terracotta.entity.EntityClientEndpoint; -import org.terracotta.entity.EntityResponse; import org.terracotta.entity.InvokeFuture; import org.terracotta.entity.MessageCodecException; import org.terracotta.exception.EntityException; diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java index 51b5a90c62..b2070c6994 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java @@ -23,7 +23,6 @@ import org.ehcache.clustered.client.internal.ClusterTierManagerClientEntity; import org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory; import org.ehcache.clustered.client.internal.ClusterTierManagerCreationException; -import org.ehcache.clustered.client.internal.ClusterTierManagerNotFoundException; import org.ehcache.clustered.client.internal.ClusterTierManagerValidationException; import org.ehcache.clustered.client.config.Timeouts; import org.ehcache.clustered.client.internal.store.ClusterTierClientEntity; @@ -64,6 +63,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeoutException; +import java.util.stream.Stream; /** * Provides support for accessing server-based cluster services. @@ -254,11 +254,11 @@ public void destroyAll() throws CachePersistenceException { @Override public boolean handlesResourceType(ResourceType resourceType) { - return (Arrays.asList(ClusteredResourceType.Types.values()).contains(resourceType)); + return Stream.of(ClusteredResourceType.Types.values()).anyMatch(t -> t.equals(resourceType)); } @Override - public PersistenceSpaceIdentifier getPersistenceSpaceIdentifier(String name, CacheConfiguration config) throws CachePersistenceException { + public PersistenceSpaceIdentifier getPersistenceSpaceIdentifier(String name, CacheConfiguration config) { ClusteredSpace clusteredSpace = knownPersistenceSpaces.get(name); if(clusteredSpace != null) { return clusteredSpace.identifier; diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ChainBuilder.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ChainBuilder.java index 068e7edc33..81bb3d5fc5 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ChainBuilder.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ChainBuilder.java @@ -38,8 +38,8 @@ private ChainBuilder(List buffers) { //TODO: optimize this & make this mutable public ChainBuilder add(final ByteBuffer payload) { - List newList = new ArrayList<>(); - newList.addAll(this.buffers); + List newList = new ArrayList<>(buffers.size() + 1); + newList.addAll(buffers); newList.add(payload); return new ChainBuilder(newList); } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java index 5cfbd0a75b..ab9f1c7526 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java @@ -429,22 +429,19 @@ public Iterator>> iterator() { } @Override - public ValueHolder compute(final K key, final BiFunction mappingFunction) - throws StoreAccessException { + public ValueHolder compute(final K key, final BiFunction mappingFunction) { // TODO: Make appropriate ServerStoreProxy call throw new UnsupportedOperationException("Implement me"); } @Override - public ValueHolder compute(final K key, final BiFunction mappingFunction, final Supplier replaceEqual) - throws StoreAccessException { + public ValueHolder compute(final K key, final BiFunction mappingFunction, final Supplier replaceEqual) { // TODO: Make appropriate ServerStoreProxy call throw new UnsupportedOperationException("Implement me"); } @Override - public ValueHolder computeIfAbsent(final K key, final Function mappingFunction) - throws StoreAccessException { + public ValueHolder computeIfAbsent(final K key, final Function mappingFunction) { // TODO: Make appropriate ServerStoreProxy call throw new UnsupportedOperationException("Implement me"); } @@ -481,8 +478,7 @@ public Map> bulkCompute(final Set keys, final Fun } @Override - public Map> bulkCompute(final Set keys, final Function>, Iterable>> remappingFunction, final Supplier replaceEqual) - throws StoreAccessException { + public Map> bulkCompute(final Set keys, final Function>, Iterable>> remappingFunction, final Supplier replaceEqual) { // TODO: Make appropriate ServerStoreProxy call throw new UnsupportedOperationException("Implement me"); } @@ -503,8 +499,7 @@ public Map> bulkComputeIfAbsent(final Set keys, f // This timeout handling is safe **only** in the context of a get/read operation! value = null; } - ValueHolder holder = (value != null) ? value : null; - map.put(key, holder); + map.put(key, value); } return map; } else { @@ -710,7 +705,7 @@ public Chain compact(Chain chain) { Serializer keySerializer = clusteredStore.codec.getKeySerializer(); if (keySerializer instanceof StatefulSerializer) { - StateRepository stateRepository = null; + StateRepository stateRepository; try { stateRepository = clusteringService.getStateRepositoryWithin(cacheIdentifier, cacheIdentifier.getId() + "-Key"); } catch (CachePersistenceException e) { @@ -720,7 +715,7 @@ public Chain compact(Chain chain) { } Serializer valueSerializer = clusteredStore.codec.getValueSerializer(); if (valueSerializer instanceof StatefulSerializer) { - StateRepository stateRepository = null; + StateRepository stateRepository; try { stateRepository = clusteringService.getStateRepositoryWithin(cacheIdentifier, cacheIdentifier.getId() + "-Value"); } catch (CachePersistenceException e) { diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java index 72bf749aa7..fee33da8d4 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java @@ -16,7 +16,6 @@ package org.ehcache.clustered.client.internal.store; -import org.ehcache.clustered.client.internal.store.ClusterTierClientEntity.ResponseListener; import org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse; import org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.ClientInvalidateAll; import org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse.ClientInvalidateHash; @@ -34,7 +33,6 @@ import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; -import java.util.Objects; import java.util.concurrent.TimeoutException; import static java.util.Objects.requireNonNull; @@ -124,7 +122,7 @@ public Chain get(long key) throws TimeoutException { } @Override - public void append(long key, ByteBuffer payLoad) throws TimeoutException { + public void append(long key, ByteBuffer payLoad) { try { entity.invokeAndWaitForReceive(new AppendMessage(key, payLoad), true); } catch (Exception e) { diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java index 3cfbabd1e6..8a2fab038c 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java @@ -191,13 +191,13 @@ public EhcacheEntityResponse invokeStateRepositoryOperation(StateRepositoryOpMes } @Override - public void invokeAndWaitForSend(EhcacheOperationMessage message, boolean track) throws ClusterException, TimeoutException { + public void invokeAndWaitForSend(EhcacheOperationMessage message, boolean track) throws TimeoutException { invokeInternal(endpoint.beginInvoke().ackSent(), getTimeoutDuration(message), message, track); } @Override public void invokeAndWaitForReceive(EhcacheOperationMessage message, boolean track) - throws ClusterException, TimeoutException { + throws TimeoutException { invokeInternal(endpoint.beginInvoke().ackReceived(), getTimeoutDuration(message), message, track); } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/EternalChainResolver.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/EternalChainResolver.java index 9868fd5c8a..65d02bbb7d 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/EternalChainResolver.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/EternalChainResolver.java @@ -18,8 +18,6 @@ import org.ehcache.clustered.client.internal.store.operations.codecs.OperationsCodec; -import static java.lang.Math.max; - /** * A specialized chain resolver for eternal caches. * diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/OperationCode.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/OperationCode.java index 691851f458..85cb9b2278 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/OperationCode.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/operations/OperationCode.java @@ -59,7 +59,7 @@ public Operation decode(final ByteBuffer buffer, final Serializer CODEC = new MessageCodec() { @Override - public byte[] encodeMessage(LockOperation message) throws MessageCodecException { + public byte[] encodeMessage(LockOperation message) { return new byte[] { (byte) message.getOperation().ordinal(), (byte) message.getHoldType().ordinal() @@ -33,12 +33,12 @@ public byte[] encodeMessage(LockOperation message) throws MessageCodecException } @Override - public LockOperation decodeMessage(byte[] bytes) throws MessageCodecException { + public LockOperation decodeMessage(byte[] bytes) { return new LockOperation(Operation.values()[bytes[0]], HoldType.values()[bytes[1]]); } @Override - public byte[] encodeResponse(LockTransition response) throws MessageCodecException { + public byte[] encodeResponse(LockTransition response) { if (response.isAcquired()) { return new byte[] {0x00}; } else if (response.isReleased()) { @@ -126,10 +126,10 @@ public boolean isReleased() { } public enum HoldType { - WRITE, READ; + WRITE, READ } public enum Operation { - ACQUIRE, TRY_ACQUIRE, RELEASE; + ACQUIRE, TRY_ACQUIRE, RELEASE } } diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ChainCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ChainCodec.java index d99391c882..77f6b62852 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ChainCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ChainCodec.java @@ -26,7 +26,6 @@ import org.terracotta.runnel.decoding.StructDecoder; import org.terracotta.runnel.encoding.StructArrayEncoder; import org.terracotta.runnel.encoding.StructEncoder; -import org.terracotta.runnel.encoding.StructEncoderFunction; import java.nio.ByteBuffer; import java.util.ArrayList; diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EhcacheCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EhcacheCodec.java index 0bd585dcdc..69c2c7c879 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EhcacheCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EhcacheCodec.java @@ -70,7 +70,7 @@ public byte[] encodeMessage(EhcacheEntityMessage message) { } @Override - public EhcacheEntityMessage decodeMessage(byte[] payload) throws MessageCodecException { + public EhcacheEntityMessage decodeMessage(byte[] payload) { ByteBuffer byteBuffer = wrap(payload); Enm opCodeEnm = OP_CODE_DECODER.decoder(byteBuffer).enm("opCode"); @@ -101,12 +101,12 @@ public EhcacheEntityMessage decodeMessage(ByteBuffer byteBuffer, EhcacheMessageT } @Override - public byte[] encodeResponse(EhcacheEntityResponse response) throws MessageCodecException { + public byte[] encodeResponse(EhcacheEntityResponse response) { return responseCodec.encode(response); } @Override - public EhcacheEntityResponse decodeResponse(byte[] payload) throws MessageCodecException { + public EhcacheEntityResponse decodeResponse(byte[] payload) { return responseCodec.decode(payload); } } diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EntityConfigurationCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EntityConfigurationCodec.java index 150457fbbc..e46df0c2de 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EntityConfigurationCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/EntityConfigurationCodec.java @@ -36,21 +36,24 @@ public class EntityConfigurationCodec { private static final String IDENTIFIER = "identifier"; - private final StructBuilder tierManagerConfigurationBaseStruct = newStructBuilder() - .string(IDENTIFIER, 10); - private final StructBuilder clusteredStoreConfigurationBaseStruct = newStructBuilder() - .string(IDENTIFIER, 10) - .string(SERVER_STORE_NAME_FIELD, 20); - private final ConfigCodec configCodec; private final Struct tierManagerConfigurationStruct; private final Struct clusteredStoreConfigurationStruct; public EntityConfigurationCodec(ConfigCodec configCodec) { this.configCodec = configCodec; + + StructBuilder tierManagerConfigurationBaseStruct = newStructBuilder() + .string(IDENTIFIER, 10); + tierManagerConfigurationStruct = configCodec.injectServerSideConfiguration(tierManagerConfigurationBaseStruct, 10) .getUpdatedBuilder() .build(); + + StructBuilder clusteredStoreConfigurationBaseStruct = newStructBuilder() + .string(IDENTIFIER, 10) + .string(SERVER_STORE_NAME_FIELD, 20); + clusteredStoreConfigurationStruct = configCodec.injectServerStoreConfiguration(clusteredStoreConfigurationBaseStruct, 30) .getUpdatedBuilder() .build(); diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ExceptionCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ExceptionCodec.java index 7499986ed7..ab5259224e 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ExceptionCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ExceptionCodec.java @@ -26,7 +26,6 @@ import org.terracotta.runnel.decoding.StructDecoder; import org.terracotta.runnel.encoding.StructArrayEncoder; import org.terracotta.runnel.encoding.StructEncoder; -import org.terracotta.runnel.encoding.StructEncoderFunction; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; @@ -93,7 +92,7 @@ public static ClusterException decode(StructDecoder> decoder } arrayDecoder.end(); Class clazz = null; - ClusterException exception = null; + ClusterException exception; try { clazz = Class.forName(exceptionClassName); } catch (ClassNotFoundException e) { diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java index f9204ff2f0..31070351a2 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java @@ -35,14 +35,7 @@ public class LifeCycleMessageCodec { private static final String CONFIG_PRESENT_FIELD = "configPresent"; - private final StructBuilder VALIDATE_MESSAGE_STRUCT_BUILDER_PREFIX = newStructBuilder() - .enm(MESSAGE_TYPE_FIELD_NAME, MESSAGE_TYPE_FIELD_INDEX, EHCACHE_MESSAGE_TYPES_ENUM_MAPPING) - .bool(CONFIG_PRESENT_FIELD, 30); private static final int CONFIGURE_MESSAGE_NEXT_INDEX = 40; - - private final StructBuilder VALIDATE_STORE_MESSAGE_STRUCT_BUILDER_PREFIX = newStructBuilder() - .enm(MESSAGE_TYPE_FIELD_NAME, MESSAGE_TYPE_FIELD_INDEX, EHCACHE_MESSAGE_TYPES_ENUM_MAPPING) - .string(SERVER_STORE_NAME_FIELD, 30); private static final int VALIDATE_STORE_NEXT_INDEX = 40; private final Struct PREPARE_FOR_DESTROY_STRUCT = newStructBuilder() @@ -58,11 +51,20 @@ public class LifeCycleMessageCodec { public LifeCycleMessageCodec(ConfigCodec configCodec) { this.messageCodecUtils = new MessageCodecUtils(); this.configCodec = configCodec; + + StructBuilder validateMessageStructBuilderPrefix = newStructBuilder() + .enm(MESSAGE_TYPE_FIELD_NAME, MESSAGE_TYPE_FIELD_INDEX, EHCACHE_MESSAGE_TYPES_ENUM_MAPPING) + .bool(CONFIG_PRESENT_FIELD, 30); + validateMessageStruct = this.configCodec.injectServerSideConfiguration( - VALIDATE_MESSAGE_STRUCT_BUILDER_PREFIX, CONFIGURE_MESSAGE_NEXT_INDEX).getUpdatedBuilder().build(); + validateMessageStructBuilderPrefix, CONFIGURE_MESSAGE_NEXT_INDEX).getUpdatedBuilder().build(); + + StructBuilder validateStoreMessageStructBuilderPrefix = newStructBuilder() + .enm(MESSAGE_TYPE_FIELD_NAME, MESSAGE_TYPE_FIELD_INDEX, EHCACHE_MESSAGE_TYPES_ENUM_MAPPING) + .string(SERVER_STORE_NAME_FIELD, 30); validateStoreMessageStruct = this.configCodec.injectServerStoreConfiguration( - VALIDATE_STORE_MESSAGE_STRUCT_BUILDER_PREFIX, VALIDATE_STORE_NEXT_INDEX).getUpdatedBuilder().build(); + validateStoreMessageStructBuilderPrefix, VALIDATE_STORE_NEXT_INDEX).getUpdatedBuilder().build(); } public byte[] encode(LifecycleMessage message) { diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/MessageCodecUtils.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/MessageCodecUtils.java index 13f0a821e0..0472f0f89c 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/MessageCodecUtils.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/MessageCodecUtils.java @@ -18,8 +18,6 @@ import org.terracotta.runnel.encoding.StructEncoder; -import java.util.UUID; - /** * MessageCodecUtils */ diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ReconnectMessageCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ReconnectMessageCodec.java index 01b2a73f2b..0198afa592 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ReconnectMessageCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/ReconnectMessageCodec.java @@ -24,7 +24,6 @@ import java.util.HashSet; import java.util.Set; -import java.util.UUID; import static java.nio.ByteBuffer.wrap; import static org.terracotta.runnel.StructBuilder.newStructBuilder; @@ -55,12 +54,12 @@ public ClusterTierReconnectMessage decode(byte[] payload) { Set hashes; if (arrayDecoder != null) { - hashes = new HashSet(arrayDecoder.length()); + hashes = new HashSet<>(arrayDecoder.length()); for (int i = 0; i < arrayDecoder.length(); i++) { hashes.add(arrayDecoder.value()); } } else { - hashes = new HashSet(0); + hashes = new HashSet<>(0); } ClusterTierReconnectMessage message = new ClusterTierReconnectMessage(hashes); diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/util/ByteBufferInputStream.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/util/ByteBufferInputStream.java index 0b0c1e60b0..895291069b 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/util/ByteBufferInputStream.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/util/ByteBufferInputStream.java @@ -33,7 +33,7 @@ public ByteBufferInputStream(ByteBuffer buffer) { } @Override - public int read() throws IOException { + public int read() { if (buffer.hasRemaining()) { return 0xff & buffer.get(); } else { diff --git a/clustered/ops-tool/src/main/java/org/ehcache/clustered/operations/OperationsTool.java b/clustered/ops-tool/src/main/java/org/ehcache/clustered/operations/OperationsTool.java index a38da11064..cdffbc3d67 100644 --- a/clustered/ops-tool/src/main/java/org/ehcache/clustered/operations/OperationsTool.java +++ b/clustered/ops-tool/src/main/java/org/ehcache/clustered/operations/OperationsTool.java @@ -33,7 +33,7 @@ public class OperationsTool { } }; - public static void main(String[] args) throws IOException { + public static void main(String[] args) { System.exit(innerMain(args)); } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockActiveEntity.java b/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockActiveEntity.java index 868dd231de..7ab148dbd7 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockActiveEntity.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockActiveEntity.java @@ -29,7 +29,6 @@ import org.terracotta.entity.ClientDescriptor; import org.terracotta.entity.MessageCodecException; import org.terracotta.entity.PassiveSynchronizationChannel; -import org.terracotta.entity.ReconnectRejectedException; import org.terracotta.entity.StateDumpCollector; /** diff --git a/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockServerEntityService.java b/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockServerEntityService.java index 76f111eb65..b73b4930b8 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockServerEntityService.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/lock/server/VoltronReadWriteLockServerEntityService.java @@ -90,7 +90,7 @@ public SyncMessageCodec getSyncMessageCodec() { return LockSyncMessaging.syncCodec(); } - private static final ServiceConfiguration config(final Class klazz) { + private static ServiceConfiguration config(Class klazz) { return () -> klazz; } } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/lock/server/messages/LockSyncMessaging.java b/clustered/server/src/main/java/org/ehcache/clustered/lock/server/messages/LockSyncMessaging.java index 354d7b2e1d..792f2d05b7 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/lock/server/messages/LockSyncMessaging.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/lock/server/messages/LockSyncMessaging.java @@ -31,12 +31,12 @@ public static SyncMessageCodec syncCodec() { private static final SyncMessageCodec SYNC_CODEC = new SyncMessageCodec() { @Override - public byte[] encode(int i, LockMessaging.LockOperation message) throws MessageCodecException { + public byte[] encode(int i, LockMessaging.LockOperation message) { throw new AssertionError(); } @Override - public LockMessaging.LockOperation decode(int i, byte[] bytes) throws MessageCodecException { + public LockMessaging.LockOperation decode(int i, byte[] bytes) { throw new AssertionError(); } }; diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerActiveEntity.java b/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerActiveEntity.java index c4c578d6fe..ba4bd939e3 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerActiveEntity.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerActiveEntity.java @@ -33,7 +33,6 @@ import org.terracotta.entity.ClientDescriptor; import org.terracotta.entity.ConfigurationException; import org.terracotta.entity.PassiveSynchronizationChannel; -import org.terracotta.entity.ReconnectRejectedException; import org.terracotta.entity.StateDumpCollector; import java.util.concurrent.atomic.AtomicBoolean; diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerPassiveEntity.java b/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerPassiveEntity.java index f4cf06969d..bcf0642210 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerPassiveEntity.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerPassiveEntity.java @@ -68,25 +68,20 @@ public void addStateTo(StateDumpCollector dump) { @Override public void invokePassive(InvokeContext context, EhcacheEntityMessage message) { - try { - if (message instanceof EhcacheOperationMessage) { - EhcacheOperationMessage operationMessage = (EhcacheOperationMessage) message; - EhcacheMessageType messageType = operationMessage.getMessageType(); - if (isLifecycleMessage(messageType)) { - invokeLifeCycleOperation((LifecycleMessage) message); - } else { - throw new AssertionError("Unsupported EhcacheOperationMessage: " + operationMessage.getMessageType()); - } + if (message instanceof EhcacheOperationMessage) { + EhcacheOperationMessage operationMessage = (EhcacheOperationMessage) message; + EhcacheMessageType messageType = operationMessage.getMessageType(); + if (isLifecycleMessage(messageType)) { + invokeLifeCycleOperation((LifecycleMessage) message); } else { - throw new AssertionError("Unsupported EhcacheEntityMessage: " + message.getClass()); + throw new AssertionError("Unsupported EhcacheOperationMessage: " + operationMessage.getMessageType()); } - } catch (ClusterException e) { - // Reaching here means a lifecycle or sync operation failed - throw new IllegalStateException("A lifecycle or sync operation failed", e); + } else { + throw new AssertionError("Unsupported EhcacheEntityMessage: " + message.getClass()); } } - private void invokeLifeCycleOperation(LifecycleMessage message) throws ClusterException { + private void invokeLifeCycleOperation(LifecycleMessage message) { switch (message.getMessageType()) { case PREPARE_FOR_DESTROY: ehcacheStateService.prepareForDestroy(); diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerServerEntityService.java b/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerServerEntityService.java index acee846bad..92717bdfa3 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerServerEntityService.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/ClusterTierManagerServerEntityService.java @@ -106,12 +106,12 @@ public MessageCodec getMessageCodec public SyncMessageCodec getSyncMessageCodec() { return new SyncMessageCodec() { @Override - public byte[] encode(int concurrencyKey, EhcacheEntityMessage response) throws MessageCodecException { + public byte[] encode(int concurrencyKey, EhcacheEntityMessage response) { throw new UnsupportedOperationException("This entity does not have sync messages"); } @Override - public EhcacheEntityMessage decode(int concurrencyKey, byte[] payload) throws MessageCodecException { + public EhcacheEntityMessage decode(int concurrencyKey, byte[] payload) { throw new UnsupportedOperationException("This entity does not have sync messages"); } }; diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java b/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java index ae0a02a052..eb99c05079 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java @@ -303,13 +303,13 @@ private ResourcePageSource createPageSource(String poolName, ServerSideConfigura } private void registerStoreStatistics(ServerStoreImpl store, String storeName) { - STAT_STORE_METHOD_REFERENCES.entrySet().stream().forEach((entry)-> - registerStatistic(store, storeName, entry.getKey(), STATISTICS_STORE_TAG, PROPERTY_STORE_KEY, () -> entry.getValue().apply(store) )); + STAT_STORE_METHOD_REFERENCES.forEach((key, value) -> + registerStatistic(store, storeName, key, STATISTICS_STORE_TAG, PROPERTY_STORE_KEY, () -> value.apply(store) )); } private void registerPoolStatistics(String poolName, ResourcePageSource pageSource) { - STAT_POOL_METHOD_REFERENCES.entrySet().stream().forEach((entry)-> - registerStatistic(pageSource, poolName, entry.getKey(), STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, () -> entry.getValue().apply(pageSource)) + STAT_POOL_METHOD_REFERENCES.forEach((key, value)-> + registerStatistic(pageSource, poolName, key, STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, () -> value.apply(pageSource)) ); } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheDataSyncMessage.java b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheDataSyncMessage.java index 9099b341f2..1937f9389f 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheDataSyncMessage.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheDataSyncMessage.java @@ -21,7 +21,6 @@ import com.tc.classloader.CommonComponent; import java.util.Collections; -import java.util.HashMap; import java.util.Map; @CommonComponent diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodec.java b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodec.java index 743089b0b9..46ce38330b 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodec.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodec.java @@ -47,7 +47,7 @@ public EhcacheServerCodec(EhcacheCodec clientCodec, PassiveReplicationMessageCod } @Override - public byte[] encodeMessage(EhcacheEntityMessage message) throws MessageCodecException { + public byte[] encodeMessage(EhcacheEntityMessage message) { if (message instanceof PassiveReplicationMessage) { return replicationCodec.encode((PassiveReplicationMessage) message); } @@ -55,7 +55,7 @@ public byte[] encodeMessage(EhcacheEntityMessage message) throws MessageCodecExc } @Override - public EhcacheEntityMessage decodeMessage(byte[] payload) throws MessageCodecException { + public EhcacheEntityMessage decodeMessage(byte[] payload) { ByteBuffer byteBuffer = wrap(payload); Enm opCodeEnm = EhcacheCodec.OP_CODE_DECODER.decoder(byteBuffer).enm("opCode"); if (!opCodeEnm.isFound()) { diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessage.java b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessage.java index ba23e4b23a..79dd79f908 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessage.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessage.java @@ -20,8 +20,6 @@ import com.tc.classloader.CommonComponent; -import java.util.UUID; - @CommonComponent public abstract class EhcacheSyncMessage extends EhcacheEntityMessage { diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessageCodec.java b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessageCodec.java index 84aa466394..a469a2bab1 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessageCodec.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/internal/messages/EhcacheSyncMessageCodec.java @@ -20,7 +20,6 @@ import org.ehcache.clustered.common.internal.messages.EhcacheEntityMessage; import org.ehcache.clustered.common.internal.messages.EhcacheEntityResponse; import org.ehcache.clustered.common.internal.messages.ResponseCodec; -import org.ehcache.clustered.common.internal.messages.StateRepositoryOpCodec; import org.ehcache.clustered.common.internal.store.Chain; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -105,7 +104,7 @@ public class EhcacheSyncMessageCodec implements SyncMessageCodec keySet() { private void evict() { int evictionIndex = heads.getEvictionIndex(); if (evictionIndex < 0) { - StringBuilder sb = new StringBuilder("Storage Engine and Eviction Failed - Everything Pinned ("); - sb.append(getSize()).append(" mappings) \n").append("Storage Engine : ").append(chainStorage); - throw new OversizeMappingException(sb.toString()); + throw new OversizeMappingException("Storage Engine and Eviction Failed - Everything Pinned (" + getSize() + " mappings) \n" + "Storage Engine : " + chainStorage); } else { heads.evict(evictionIndex, false); } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java b/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java index 3688ae746a..5b2a2a7cde 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java @@ -19,7 +19,6 @@ import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; -import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; @@ -264,11 +263,7 @@ public boolean append(ByteBuffer element) { } else { long oldTail = storage.readLong(chain + CHAIN_HEADER_TAIL_OFFSET); storage.writeLong(newTail + ELEMENT_HEADER_NEXT_OFFSET, chain); - try { - storage.writeLong(oldTail + ELEMENT_HEADER_NEXT_OFFSET, newTail); - } catch (NullPointerException e) { - throw e; - } + storage.writeLong(oldTail + ELEMENT_HEADER_NEXT_OFFSET, newTail); storage.writeLong(chain + CHAIN_HEADER_TAIL_OFFSET, newTail); return true; } @@ -445,11 +440,10 @@ public void close() { } } - private long writeElement(long address, ByteBuffer element) { + private void writeElement(long address, ByteBuffer element) { storage.writeLong(address + ELEMENT_HEADER_SEQUENCE_OFFSET, nextSequenceNumber++); storage.writeInt(address + ELEMENT_HEADER_LENGTH_OFFSET, element.remaining()); storage.writeBuffer(address + ELEMENT_HEADER_SIZE, element.duplicate()); - return address; } private Long createAttachedChain(K key, int hash, PrimordialChain value) { diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/repo/ServerStateRepository.java b/clustered/server/src/main/java/org/ehcache/clustered/server/repo/ServerStateRepository.java index e6bc05876e..9942c16e5d 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/repo/ServerStateRepository.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/repo/ServerStateRepository.java @@ -33,7 +33,7 @@ class ServerStateRepository { private final ConcurrentMap> concurrentMapRepo = new ConcurrentHashMap<>(); - EhcacheEntityResponse invoke(StateRepositoryOpMessage message) throws ClusterException { + EhcacheEntityResponse invoke(StateRepositoryOpMessage message) { String mapId = message.getMapId(); ConcurrentMap map = getStateMap(mapId); diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/repo/StateRepositoryManager.java b/clustered/server/src/main/java/org/ehcache/clustered/server/repo/StateRepositoryManager.java index 2f0255f0c4..cdad28f650 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/repo/StateRepositoryManager.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/repo/StateRepositoryManager.java @@ -34,11 +34,11 @@ public class StateRepositoryManager { private final ConcurrentMap mapRepositoryMap = new ConcurrentHashMap<>(); - public void destroyStateRepository(String cacheId) throws ClusterException { + public void destroyStateRepository(String cacheId) { mapRepositoryMap.remove(cacheId); } - public EhcacheEntityResponse invoke(StateRepositoryOpMessage message) throws ClusterException { + public EhcacheEntityResponse invoke(StateRepositoryOpMessage message) { String cacheId = message.getCacheId(); ServerStateRepository currentRepo = getServerStateRepository(cacheId); return currentRepo.invoke(message); diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateService.java b/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateService.java index 3ae9833793..0a524e8a3b 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateService.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateService.java @@ -19,7 +19,6 @@ import org.ehcache.clustered.common.ServerSideConfiguration; import org.ehcache.clustered.common.internal.ServerStoreConfiguration; import org.ehcache.clustered.common.internal.exceptions.ClusterException; -import org.ehcache.clustered.common.internal.exceptions.InvalidStoreException; import org.ehcache.clustered.server.ServerSideServerStore; import org.ehcache.clustered.server.repo.StateRepositoryManager; import org.terracotta.entity.ConfigurationException; diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateServiceProvider.java b/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateServiceProvider.java index ab1c5ac533..e0ec5d9bfd 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateServiceProvider.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/state/EhcacheStateServiceProvider.java @@ -47,7 +47,7 @@ public class EhcacheStateServiceProvider implements ServiceProvider { private static final Logger LOGGER = LoggerFactory.getLogger(EhcacheStateServiceProvider.class); - private ConcurrentMap serviceMap = new ConcurrentHashMap<>(); + private final ConcurrentMap serviceMap = new ConcurrentHashMap<>(); private OffHeapResources offHeapResourcesProvider; @Override @@ -112,7 +112,7 @@ public Collection> getProvidedServiceTypes() { } @Override - public void prepareForSynchronization() throws ServiceProviderCleanupException { + public void prepareForSynchronization() { serviceMap.clear(); } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/state/InvalidationTracker.java b/clustered/server/src/main/java/org/ehcache/clustered/server/state/InvalidationTracker.java index 30c5e75e4e..d3c95d3ba2 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/state/InvalidationTracker.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/state/InvalidationTracker.java @@ -19,7 +19,6 @@ import com.tc.classloader.CommonComponent; import java.util.Set; -import java.util.concurrent.ConcurrentMap; @CommonComponent public interface InvalidationTracker { diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/state/ResourcePageSource.java b/clustered/server/src/main/java/org/ehcache/clustered/server/state/ResourcePageSource.java index 9827e45474..ceb6e968dd 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/state/ResourcePageSource.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/state/ResourcePageSource.java @@ -63,10 +63,9 @@ public void free(Page page) { @Override public String toString() { - final StringBuilder sb = new StringBuilder("ResourcePageSource{"); - sb.append("pool=").append(pool); - sb.append(", delegatePageSource=").append(delegatePageSource); - sb.append('}'); - return sb.toString(); + String sb = "ResourcePageSource{" + "pool=" + pool + + ", delegatePageSource=" + delegatePageSource + + '}'; + return sb; } } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierActiveEntity.java b/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierActiveEntity.java index 56f4307cb6..0b199e7fe8 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierActiveEntity.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierActiveEntity.java @@ -34,7 +34,6 @@ import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.AppendMessage; import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.ClientInvalidationAck; import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.ClientInvalidationAllAck; -import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.GetAndAppendMessage; import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.GetMessage; import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.KeyBasedServerStoreOpMessage; import org.ehcache.clustered.common.internal.messages.ServerStoreOpMessage.ReplaceAtHeadMessage; @@ -71,7 +70,6 @@ import org.terracotta.entity.InvokeContext; import org.terracotta.entity.MessageCodecException; import org.terracotta.entity.PassiveSynchronizationChannel; -import org.terracotta.entity.ReconnectRejectedException; import org.terracotta.entity.ServiceException; import org.terracotta.entity.ServiceRegistry; import org.terracotta.entity.StateDumpCollector; @@ -83,7 +81,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeoutException; diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierPassiveEntity.java b/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierPassiveEntity.java index 8ee9348c4f..a4205ba3d4 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierPassiveEntity.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/store/ClusterTierPassiveEntity.java @@ -179,11 +179,7 @@ private EhcacheEntityResponse invokePassiveInternal(InvokeContext context, Ehcac LOGGER.error("Unexpected exception raised during operation: " + message, e); } } else if (message instanceof EhcacheSyncMessage) { - try { - invokeSyncOperation(context, (EhcacheSyncMessage) message); - } catch (ClusterException e) { - throw new IllegalStateException("Sync operation failed", e); - } + invokeSyncOperation(context, (EhcacheSyncMessage) message); } else { throw new AssertionError("Unsupported EhcacheEntityMessage: " + message.getClass()); } @@ -192,7 +188,7 @@ private EhcacheEntityResponse invokePassiveInternal(InvokeContext context, Ehcac return success(); } - private void invokeSyncOperation(InvokeContext context, EhcacheSyncMessage message) throws ClusterException { + private void invokeSyncOperation(InvokeContext context, EhcacheSyncMessage message) { switch (message.getMessageType()) { case DATA: EhcacheDataSyncMessage dataSyncMessage = (EhcacheDataSyncMessage) message; diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/store/MessageToTrackerSegmentFunction.java b/clustered/server/src/main/java/org/ehcache/clustered/server/store/MessageToTrackerSegmentFunction.java index 79f73c4157..3cc048688f 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/store/MessageToTrackerSegmentFunction.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/store/MessageToTrackerSegmentFunction.java @@ -26,12 +26,12 @@ */ class MessageToTrackerSegmentFunction implements ToIntFunction { - private ConcurrencyStrategy concurrencyStrategy; + private final ConcurrencyStrategy concurrencyStrategy; MessageToTrackerSegmentFunction(ConcurrencyStrategy concurrencyStrategy) { - this.concurrencyStrategy = concurrencyStrategy; } + @Override public int applyAsInt(EhcacheEntityMessage value) { // Concurrency is 1 based, segments are 0 based diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java index 7e9b6182d3..b7bc1a8198 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java @@ -24,7 +24,6 @@ import org.ehcache.spi.test.SPITest; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java index b3f9c79a0c..978f5d2a08 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java @@ -29,9 +29,6 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; -import java.util.function.BiFunction; -import java.util.function.Function; - import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.hamcrest.MockitoHamcrest.argThat; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java index 07c29dde4d..02da9d3dd1 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java @@ -27,9 +27,6 @@ import org.ehcache.spi.test.SPITest; import org.hamcrest.Matcher; -import java.util.function.BiFunction; -import java.util.function.Function; - import static org.ehcache.internal.store.StoreCreationEventListenerTest.eventType; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -48,10 +45,10 @@ public StoreEvictionEventListenerTest(StoreFactory factory) { } final K k = factory.createKey(1L); - final V v = factory.createValue(1l); + final V v = factory.createValue(1L); final K k2 = factory.createKey(2L); - final V v2 = factory.createValue(2l); - final V v3 = factory.createValue(3l); + final V v2 = factory.createValue(2L); + final V v3 = factory.createValue(3L); protected Store kvStore; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java index 3b3dc624d4..7ad67a3414 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java @@ -51,8 +51,8 @@ public StoreExpiryEventListenerTest(StoreFactory factory) { } final K k = factory.createKey(1L); - final V v = factory.createValue(1l); - final V v2 = factory.createValue(2l); + final V v = factory.createValue(1L); + final V v2 = factory.createValue(2L); protected Store kvStore; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java index 2185254092..8de281a66b 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java @@ -27,8 +27,6 @@ import org.ehcache.spi.test.SPITest; import org.hamcrest.Matcher; -import java.util.function.BiFunction; - import static org.ehcache.internal.store.StoreCreationEventListenerTest.eventType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java index 76db98d3c9..30ca6f4f97 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java @@ -203,7 +203,7 @@ public void wrongKeyTypeThrowsException() if (this.factory.getKeyType() == String.class) { kvStore2.remove((K) (Object) 1.0f, value); } else { - kvStore2.remove((K) (Object) "key", value); + kvStore2.remove((K) "key", value); } throw new AssertionError("Expected ClassCastException because the key is of the wrong type"); } catch (ClassCastException e) { @@ -225,7 +225,7 @@ public void wrongValueTypeThrowsException() if (this.factory.getValueType() == String.class) { kvStore2.remove(key, (V) (Object) 1.0f); } else { - kvStore2.remove(key, (V) (Object) "value"); + kvStore2.remove(key, (V) "value"); } throw new AssertionError("Expected ClassCastException because the value is of the wrong type"); } catch (ClassCastException e) { diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java index 61657cfdd0..530cf326f1 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java @@ -27,8 +27,6 @@ import org.ehcache.spi.test.SPITest; import org.hamcrest.Matcher; -import java.util.function.BiFunction; - import static org.ehcache.internal.store.StoreCreationEventListenerTest.eventType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java index 16c7356535..eb99068b88 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java @@ -20,7 +20,6 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.spi.test.After; -import org.ehcache.spi.test.Before; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java index 6a9cde5b7e..05f61adb36 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java @@ -26,7 +26,6 @@ import java.util.ArrayList; import java.util.List; -import java.util.function.Function; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; @@ -48,10 +47,6 @@ public CachingTierClear(final CachingTierFactory factory) { super(factory); } - @Before - public void setUp() { - } - @After public void tearDown() { if (tier != null) { diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java index 2ae60634f6..6464b91de9 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java @@ -49,10 +49,6 @@ public CachingTierGetOrComputeIfAbsent(final CachingTierFactory factory) { super(factory); } - @Before - public void setUp() { - } - @After public void tearDown() { if (tier != null) { diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java index 518178a994..b6ca9df440 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java @@ -27,7 +27,6 @@ import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Function; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java index a9b1c4db93..7da1abd7e5 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java @@ -24,8 +24,6 @@ import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; -import java.util.function.Function; - import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -46,10 +44,6 @@ public CachingTierRemove(final CachingTierFactory factory) { super(factory); } - @Before - public void setUp() { - } - @After public void tearDown() { if (tier != null) { diff --git a/core/src/main/java/org/ehcache/core/EhcacheManager.java b/core/src/main/java/org/ehcache/core/EhcacheManager.java index 63b4522a88..a4cb7f9fcd 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheManager.java +++ b/core/src/main/java/org/ehcache/core/EhcacheManager.java @@ -97,7 +97,7 @@ public class EhcacheManager implements PersistentCacheManager, InternalCacheMana protected final ServiceLocator serviceLocator; public EhcacheManager(Configuration config) { - this(config, Collections.emptyList(), true); + this(config, Collections.emptyList(), true); } public EhcacheManager(Configuration config, Collection services) { @@ -247,7 +247,7 @@ private Cache createCache(final String alias, CacheConfiguration keyType = config.getKeyType(); Class valueType = config.getValueType(); - final CacheHolder value = new CacheHolder(keyType, valueType, null); + CacheHolder value = new CacheHolder(keyType, valueType); if (caches.putIfAbsent(alias, value) != null) { throw new IllegalArgumentException("Cache '" + alias +"' already exists"); } @@ -374,7 +374,7 @@ public void close() { lsnrConfig.fireOn()); lifeCycledList.add(new LifeCycled() { @Override - public void init() throws Exception { + public void init() { // no-op for now } @@ -495,7 +495,7 @@ public void close() throws Exception { lifeCycledList.add(new LifeCycled() { @Override - public void init() throws Exception { + public void init() { storeProvider.initStore(store); } @@ -756,10 +756,9 @@ private static final class CacheHolder { private volatile InternalCache cache; private volatile boolean isValueSet = false; - CacheHolder(Class keyType, Class valueType, InternalCache cache) { + CacheHolder(Class keyType, Class valueType) { this.keyType = keyType; this.valueType = valueType; - this.cache = cache; } InternalCache retrieve(Class refKeyType, Class refValueType) { diff --git a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java index d6180a7af5..015f6ac50f 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java +++ b/core/src/main/java/org/ehcache/core/EhcacheRuntimeConfiguration.java @@ -184,14 +184,12 @@ public String readableString() { serviceConfigurationsToStringBuilder.append(" None"); } - String expiryPolicy = ""; + String expiryPolicy; - if (expiryPolicy != null) { - if (ExpiryPolicy.NO_EXPIRY == expiry) { - expiryPolicy = "NoExpiryPolicy"; - } else { - expiryPolicy = expiry.toString(); - } + if (ExpiryPolicy.NO_EXPIRY == expiry) { + expiryPolicy = "NoExpiryPolicy"; + } else { + expiryPolicy = expiry.toString(); } return diff --git a/core/src/main/java/org/ehcache/core/StatusTransitioner.java b/core/src/main/java/org/ehcache/core/StatusTransitioner.java index 6994d4ab9e..1727920038 100644 --- a/core/src/main/java/org/ehcache/core/StatusTransitioner.java +++ b/core/src/main/java/org/ehcache/core/StatusTransitioner.java @@ -220,7 +220,7 @@ public void succeeded() { public StateTransitionException failed(Throwable t) { if (st.done()) { if (t != null) { - throw (AssertionError) new AssertionError("Throwable cannot be thrown if Transition is done.").initCause(t); + throw new AssertionError("Throwable cannot be thrown if Transition is done.", t); } return null; } diff --git a/core/src/main/java/org/ehcache/core/config/ResourcePoolsImpl.java b/core/src/main/java/org/ehcache/core/config/ResourcePoolsImpl.java index 10e0b494e7..dca19f48ee 100644 --- a/core/src/main/java/org/ehcache/core/config/ResourcePoolsImpl.java +++ b/core/src/main/java/org/ehcache/core/config/ResourcePoolsImpl.java @@ -25,8 +25,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; -import java.util.EnumMap; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -69,25 +67,27 @@ public Set> getResourceTypeSet() { */ @Override public ResourcePools validateAndMerge(ResourcePools toBeUpdated) { + Set> resourceTypeSet = toBeUpdated.getResourceTypeSet(); + // Ensure update pool types already exist in existing pools - if(!getResourceTypeSet().containsAll(toBeUpdated.getResourceTypeSet())) { + if(!getResourceTypeSet().containsAll(resourceTypeSet)) { throw new IllegalArgumentException("Pools to be updated cannot contain previously undefined resources pools"); } // Can not update OFFHEAP - if(toBeUpdated.getResourceTypeSet().contains(ResourceType.Core.OFFHEAP)) { + if(resourceTypeSet.contains(ResourceType.Core.OFFHEAP)) { throw new UnsupportedOperationException("Updating OFFHEAP resource is not supported"); } // Can not update DISK - if(toBeUpdated.getResourceTypeSet().contains(ResourceType.Core.DISK)) { + if(resourceTypeSet.contains(ResourceType.Core.DISK)) { throw new UnsupportedOperationException("Updating DISK resource is not supported"); } - for(ResourceType currentResourceType : toBeUpdated.getResourceTypeSet()) { + for(ResourceType currentResourceType : resourceTypeSet) { getPoolForResource(currentResourceType).validateUpdate(toBeUpdated.getPoolForResource(currentResourceType)); } - Map, ResourcePool> poolsMap = new HashMap<>(); + Map, ResourcePool> poolsMap = new HashMap<>(pools.size() + resourceTypeSet.size()); poolsMap.putAll(pools); - for(ResourceType currentResourceType : toBeUpdated.getResourceTypeSet()) { + for(ResourceType currentResourceType : resourceTypeSet) { ResourcePool poolForResource = toBeUpdated.getPoolForResource(currentResourceType); poolsMap.put(currentResourceType, poolForResource); } @@ -107,9 +107,9 @@ public static void validateResourcePools(Collection pool ordered.add((SizedResourcePool)pool); } } - Collections.sort(ordered, (o1, o2) -> { + ordered.sort((o1, o2) -> { int retVal = o2.getType().getTierHeight() - o1.getType().getTierHeight(); - if(retVal == 0) { + if (retVal == 0) { return o1.toString().compareTo(o2.toString()); } else { return retVal; diff --git a/core/src/main/java/org/ehcache/core/internal/service/ServiceLocator.java b/core/src/main/java/org/ehcache/core/internal/service/ServiceLocator.java index 7ad35054d4..b28c29a058 100644 --- a/core/src/main/java/org/ehcache/core/internal/service/ServiceLocator.java +++ b/core/src/main/java/org/ehcache/core/internal/service/ServiceLocator.java @@ -30,7 +30,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.Deque; import java.util.HashMap; import java.util.HashSet; @@ -91,7 +90,7 @@ public boolean knowsServiceFor(ServiceConfiguration serviceConfig) { return services.contains(serviceConfig.getServiceType()); } - public void startAllServices() throws Exception { + public void startAllServices() { Deque started = new LinkedList<>(); final Lock lock = runningLock.writeLock(); lock.lock(); @@ -437,9 +436,9 @@ private static Set> identifyImmediateDependenciesOf(fin } private static Set> identifyTransitiveDependenciesOf(final Class clazz) { - Set> transitive = new HashSet<>(); Set> dependencies = identifyImmediateDependenciesOf(clazz); + Set> transitive = new HashSet<>(dependencies.size() * 3); // 3 is my feeling of how many there should be per class at most transitive.addAll(dependencies); for (Class klazz : dependencies) { diff --git a/core/src/main/java/org/ehcache/core/internal/store/StoreSupport.java b/core/src/main/java/org/ehcache/core/internal/store/StoreSupport.java index 8c42f44273..386c572581 100644 --- a/core/src/main/java/org/ehcache/core/internal/store/StoreSupport.java +++ b/core/src/main/java/org/ehcache/core/internal/store/StoreSupport.java @@ -89,7 +89,7 @@ public static Store.Provider selectStoreProvider( return rankingProviders.get(0); } - private static StringBuilder formatStoreProviders(final Collection storeProviders, final StringBuilder sb) { + private static void formatStoreProviders(final Collection storeProviders, final StringBuilder sb) { sb.append('{'); boolean prependSeparator = false; for (final Store.Provider provider : storeProviders) { @@ -101,6 +101,5 @@ private static StringBuilder formatStoreProviders(final Collection implements Store.ValueHolder { private static final AtomicLongFieldUpdater HITS_UPDATER = AtomicLongFieldUpdater.newUpdater(AbstractValueHolder.class, "hits"); private final long id; private final long creationTime; + @SuppressWarnings("CanBeFinal") private volatile long lastAccessTime; + @SuppressWarnings("CanBeFinal") private volatile long expirationTime; private volatile long hits; @@ -77,7 +79,7 @@ private void updateExpirationTime(long update) { if (EXPIRATIONTIME_UPDATER.compareAndSet(this, current, update)) { break; } - }; + } } public void accessed(long now, Duration expiration) { @@ -127,7 +129,7 @@ public void setLastAccessTime(long lastAccessTime, TimeUnit unit) { if (ACCESSTIME_UPDATER.compareAndSet(this, current, update)) { break; } - }; + } } @Override diff --git a/core/src/main/java/org/ehcache/core/spi/store/Store.java b/core/src/main/java/org/ehcache/core/spi/store/Store.java index 7b6b123ab7..8765c9d351 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/Store.java +++ b/core/src/main/java/org/ehcache/core/spi/store/Store.java @@ -452,7 +452,7 @@ public interface Store extends ConfigurationChangeSupport { * @return a {@link Map} of key/value pairs for each key in keys to the previously missing value. * @throws ClassCastException if the specified key(s) are not of the correct type ({@code K}). Also thrown if the given function produces * entries with either incorrect key or value types - * @throws StoreAccessException + * @throws StoreAccessException when a failure occurs when accessing the store */ Map> bulkComputeIfAbsent(Set keys, Function, Iterable>> mappingFunction) throws StoreAccessException; diff --git a/core/src/main/java/org/ehcache/core/statistics/BulkOps.java b/core/src/main/java/org/ehcache/core/statistics/BulkOps.java index f2802f2657..bbbc1ce4ed 100644 --- a/core/src/main/java/org/ehcache/core/statistics/BulkOps.java +++ b/core/src/main/java/org/ehcache/core/statistics/BulkOps.java @@ -44,5 +44,5 @@ public enum BulkOps { /** * The "put all" bulk operation performing an update */ - UPDATE_ALL; + UPDATE_ALL } diff --git a/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java b/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java index 9e2bc30c30..ad85ef4c48 100755 --- a/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java +++ b/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java @@ -45,7 +45,7 @@ enum GetOutcome implements CacheOperationOutcomes { MISS, /** failure */ FAILURE - }; + } /** * Outcomes for cache getAll operation @@ -71,7 +71,7 @@ enum PutOutcome implements CacheOperationOutcomes { NOOP, /** failure */ FAILURE - }; + } /** * Outcomes for cache putAll operation @@ -97,7 +97,7 @@ enum RemoveOutcome implements CacheOperationOutcomes { NOOP, /** failure */ FAILURE - }; + } /** * Outcomes for cache removeAll operation @@ -133,7 +133,7 @@ enum ConditionalRemoveOutcome implements CacheOperationOutcomes { * Operation failure */ FAILURE - }; + } /** * The cache loading outcomes. @@ -143,7 +143,7 @@ enum CacheLoadingOutcome implements CacheOperationOutcomes { SUCCESS, /** failure */ FAILURE - }; + } /** * The putIfAbsent outcomes. @@ -161,7 +161,7 @@ enum PutIfAbsentOutcome implements CacheOperationOutcomes { * operation failure */ FAILURE - }; + } /** * The replace outcomes. @@ -183,5 +183,5 @@ enum ReplaceOutcome implements CacheOperationOutcomes { * operation failure */ FAILURE - }; + } } diff --git a/core/src/main/java/org/ehcache/core/statistics/StoreOperationOutcomes.java b/core/src/main/java/org/ehcache/core/statistics/StoreOperationOutcomes.java index 3dfbf6df7d..82f3b0d6b2 100755 --- a/core/src/main/java/org/ehcache/core/statistics/StoreOperationOutcomes.java +++ b/core/src/main/java/org/ehcache/core/statistics/StoreOperationOutcomes.java @@ -174,7 +174,7 @@ enum EvictionOutcome implements StoreOperationOutcomes { SUCCESS, /** failure */ FAILURE - }; + } /** * Outcomes for expiration diff --git a/demos/00-NoCache/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java b/demos/00-NoCache/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java index 222696ed4c..17937b226a 100755 --- a/demos/00-NoCache/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java +++ b/demos/00-NoCache/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java @@ -63,7 +63,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String peepText = req.getParameter("peep"); try { diff --git a/demos/01-CacheAside/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java b/demos/01-CacheAside/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java index 222696ed4c..17937b226a 100755 --- a/demos/01-CacheAside/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java +++ b/demos/01-CacheAside/src/main/java/org/ehcache/demos/peeper/PeeperServlet.java @@ -63,7 +63,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se @Override - protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { + protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException { String peepText = req.getParameter("peep"); try { diff --git a/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java b/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java index fe761351a5..8c6c97586b 100644 --- a/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/CacheConfigurationBuilder.java @@ -64,8 +64,8 @@ public class CacheConfigurationBuilder implements Builder evictionAdvisor; private ResourcePools resourcePools; - private Class keyType; - private Class valueType; + private final Class keyType; + private final Class valueType; /** * Creates a new instance ready to produce a {@link CacheConfiguration} with key type {@code } and with value type diff --git a/impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java b/impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java index 861ba37519..ef83df8006 100644 --- a/impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/PooledExecutionServiceConfigurationBuilder.java @@ -99,9 +99,9 @@ public PooledExecutionServiceConfiguration build() { private static class Pool { - private String alias; - private int minSize; - private int maxSize; + private final String alias; + private final int minSize; + private final int maxSize; Pool(String alias, int minSize, int maxSize) { this.alias = alias; diff --git a/impl/src/main/java/org/ehcache/config/builders/ResourcePoolsBuilder.java b/impl/src/main/java/org/ehcache/config/builders/ResourcePoolsBuilder.java index 0a2a32a347..89e3a06807 100644 --- a/impl/src/main/java/org/ehcache/config/builders/ResourcePoolsBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/ResourcePoolsBuilder.java @@ -46,7 +46,7 @@ public class ResourcePoolsBuilder implements Builder { private final Map, ResourcePool> resourcePools; private ResourcePoolsBuilder() { - this(Collections., ResourcePool>emptyMap()); + this(Collections.emptyMap()); } private ResourcePoolsBuilder(Map, ResourcePool> resourcePools) { diff --git a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java index 5377e9fcfb..4e407e0e6b 100644 --- a/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/UserManagedCacheBuilder.java @@ -278,12 +278,12 @@ public void close() throws Exception { lifeCycledList.add(new LifeCycled() { @Override - public void init() throws Exception { + public void init() { storeProvider.initStore(store); } @Override - public void close() throws Exception { + public void close() { storeProvider.releaseStore(store); } }); @@ -356,7 +356,7 @@ private void registerListeners(Cache cache, ServiceProvider servi lifeCycledList.add(new LifeCycled() { @Override - public void init() throws Exception { + public void init() { } diff --git a/impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java b/impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java index 5579b8bd6c..152f6bb066 100644 --- a/impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java +++ b/impl/src/main/java/org/ehcache/impl/events/CacheEventDispatcherImpl.java @@ -17,7 +17,6 @@ package org.ehcache.impl.events; import org.ehcache.Cache; -import org.ehcache.core.CacheConfigurationChangeEvent; import org.ehcache.core.CacheConfigurationChangeListener; import org.ehcache.core.CacheConfigurationProperty; import org.ehcache.core.events.CacheEventDispatcher; diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProvider.java b/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProvider.java index a53dba716e..012f53983d 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProvider.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProvider.java @@ -104,7 +104,7 @@ private T newInstance(K alias, ClassInstanceConfiguration config) { } } - T instance = null; + T instance; if(config.getInstance() != null) { instance = config.getInstance(); diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProviderConfiguration.java b/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProviderConfiguration.java index bc7331dcf2..5a2330618c 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProviderConfiguration.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/ClassInstanceProviderConfiguration.java @@ -29,7 +29,7 @@ */ public class ClassInstanceProviderConfiguration { - private Map> defaults = new LinkedHashMap<>(); + private final Map> defaults = new LinkedHashMap<>(); public Map> getDefaults() { return defaults; diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java index c6cae1506f..1b863ae7f5 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java @@ -113,7 +113,7 @@ public ClassUtils() { * @return {@code true} if assignment possible */ public static boolean isAssignable(Class[] classArray, Class[] toClassArray, final boolean autoboxing) { - if (ArrayUtils.isSameLength(classArray, toClassArray) == false) { + if (!ArrayUtils.isSameLength(classArray, toClassArray)) { return false; } if (classArray == null) { @@ -123,7 +123,7 @@ public static boolean isAssignable(Class[] classArray, Class[] toClassArra toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY; } for (int i = 0; i < classArray.length; i++) { - if (isAssignable(classArray[i], toClassArray[i], autoboxing) == false) { + if (!isAssignable(classArray[i], toClassArray[i], autoboxing)) { return false; } } @@ -219,7 +219,7 @@ public static boolean isAssignable(Class cls, final Class toClass, final b return true; } if (cls.isPrimitive()) { - if (toClass.isPrimitive() == false) { + if (!toClass.isPrimitive()) { return false; } if (Integer.TYPE.equals(cls)) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/Validate.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/Validate.java index f0a1b9a385..a5550fb161 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/Validate.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/Validate.java @@ -64,7 +64,6 @@ public Validate() { * @param values the optional values for the formatted exception message * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} - * @see #notNull(Object) */ public static T notNull(final T object, final String message, final Object... values) { if (object == null) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java index 1dc2de83bf..10a5cf336e 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java @@ -30,8 +30,8 @@ import java.lang.reflect.Modifier; /** - *

Utility reflection methods focused on constructors, modeled after - * {@link MethodUtils}. + *

Utility reflection methods focused on constructors, modeled after + * {@code MethodUtils}. * *

Known Limitations

Accessing Public Constructors In A Default * Access Superclass

There is an issue when invoking {@code public} constructors diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java index d6592cbc46..f3d422f7b7 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java @@ -29,7 +29,7 @@ /** * Contains common code for working with {@link java.lang.reflect.Method Methods}/{@link java.lang.reflect.Constructor Constructors}, - * extracted and refactored from {@link MethodUtils} when it was imported from Commons BeanUtils. + * extracted and refactored from {@code MethodUtils} when it was imported from Commons BeanUtils. * * @since 2.5 */ @@ -104,7 +104,7 @@ static boolean isAccessible(final Member m) { static int compareParameterTypes(final Class[] left, final Class[] right, final Class[] actual) { final float leftCost = getTotalTransformationCost(actual, left); final float rightCost = getTotalTransformationCost(actual, right); - return leftCost < rightCost ? -1 : rightCost < leftCost ? 1 : 0; + return Float.compare(leftCost, rightCost); } /** diff --git a/impl/src/main/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java b/impl/src/main/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java index fc7410543d..5f921e5c56 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java +++ b/impl/src/main/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java @@ -64,7 +64,6 @@ import java.util.function.ToLongFunction; import org.ehcache.config.EvictionAdvisor; -import org.ehcache.impl.internal.store.heap.holders.OnHeapValueHolder; import sun.misc.Unsafe; @@ -2557,10 +2556,10 @@ final long sumCount() { CounterCell[] as = counterCells; CounterCell a; long sum = baseCount; if (as != null) { - for (int i = 0; i < as.length; ++i) { - if ((a = as[i]) != null) - sum += a.value; - } + for (CounterCell a1 : as) { + if ((a = a1) != null) + sum += a.value; + } } return sum; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/executor/OnDemandExecutionService.java b/impl/src/main/java/org/ehcache/impl/internal/executor/OnDemandExecutionService.java index 2ce6f6db9f..256793b903 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/executor/OnDemandExecutionService.java +++ b/impl/src/main/java/org/ehcache/impl/internal/executor/OnDemandExecutionService.java @@ -20,7 +20,7 @@ import java.util.concurrent.Executors; import static java.util.concurrent.Executors.unconfigurableExecutorService; import static java.util.concurrent.Executors.unconfigurableScheduledExecutorService; -import java.util.concurrent.RejectedExecutionHandler; + import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; diff --git a/impl/src/main/java/org/ehcache/impl/internal/executor/OutOfBandScheduledExecutor.java b/impl/src/main/java/org/ehcache/impl/internal/executor/OutOfBandScheduledExecutor.java index 37436b1fec..79f9f4e7cb 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/executor/OutOfBandScheduledExecutor.java +++ b/impl/src/main/java/org/ehcache/impl/internal/executor/OutOfBandScheduledExecutor.java @@ -20,13 +20,10 @@ import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; import java.util.concurrent.Future; -import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RunnableScheduledFuture; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; -import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; diff --git a/impl/src/main/java/org/ehcache/impl/internal/executor/PooledExecutionService.java b/impl/src/main/java/org/ehcache/impl/internal/executor/PooledExecutionService.java index a24b5fa551..a620ca641d 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/executor/PooledExecutionService.java +++ b/impl/src/main/java/org/ehcache/impl/internal/executor/PooledExecutionService.java @@ -150,7 +150,7 @@ public boolean isStopping() { /** * {@link #stop} has been called and has managed to finish processing all tasks. * - * @return + * @return if this executor has been stopped */ public boolean isStopped() { return scheduledExecutor.isTerminated(); diff --git a/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java b/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java index c56aac4f0a..434f45900f 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java +++ b/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java @@ -68,7 +68,7 @@ public void start() { @Override public V load(K key) throws Exception { - V v = null; + V v; readLock.lock(); try { v = getStripe(key).load(key); diff --git a/impl/src/main/java/org/ehcache/impl/internal/persistence/DefaultDiskResourceServiceFactory.java b/impl/src/main/java/org/ehcache/impl/internal/persistence/DefaultDiskResourceServiceFactory.java index 46a6c24d4f..3680ed45cd 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/persistence/DefaultDiskResourceServiceFactory.java +++ b/impl/src/main/java/org/ehcache/impl/internal/persistence/DefaultDiskResourceServiceFactory.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.persistence; -import org.ehcache.core.spi.service.DiskResourceService; import org.ehcache.core.spi.service.ServiceFactory; import org.ehcache.impl.persistence.DefaultDiskResourceService; import org.ehcache.spi.service.ServiceCreationConfiguration; diff --git a/impl/src/main/java/org/ehcache/impl/internal/sizeof/DefaultSizeOfEngine.java b/impl/src/main/java/org/ehcache/impl/internal/sizeof/DefaultSizeOfEngine.java index 71760e5430..925bae9f2e 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/sizeof/DefaultSizeOfEngine.java +++ b/impl/src/main/java/org/ehcache/impl/internal/sizeof/DefaultSizeOfEngine.java @@ -37,12 +37,11 @@ public class DefaultSizeOfEngine implements SizeOfEngine { private final SizeOf sizeOf; private final long chmTreeBinOffset; private final long onHeapKeyOffset; - private final SizeOfFilterSource filterSource = new SizeOfFilterSource(true); public DefaultSizeOfEngine(long maxObjectGraphSize, long maxObjectSize) { this.maxObjectGraphSize = maxObjectGraphSize; this.maxObjectSize = maxObjectSize; - this.sizeOf = SizeOf.newInstance(filterSource.getFilters()); + this.sizeOf = SizeOf.newInstance(new SizeOfFilterSource(true).getFilters()); this.onHeapKeyOffset = sizeOf.deepSizeOf(new CopiedOnHeapKey<>(new Object(), new IdentityCopier<>())); this.chmTreeBinOffset = sizeOf.deepSizeOf(ConcurrentHashMap.FAKE_TREE_BIN); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/spi/copy/DefaultCopyProvider.java b/impl/src/main/java/org/ehcache/impl/internal/spi/copy/DefaultCopyProvider.java index 0da757abaf..ed98ec8b0e 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/spi/copy/DefaultCopyProvider.java +++ b/impl/src/main/java/org/ehcache/impl/internal/spi/copy/DefaultCopyProvider.java @@ -92,7 +92,7 @@ private Copier createCopier(Class clazz, DefaultCopierConfiguration Copier copier = (Copier) newInstance(clazz, config); if (copier == null) { @SuppressWarnings("unchecked") - Copier defaultInstance = (Copier) newInstance(clazz, new DefaultCopierConfiguration((Class) IdentityCopier.class, type)); + Copier defaultInstance = (Copier) newInstance(clazz, new DefaultCopierConfiguration(IdentityCopier.class, type)); copier = defaultInstance; } return copier; diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java index f6927709b1..d78bb723fb 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java @@ -55,7 +55,7 @@ static Matcher> hasProperty(final String key, final String v @Override protected boolean matchesSafely(Map properties) { Object val = properties.get(key); - return val == null ? false : value.equals(val); + return val != null && value.equals(val); } }); } @@ -76,7 +76,7 @@ static T findStatisticOnDescendants(Object context, String discriminator, St @SuppressWarnings("unchecked") Set statResult = queryBuilder() .descendants() - .filter(context(attributes(Matchers.>allOf( + .filter(context(attributes(Matchers.allOf( hasAttribute("name", statName), hasProperty("discriminator", discriminator), hasTag(tag))))) @@ -111,7 +111,7 @@ static T findStatisticOnDescendants(Object context, String tag, String statN @SuppressWarnings("unchecked") Set statResult = queryBuilder() .descendants() - .filter(context(attributes(Matchers.>allOf( + .filter(context(attributes(Matchers.allOf( hasAttribute("name", statName), hasTag(tag))))) .build().execute(Collections.singleton(ContextManager.nodeFor(context))); @@ -144,7 +144,7 @@ static > OperationStatistic findOperationStatisticOnChildre @SuppressWarnings("unchecked") Query query = queryBuilder() .children() - .filter(context(attributes(Matchers.>allOf(hasAttribute("name", statName), hasAttribute("type", type))))) + .filter(context(attributes(Matchers.allOf(hasAttribute("name", statName), hasAttribute("type", type))))) .build(); Set result = query.execute(Collections.singleton(ContextManager.nodeFor(context))); @@ -177,7 +177,7 @@ static String[] findTiers(Cache cache) { @SuppressWarnings("unchecked") Query statQuery = queryBuilder() .descendants() - .filter(context(attributes(Matchers.>allOf(hasAttribute("name", "eviction"), hasAttribute("type", StoreOperationOutcomes.EvictionOutcome.class))))) + .filter(context(attributes(Matchers.allOf(hasAttribute("name", "eviction"), hasAttribute("type", StoreOperationOutcomes.EvictionOutcome.class))))) .build(); Set statResult = statQuery.execute(Collections.singleton(ContextManager.nodeFor(cache))); diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java index e81c683276..13be97cc87 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java @@ -51,7 +51,7 @@ public ValueHolder getAndFault(K key) throws StoreAccessException { } @Override - public ValueHolder computeIfAbsentAndFault(K key, Function mappingFunction) throws StoreAccessException { + public ValueHolder computeIfAbsentAndFault(K key, Function mappingFunction) { return null; } @@ -66,12 +66,12 @@ public void setInvalidationValve(InvalidationValve valve) { } @Override - public ValueHolder get(K key) throws StoreAccessException { + public ValueHolder get(K key) { return null; } @Override - public boolean containsKey(K key) throws StoreAccessException { + public boolean containsKey(K key) { return false; } @@ -106,7 +106,7 @@ public ReplaceStatus replace(K key, V oldValue, V newValue) throws StoreAccessEx } @Override - public void clear() throws StoreAccessException { + public void clear() { } @@ -149,24 +149,24 @@ public boolean hasNext() { } @Override - public Cache.Entry> next() throws StoreAccessException { + public Cache.Entry> next() { return null; } }; } @Override - public ValueHolder compute(K key, BiFunction mappingFunction) throws StoreAccessException { + public ValueHolder compute(K key, BiFunction mappingFunction) { return EmptyValueHolder.empty(); } @Override - public ValueHolder compute(K key, BiFunction mappingFunction, Supplier replaceEqual) throws StoreAccessException { + public ValueHolder compute(K key, BiFunction mappingFunction, Supplier replaceEqual) { return null; } @Override - public ValueHolder computeIfAbsent(K key, Function mappingFunction) throws StoreAccessException { + public ValueHolder computeIfAbsent(K key, Function mappingFunction) { return null; } @@ -176,19 +176,19 @@ public Map> bulkCompute(Set keys, Function> bulkCompute(Set keys, Function>, Iterable>> remappingFunction, Supplier replaceEqual) throws StoreAccessException { + public Map> bulkCompute(Set keys, Function>, Iterable>> remappingFunction, Supplier replaceEqual) { Map> map = new HashMap<>(keys.size()); for(K key : keys) { - map.put(key, EmptyValueHolder.empty()); + map.put(key, EmptyValueHolder.empty()); } return map; } @Override - public Map> bulkComputeIfAbsent(Set keys, Function, Iterable>> mappingFunction) throws StoreAccessException { + public Map> bulkComputeIfAbsent(Set keys, Function, Iterable>> mappingFunction) { Map> map = new HashMap<>(keys.size()); for(K key : keys) { - map.put(key, EmptyValueHolder.empty()); + map.put(key, EmptyValueHolder.empty()); } return map; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStore.java index 1340fb1d04..65350f1a10 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStore.java @@ -70,8 +70,6 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; @@ -422,7 +420,7 @@ public void initStore(Store resource) { Serializer keySerializer = diskStore.keySerializer; if (keySerializer instanceof StatefulSerializer) { - StateRepository stateRepository = null; + StateRepository stateRepository; try { stateRepository = diskPersistenceService.getStateRepositoryWithin(identifier, "key-serializer"); } catch (CachePersistenceException e) { @@ -432,7 +430,7 @@ public void initStore(Store resource) { } Serializer valueSerializer = diskStore.valueSerializer; if (valueSerializer instanceof StatefulSerializer) { - StateRepository stateRepository = null; + StateRepository stateRepository; try { stateRepository = diskPersistenceService.getStateRepositoryWithin(identifier, "value-serializer"); } catch (CachePersistenceException e) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/KeyCopyBackend.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/KeyCopyBackend.java index 4a37035303..de7860d427 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/KeyCopyBackend.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/KeyCopyBackend.java @@ -29,7 +29,6 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; -import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Random; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index 1f0daef25c..146ec84ad9 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -99,7 +99,7 @@ public abstract class AbstractOffHeapStore implements AuthoritativeTier mapEvictionListener; + protected final BackingMapEvictionListener mapEvictionListener; @SuppressWarnings("unchecked") private volatile CachingTier.InvalidationListener invalidationListener = (CachingTier.InvalidationListener) NULL_INVALIDATION_LISTENER; @@ -518,7 +518,7 @@ public boolean hasNext() { } @Override - public Cache.Entry> next() throws StoreAccessException { + public Cache.Entry> next() { Map.Entry> next = mapIterator.next(); final K key = next.getKey(); final OffHeapValueHolder value = next.getValue(); @@ -765,7 +765,7 @@ public Map> bulkComputeIfAbsent(Set keys, final F public ValueHolder getAndFault(K key) throws StoreAccessException { getAndFaultObserver.begin(); checkKey(key); - ValueHolder mappedValue = null; + ValueHolder mappedValue; final StoreEventSink eventSink = eventDispatcher.eventSink(); try { mappedValue = backingMap().computeIfPresentAndPin(key, (mappedKey, mappedValue1) -> { @@ -969,7 +969,7 @@ public ValueHolder installMapping(final K key, final Function computeWithRetry(K key, BiFunction, OffHeapValueHolder> computeFunction, boolean fault) throws StoreAccessException { - OffHeapValueHolder computeResult = null; + OffHeapValueHolder computeResult; try { computeResult = backingMap().compute(key, computeFunction, fault); } catch (OversizeMappingException ex) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java index 48b0b33f4b..81d0b5133c 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java @@ -18,7 +18,6 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.impl.internal.store.BinaryValueHolder; -import org.terracotta.offheapstore.util.FindbugsSuppressWarnings; import java.io.IOException; import java.nio.ByteBuffer; @@ -75,7 +74,7 @@ public V value() { return value; } - private void writeObject(java.io.ObjectOutputStream out) throws IOException { + private void writeObject(java.io.ObjectOutputStream out) { throw new UnsupportedOperationException("This subclass of AbstractValueHolder is NOT serializable"); } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/HeuristicConfiguration.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/HeuristicConfiguration.java index 9952983993..e74e6e0466 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/HeuristicConfiguration.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/HeuristicConfiguration.java @@ -106,14 +106,13 @@ private long getInitialSegmentCapacity() { @Override public String toString() { - StringBuilder sb = new StringBuilder("Heuristic Configuration: \n"); - sb.append("Maximum Size (specified) : ").append(DebuggingUtils.toBase2SuffixedString(getMaximumSize())).append("B\n"); - sb.append("Minimum Chunk Size : ").append(DebuggingUtils.toBase2SuffixedString(getMinimumChunkSize())).append("B\n"); - sb.append("Maximum Chunk Size : ").append(DebuggingUtils.toBase2SuffixedString(getMaximumChunkSize())).append("B\n"); - sb.append("Concurrency : ").append(getConcurrency()).append("\n"); - sb.append("Initial Segment Table Size : ").append(DebuggingUtils.toBase2SuffixedString(getInitialSegmentTableSize())).append(" slots\n"); - sb.append("Segment Data Page Size : ").append(DebuggingUtils.toBase2SuffixedString(getSegmentDataPageSize())).append("B\n"); - return sb.toString(); + String sb = "Heuristic Configuration: \n" + "Maximum Size (specified) : " + DebuggingUtils.toBase2SuffixedString(getMaximumSize()) + "B\n" + + "Minimum Chunk Size : " + DebuggingUtils.toBase2SuffixedString(getMinimumChunkSize()) + "B\n" + + "Maximum Chunk Size : " + DebuggingUtils.toBase2SuffixedString(getMaximumChunkSize()) + "B\n" + + "Concurrency : " + getConcurrency() + "\n" + + "Initial Segment Table Size : " + DebuggingUtils.toBase2SuffixedString(getInitialSegmentTableSize()) + " slots\n" + + "Segment Data Page Size : " + DebuggingUtils.toBase2SuffixedString(getSegmentDataPageSize()) + "B\n"; + return sb; } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java index f65a9bcbe9..5b5216d03c 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java @@ -125,7 +125,7 @@ private enum Mode { ATTACHED, DETACHED } - private void writeObject(java.io.ObjectOutputStream out) throws IOException { + private void writeObject(java.io.ObjectOutputStream out) { throw new UnsupportedOperationException("This subclass of AbstractValueHolder is NOT serializable"); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/MemorySizeParser.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/MemorySizeParser.java index 0b89ab895e..696a150676 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/MemorySizeParser.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/MemorySizeParser.java @@ -87,8 +87,8 @@ private static MemorySize toMemorySize(String configuredMemorySize, long unitMul * Memory size calculator. */ private static final class MemorySize { - private String configuredMemorySizeWithoutUnit; - private long multiplicationFactor; + private final String configuredMemorySizeWithoutUnit; + private final long multiplicationFactor; private MemorySize(String configuredMemorySizeWithoutUnit, long multiplicationFactor) { this.configuredMemorySizeWithoutUnit = configuredMemorySizeWithoutUnit; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java index e62ce0984b..7bd39b9e6f 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java @@ -274,7 +274,7 @@ public void initAuthoritativeTier(AuthoritativeTier resource) { @Override public LowerCachingTier createCachingTier(Configuration storeConfig, ServiceConfiguration... serviceConfigs) { - OffHeapStore lowerCachingTier = createStoreInternal(storeConfig, NullStoreEventDispatcher.nullStoreEventDispatcher(), serviceConfigs); + OffHeapStore lowerCachingTier = createStoreInternal(storeConfig, NullStoreEventDispatcher.nullStoreEventDispatcher(), serviceConfigs); Collection> tieredOps = new ArrayList<>(); MappedOperationStatistic get @@ -303,12 +303,10 @@ public void releaseCachingTier(LowerCachingTier resource) { releaseStore((Store) resource); } - private void flushToLowerTier(OffHeapStore resource) { + private void flushToLowerTier(OffHeapStore offheapStore) { StoreAccessException lastFailure = null; int failureCount = 0; - OffHeapStore offheapStore = resource; - Set keys = offheapStore.backingMap().keySet(); - for (Object key : keys) { + for (Object key : offheapStore.backingMap().keySet()) { try { offheapStore.invalidate(key); } catch (StoreAccessException cae) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java index 798c441397..a4456d33d8 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java @@ -39,7 +39,6 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; -import java.util.function.BiFunction; import java.util.function.Function; import static java.util.Collections.unmodifiableSet; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java index 0715da14d9..fe0ea103f4 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java @@ -336,8 +336,7 @@ public int rank(final Set> resourceTypes, final Collection> cachingResources = new HashSet<>(); - cachingResources.addAll(resourceTypes); + Set> cachingResources = new HashSet<>(resourceTypes); cachingResources.remove(authorityResource); int cachingTierRank = 0; Collection cachingTierProviders = serviceProvider.getServicesOfType(CachingTier.Provider.class); @@ -376,8 +375,7 @@ public Store createStore(Configuration storeConfig, ServiceCo ResourceType authorityResource = getAuthorityResource(resourcePools.getResourceTypeSet()); AuthoritativeTier.Provider authoritativeTierProvider = getAuthoritativeTierProvider(authorityResource, enhancedServiceConfigs); - Set> cachingResources = new HashSet<>(); - cachingResources.addAll(resourcePools.getResourceTypeSet()); + Set> cachingResources = new HashSet<>(resourcePools.getResourceTypeSet()); cachingResources.remove(authorityResource); CachingTier.Provider cachingTierProvider = getCachingTierProvider(cachingResources, enhancedServiceConfigs); @@ -439,11 +437,11 @@ public void releaseStore(Store resource) { // and thus not be in a state when they can invalidate anymore tieredStore.authoritativeTier.setInvalidationValve(new AuthoritativeTier.InvalidationValve() { @Override - public void invalidateAll() throws StoreAccessException { + public void invalidateAll() { } @Override - public void invalidateAllWithHash(long hash) throws StoreAccessException { + public void invalidateAllWithHash(long hash) { } }); entry.getKey().releaseCachingTier(tieredStore.realCachingTier); @@ -482,14 +480,14 @@ public NoopCachingTier(final AuthoritativeTier authoritativeTier) { } @Override - public ValueHolder getOrComputeIfAbsent(final K key, final Function> source) throws StoreAccessException { + public ValueHolder getOrComputeIfAbsent(final K key, final Function> source) { final ValueHolder apply = source.apply(key); authoritativeTier.flush(key, apply); return apply; } @Override - public void invalidate(final K key) throws StoreAccessException { + public void invalidate(final K key) { // noop } @@ -499,7 +497,7 @@ public void invalidateAll() { } @Override - public void clear() throws StoreAccessException { + public void clear() { // noop } @@ -509,7 +507,7 @@ public void setInvalidationListener(final InvalidationListener invalidatio } @Override - public void invalidateAllWithHash(long hash) throws StoreAccessException { + public void invalidateAllWithHash(long hash) { // noop } diff --git a/impl/src/main/java/org/ehcache/impl/internal/util/ByteBufferInputStream.java b/impl/src/main/java/org/ehcache/impl/internal/util/ByteBufferInputStream.java index 369e57f86e..d9af55b39b 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/util/ByteBufferInputStream.java +++ b/impl/src/main/java/org/ehcache/impl/internal/util/ByteBufferInputStream.java @@ -31,7 +31,7 @@ public ByteBufferInputStream(ByteBuffer buffer) { } @Override - public int read() throws IOException { + public int read() { if (buffer.hasRemaining()) { return 0xff & buffer.get(); } else { diff --git a/impl/src/main/java/org/ehcache/impl/persistence/DefaultDiskResourceService.java b/impl/src/main/java/org/ehcache/impl/persistence/DefaultDiskResourceService.java index 9383c5a849..2d3e273a19 100644 --- a/impl/src/main/java/org/ehcache/impl/persistence/DefaultDiskResourceService.java +++ b/impl/src/main/java/org/ehcache/impl/persistence/DefaultDiskResourceService.java @@ -170,7 +170,7 @@ private void checkStarted() { * {@inheritDoc} */ @Override - public void destroy(String name) throws CachePersistenceException { + public void destroy(String name) { checkStarted(); if(persistenceService == null) { @@ -218,7 +218,7 @@ public StateRepository getStateRepositoryWithin(PersistenceSpaceIdentifier id return stateRepository; } - private CachePersistenceException newCachePersistenceException(PersistenceSpaceIdentifier identifier) throws CachePersistenceException { + private CachePersistenceException newCachePersistenceException(PersistenceSpaceIdentifier identifier) { return new CachePersistenceException("Unknown space: " + identifier); } diff --git a/impl/src/main/java/org/ehcache/impl/persistence/FileBasedStateRepository.java b/impl/src/main/java/org/ehcache/impl/persistence/FileBasedStateRepository.java index 91f367f6c9..90a5ac0c49 100644 --- a/impl/src/main/java/org/ehcache/impl/persistence/FileBasedStateRepository.java +++ b/impl/src/main/java/org/ehcache/impl/persistence/FileBasedStateRepository.java @@ -64,6 +64,7 @@ class FileBasedStateRepository implements StateRepository, Closeable { @SuppressFBWarnings("NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE") private void loadMaps() throws CachePersistenceException { try { + //noinspection ConstantConditions for (File file : dataDirectory.listFiles((dir, name) -> name.endsWith(HOLDER_FILE_SUFFIX))) { try (FileInputStream fis = new FileInputStream(file); ObjectInputStream oin = new ObjectInputStream(fis)) { diff --git a/impl/src/main/java/org/ehcache/impl/serialization/ByteArraySerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/ByteArraySerializer.java index ab3ccc5bb5..ddb8390083 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/ByteArraySerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/ByteArraySerializer.java @@ -60,7 +60,7 @@ public ByteBuffer serialize(byte[] object) throws SerializerException { * {@inheritDoc} */ @Override - public byte[] read(ByteBuffer binary) throws ClassNotFoundException, SerializerException { + public byte[] read(ByteBuffer binary) { byte[] bytes = new byte[binary.remaining()]; binary.get(bytes); return bytes; @@ -70,7 +70,7 @@ public byte[] read(ByteBuffer binary) throws ClassNotFoundException, SerializerE * {@inheritDoc} */ @Override - public boolean equals(byte[] object, ByteBuffer binary) throws ClassNotFoundException, SerializerException { + public boolean equals(byte[] object, ByteBuffer binary) { boolean equals = binary.equals(serialize(object)); binary.position(binary.limit()); return equals; diff --git a/impl/src/main/java/org/ehcache/impl/serialization/CharSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/CharSerializer.java index 094c9984be..a5fb2bea5f 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/CharSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/CharSerializer.java @@ -58,16 +58,15 @@ public ByteBuffer serialize(Character object) { * {@inheritDoc} */ @Override - public Character read(ByteBuffer binary) throws ClassNotFoundException { - char c = binary.getChar(); - return c; + public Character read(ByteBuffer binary) { + return binary.getChar(); } /** * {@inheritDoc} */ @Override - public boolean equals(Character object, ByteBuffer binary) throws ClassNotFoundException { + public boolean equals(Character object, ByteBuffer binary) { return object.equals(read(binary)); } } diff --git a/impl/src/main/java/org/ehcache/impl/serialization/CompactJavaSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/CompactJavaSerializer.java index e680c8a5f3..f442732a8e 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/CompactJavaSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/CompactJavaSerializer.java @@ -79,7 +79,7 @@ public static Class> asTypedSerializer() { @Override public void init(final StateRepository stateRepository) { this.readLookup = stateRepository.getPersistentStateHolder("CompactJavaSerializer-ObjectStreamClassIndex", Integer.class, ObjectStreamClass.class); - loadMappingsInWriteContext(readLookup.entrySet(), true); + loadMappingsInWriteContext(readLookup.entrySet()); } /** @@ -146,7 +146,7 @@ private int getOrAddMapping(ObjectStreamClass desc) throws IOException { } } - private int addMappingUnderLock(ObjectStreamClass desc, SerializableDataKey probe) throws IOException { + private int addMappingUnderLock(ObjectStreamClass desc, SerializableDataKey probe) { ObjectStreamClass disconnected = disconnect(desc); SerializableDataKey key = new SerializableDataKey(disconnected, true); while (true) { @@ -169,12 +169,12 @@ private int addMappingUnderLock(ObjectStreamClass desc, SerializableDataKey prob } } - private void loadMappingsInWriteContext(Set> entries, boolean throwOnFailedPutIfAbsent) { + private void loadMappingsInWriteContext(Set> entries) { for (Entry entry : entries) { Integer index = entry.getKey(); ObjectStreamClass discOsc = disconnect(entry.getValue()); readLookupLocalCache.put(index, discOsc); - if (writeLookup.putIfAbsent(new SerializableDataKey(discOsc, true), index) != null && throwOnFailedPutIfAbsent) { + if (writeLookup.putIfAbsent(new SerializableDataKey(discOsc, true), index) != null) { throw new AssertionError("Corrupted data " + readLookup); } if (nextStreamIndex < index + 1) { @@ -205,7 +205,7 @@ class OIS extends ObjectInputStream { } @Override - protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { + protected ObjectStreamClass readClassDescriptor() throws IOException { int key = readInt(); ObjectStreamClass objectStreamClass = readLookupLocalCache.get(key); if (objectStreamClass != null) { diff --git a/impl/src/main/java/org/ehcache/impl/serialization/DoubleSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/DoubleSerializer.java index cd482def9a..f74607f2fd 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/DoubleSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/DoubleSerializer.java @@ -59,8 +59,7 @@ public ByteBuffer serialize(Double object) { */ @Override public Double read(ByteBuffer binary) throws ClassNotFoundException { - double d = binary.getDouble(); - return d; + return binary.getDouble(); } /** diff --git a/impl/src/main/java/org/ehcache/impl/serialization/FloatSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/FloatSerializer.java index 6dab6a8cdc..23714b4531 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/FloatSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/FloatSerializer.java @@ -58,16 +58,15 @@ public ByteBuffer serialize(Float object) { * {@inheritDoc} */ @Override - public Float read(ByteBuffer binary) throws ClassNotFoundException { - float f = binary.getFloat(); - return f; + public Float read(ByteBuffer binary) { + return binary.getFloat(); } /** * {@inheritDoc} */ @Override - public boolean equals(Float object, ByteBuffer binary) throws ClassNotFoundException { + public boolean equals(Float object, ByteBuffer binary) { return object.equals(read(binary)); } } diff --git a/impl/src/main/java/org/ehcache/impl/serialization/IntegerSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/IntegerSerializer.java index 38097f322f..40ddc10089 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/IntegerSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/IntegerSerializer.java @@ -58,16 +58,15 @@ public ByteBuffer serialize(Integer object) { * {@inheritDoc} */ @Override - public Integer read(ByteBuffer binary) throws ClassNotFoundException { - int i = binary.getInt(); - return i; + public Integer read(ByteBuffer binary) { + return binary.getInt(); } /** * {@inheritDoc} */ @Override - public boolean equals(Integer object, ByteBuffer binary) throws ClassNotFoundException { + public boolean equals(Integer object, ByteBuffer binary) { return object.equals(read(binary)); } } diff --git a/impl/src/main/java/org/ehcache/impl/serialization/LongSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/LongSerializer.java index 7d7697d29a..09dc514002 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/LongSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/LongSerializer.java @@ -59,8 +59,7 @@ public ByteBuffer serialize(Long object) { */ @Override public Long read(ByteBuffer binary) throws ClassNotFoundException { - long l = binary.getLong(); - return l; + return binary.getLong(); } /** diff --git a/impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java b/impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java index 12e938143b..a5c8cb420d 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java @@ -45,17 +45,10 @@ public PlainJavaSerializer(ClassLoader classLoader) { @Override public ByteBuffer serialize(T object) { ByteArrayOutputStream bout = new ByteArrayOutputStream(); - try { - ObjectOutputStream oout = new ObjectOutputStream(bout); + try(ObjectOutputStream oout = new ObjectOutputStream(bout)) { oout.writeObject(object); } catch (IOException e) { throw new SerializerException(e); - } finally { - try { - bout.close(); - } catch (IOException e) { - throw new AssertionError(e); - } } return ByteBuffer.wrap(bout.toByteArray()); } @@ -94,7 +87,7 @@ public OIS(InputStream in, ClassLoader classLoader) throws IOException { } @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { + protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundException { try { return Class.forName(desc.getName(), false, classLoader); } catch (ClassNotFoundException cnfe) { @@ -107,7 +100,7 @@ protected Class resolveClass(ObjectStreamClass desc) throws IOException, Clas } @Override - protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { + protected Class resolveProxyClass(String[] interfaces) throws ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader); diff --git a/impl/src/main/java/org/ehcache/impl/serialization/TransientStateRepository.java b/impl/src/main/java/org/ehcache/impl/serialization/TransientStateRepository.java index 6010b8ed6c..9fb70bda74 100644 --- a/impl/src/main/java/org/ehcache/impl/serialization/TransientStateRepository.java +++ b/impl/src/main/java/org/ehcache/impl/serialization/TransientStateRepository.java @@ -29,7 +29,7 @@ */ public class TransientStateRepository implements StateRepository { - private ConcurrentMap> knownHolders = new ConcurrentHashMap<>(); + private final ConcurrentMap> knownHolders = new ConcurrentHashMap<>(); @Override @SuppressWarnings("unchecked") diff --git a/impl/src/slow-test/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMapITest.java b/impl/src/slow-test/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMapITest.java index 25ff999284..7932ba1919 100644 --- a/impl/src/slow-test/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMapITest.java +++ b/impl/src/slow-test/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMapITest.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.concurrent; -import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.junit.Test; import java.util.ArrayList; @@ -146,7 +145,7 @@ private void assertThings(final ConcurrentHashMap map) { assertThat(map.size(), is(ENTRIES)); for(int i = 0; i < 100; i ++) { - final HashSet randomValues = new HashSet(getRandomValues(map, ENTRIES)); + final HashSet randomValues = new HashSet(getRandomValues(map)); assertThat(randomValues.size(), is(ENTRIES)); for (Object randomValue : randomValues) { assertThat(randomValue, instanceOf(KeyHolder.class)); @@ -156,10 +155,10 @@ private void assertThings(final ConcurrentHashMap map) { } } - private static List getRandomValues(Map map, int amount) { + private static List getRandomValues(Map map) { List values = new ArrayList(map.values()); Collections.shuffle(values); - return values.subList(0, amount); + return values.subList(0, ENTRIES); } @@ -202,7 +201,7 @@ static class EvilComparableKey extends EvilKey implements Comparable getDescriptors() { final CacheConfiguration cacheConfig = cacheBinding.getCache().getRuntimeConfiguration(); List> resourceTypes = new ArrayList<>(cacheConfig.getResourcePools().getResourceTypeSet()); - Collections.sort(resourceTypes, RESOURCE_TYPE_COMPARATOR); + resourceTypes.sort(RESOURCE_TYPE_COMPARATOR); Map> map = new LinkedHashMap<>(); for (ResourceType type : resourceTypes) { map.put(type.toString(), type); diff --git a/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java b/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java index e700e181b4..5ec1af5aca 100644 --- a/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java +++ b/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java @@ -61,7 +61,7 @@ public final Collection getDescriptors() { capabilities.addAll(((StandardEhcacheStatistics) o).getDescriptors()); } List list = new ArrayList<>(capabilities); - Collections.sort(list, STATISTIC_DESCRIPTOR_COMPARATOR); + list.sort(STATISTIC_DESCRIPTOR_COMPARATOR); return list; } diff --git a/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java b/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java index 32f1297992..36f8d997e3 100644 --- a/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java +++ b/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java @@ -30,13 +30,12 @@ public class StandardEhcacheStatistics extends ExposedCacheBinding { private final StatisticRegistry statisticRegistry; - private final String cacheName; StandardEhcacheStatistics(ManagementRegistryServiceConfiguration registryConfiguration, CacheBinding cacheBinding, StatisticsService statisticsService) { super(registryConfiguration, cacheBinding); - this.cacheName = cacheBinding.getAlias(); this.statisticRegistry = new StatisticRegistry(cacheBinding.getCache()); + String cacheName = cacheBinding.getAlias(); CacheStatistics cacheStatistics = statisticsService.getCacheStatistics(cacheName); Map knownStatistics = cacheStatistics.getKnownStatistics(); diff --git a/management/src/main/java/org/ehcache/management/registry/DefaultCollectorService.java b/management/src/main/java/org/ehcache/management/registry/DefaultCollectorService.java index 89662baa9d..99b8e22511 100644 --- a/management/src/main/java/org/ehcache/management/registry/DefaultCollectorService.java +++ b/management/src/main/java/org/ehcache/management/registry/DefaultCollectorService.java @@ -29,11 +29,8 @@ import org.ehcache.spi.service.ServiceDependencies; import org.ehcache.spi.service.ServiceProvider; import org.terracotta.management.model.notification.ContextualNotification; -import org.terracotta.management.model.stats.ContextualStatistics; import org.terracotta.management.registry.collect.DefaultStatisticCollector; -import org.terracotta.management.registry.collect.StatisticCollector; -import java.util.Collection; import java.util.concurrent.ScheduledExecutorService; import static org.ehcache.impl.internal.executor.ExecutorUtil.shutdownNow; diff --git a/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java b/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java index 6049ad891f..2c468806d0 100644 --- a/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java +++ b/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java @@ -37,7 +37,6 @@ import org.ehcache.spi.service.ServiceProvider; import org.terracotta.management.model.context.ContextContainer; import org.terracotta.management.registry.DefaultManagementRegistry; -import org.terracotta.management.registry.ManagementProvider; import org.terracotta.statistics.StatisticsManager; import java.util.ArrayList; diff --git a/management/src/main/java/org/ehcache/management/registry/ManagementRegistryServiceConfigurationParser.java b/management/src/main/java/org/ehcache/management/registry/ManagementRegistryServiceConfigurationParser.java index 3acbdda68b..f030d14c54 100644 --- a/management/src/main/java/org/ehcache/management/registry/ManagementRegistryServiceConfigurationParser.java +++ b/management/src/main/java/org/ehcache/management/registry/ManagementRegistryServiceConfigurationParser.java @@ -78,13 +78,9 @@ public ServiceCreationConfiguration parseServiceCreat } } - private static String attr(Element element, String name, String def) { - String s = element.getAttribute(name); - return s == null || s.equals("") ? def : s; - } - private static String attr(Element element, String name) { - return attr(element, name, null); + String s = element.getAttribute(name); + return s == null || s.equals("") ? null : s; } private static String val(Element element) { diff --git a/spi-tester/src/main/java/org/ehcache/spi/test/After.java b/spi-tester/src/main/java/org/ehcache/spi/test/After.java index 59b30f5bce..3a124e163a 100644 --- a/spi-tester/src/main/java/org/ehcache/spi/test/After.java +++ b/spi-tester/src/main/java/org/ehcache/spi/test/After.java @@ -16,16 +16,15 @@ package org.ehcache.spi.test; -/** - * Indicates the annotated method has to be run after each SPI Test - * Created by rism on 19-02-2015. - */ - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Indicates the annotated method has to be run after each SPI Test + * Created by rism on 19-02-2015. + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface After { diff --git a/spi-tester/src/main/java/org/ehcache/spi/test/Before.java b/spi-tester/src/main/java/org/ehcache/spi/test/Before.java index e3fe2f34ab..53acbc80d1 100644 --- a/spi-tester/src/main/java/org/ehcache/spi/test/Before.java +++ b/spi-tester/src/main/java/org/ehcache/spi/test/Before.java @@ -16,16 +16,15 @@ package org.ehcache.spi.test; -/** - * Indicates the annotated method has to be run before each SPI Test - * Created by rism on 19-02-2015. - */ - import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +/** + * Indicates the annotated method has to be run before each SPI Test + * Created by rism on 19-02-2015. + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Before { diff --git a/spi-tester/src/main/java/org/ehcache/spi/test/Result.java b/spi-tester/src/main/java/org/ehcache/spi/test/Result.java index 763883b319..fee7f4db9e 100755 --- a/spi-tester/src/main/java/org/ehcache/spi/test/Result.java +++ b/spi-tester/src/main/java/org/ehcache/spi/test/Result.java @@ -24,7 +24,6 @@ */ public class Result { private long startTime; - private long endTime; private long runTime; private int runCount; private final List failedTests = new ArrayList<>(); @@ -48,7 +47,7 @@ public void testRunStarted() { } public void testRunFinished() { - endTime = System.nanoTime(); + long endTime = System.nanoTime(); runTime = (endTime - startTime) / 1000L; } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java index 774c66c65e..f429c53162 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java @@ -104,12 +104,12 @@ public void forget(Xid xid) throws XAException { } @Override - public int getTransactionTimeout() throws XAException { + public int getTransactionTimeout() { return transactionTimeoutInSeconds; } @Override - public boolean isSameRM(XAResource xaResource) throws XAException { + public boolean isSameRM(XAResource xaResource) { return xaResource == this; } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java index 1922e88592..6147b9835b 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java @@ -96,7 +96,7 @@ public OIS(InputStream in, ClassLoader classLoader) throws IOException { } @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { + protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundException { try { return Class.forName(desc.getName(), false, classLoader); } catch (ClassNotFoundException cnfe) { @@ -109,7 +109,7 @@ protected Class resolveClass(ObjectStreamClass desc) throws IOException, Clas } @Override - protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { + protected Class resolveProxyClass(String[] interfaces) throws ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader); diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/StoreEventSourceWrapper.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/StoreEventSourceWrapper.java index a85326b32d..575c453a77 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/StoreEventSourceWrapper.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/StoreEventSourceWrapper.java @@ -16,7 +16,6 @@ package org.ehcache.transactions.xa.internal; -import org.ehcache.event.EventType; import org.ehcache.impl.internal.events.StoreEventImpl; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventFilter; diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java index 91ced047ba..11bbbd936b 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java @@ -761,12 +761,14 @@ public Store createStore(Configuration storeConfig, ServiceCo throw new IllegalStateException("XAStore.Provider.createStore called without XAStoreConfiguration"); } - final Store.Provider underlyingStoreProvider = - selectProvider(configuredTypes, Arrays.asList(serviceConfigs), xaServiceConfiguration); + List> serviceConfigList = Arrays.asList(serviceConfigs); + + Store.Provider underlyingStoreProvider = + selectProvider(configuredTypes, serviceConfigList, xaServiceConfiguration); String uniqueXAResourceId = xaServiceConfiguration.getUniqueXAResourceId(); - List> underlyingServiceConfigs = new ArrayList<>(); - underlyingServiceConfigs.addAll(Arrays.asList(serviceConfigs)); + List> underlyingServiceConfigs = new ArrayList<>(serviceConfigList.size() + 5); // pad a bit because we add stuff + underlyingServiceConfigs.addAll(serviceConfigList); // eviction advisor EvictionAdvisor realEvictionAdvisor = storeConfig.getEvictionAdvisor(); @@ -892,7 +894,8 @@ public Duration getExpiryForUpdate(K key, ValueSupplier> o AtomicReference> softLockSerializerRef = new AtomicReference<>(); SoftLockValueCombinedSerializer softLockValueCombinedSerializer; if (storeConfig.getValueSerializer() instanceof StatefulSerializer) { - softLockValueCombinedSerializer = new StatefulSoftLockValueCombinedSerializer(softLockSerializerRef, storeConfig.getValueSerializer()); + softLockValueCombinedSerializer = new StatefulSoftLockValueCombinedSerializer<>(softLockSerializerRef, storeConfig + .getValueSerializer()); } else { softLockValueCombinedSerializer = new SoftLockValueCombinedSerializer<>(softLockSerializerRef, storeConfig .getValueSerializer()); diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java index 0321f8d2ef..bdcad8a840 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java @@ -114,7 +114,7 @@ public boolean equals(Object other) { return value.equals(that.value); } - private Object writeReplace() throws ObjectStreamException { + private Object writeReplace() { return new SerializedXAValueHolder<>(getId(), creationTime(NATIVE_TIME_UNIT), lastAccessTime(NATIVE_TIME_UNIT), expirationTime(NATIVE_TIME_UNIT), hits(), value(), valueSerialized); } @@ -143,7 +143,7 @@ private static class SerializedXAValueHolder implements Serializable { this.valueSerialized = valueSerialized; } - private Object readResolve() throws ObjectStreamException { + private Object readResolve() { return new XAValueHolder<>(id, creationTime, lastAccessTime, expirationTime, hits, value, valueSerialized); } } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/journal/TransientJournal.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/journal/TransientJournal.java index 795964bfe6..58997142a1 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/journal/TransientJournal.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/journal/TransientJournal.java @@ -65,12 +65,12 @@ public Entry(XAState state, boolean heuristic, Collection keys) { @Override public void saveCommitted(TransactionId transactionId, boolean heuristicDecision) { - save(transactionId, XAState.COMMITTED, heuristicDecision, Collections.emptySet()); + save(transactionId, XAState.COMMITTED, heuristicDecision, Collections.emptySet()); } @Override public void saveRolledBack(TransactionId transactionId, boolean heuristicDecision) { - save(transactionId, XAState.ROLLED_BACK, heuristicDecision, Collections.emptySet()); + save(transactionId, XAState.ROLLED_BACK, heuristicDecision, Collections.emptySet()); } @Override @@ -97,7 +97,7 @@ private void save(TransactionId transactionId, XAState xaState, boolean heuristi if (xaState == XAState.IN_DOUBT) { throw new IllegalStateException("A transaction cannot enter in-doubt state heuristically"); } else { - Entry replaced = states.replace(transactionId, new Entry<>(xaState, true, Collections.emptySet())); + Entry replaced = states.replace(transactionId, new Entry<>(xaState, true, Collections.emptySet())); if (replaced == null) { throw new IllegalStateException("Only in-doubt transactions can be heuristically terminated"); } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceHolder.java b/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceHolder.java index 27dbadca65..d439ae6762 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceHolder.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceHolder.java @@ -59,14 +59,14 @@ public ResourceBean getResourceBean() { /** * {@inheritDoc} */ - public void close() throws Exception { + public void close() { throw new UnsupportedOperationException("Ehcache3XAResourceHolder cannot be used with an XAPool"); } /** * {@inheritDoc} */ - public Object getConnectionHandle() throws Exception { + public Object getConnectionHandle() { throw new UnsupportedOperationException("Ehcache3XAResourceHolder cannot be used with an XAPool"); } @@ -81,7 +81,7 @@ public Date getLastReleaseDate() { * {@inheritDoc} */ public List getXAResourceHolders() { - return Collections.singletonList((XAResourceHolder) this); + return Collections.singletonList(this); } } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceProducer.java b/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceProducer.java index 1160abbed1..84fa57bec9 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceProducer.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/txmgr/btm/Ehcache3XAResourceProducer.java @@ -78,7 +78,7 @@ boolean isEmpty() { return xaResourceHolders.isEmpty(); } - public void endRecovery() throws RecoveryException { + public void endRecovery() { recoveryXAResourceHolder = null; } @@ -109,12 +109,12 @@ public void close() { } @Override - public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) throws Exception { + public XAStatefulHolder createPooledConnection(Object xaFactory, ResourceBean bean) { throw new UnsupportedOperationException("Ehcache is not connection-oriented"); } @Override - public Reference getReference() throws NamingException { + public Reference getReference() { return new Reference(Ehcache3XAResourceProducer.class.getName(), new StringRefAddr("uniqueName", getUniqueName()), ResourceObjectFactory.class.getName(), null); diff --git a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java index 38a4b5b20d..1d57e0b50b 100644 --- a/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java +++ b/xml/src/main/java/org/ehcache/xml/XmlConfiguration.java @@ -129,7 +129,7 @@ public XmlConfiguration(URL url) */ public XmlConfiguration(URL url, final ClassLoader classLoader) throws XmlConfigurationException { - this(url, classLoader, Collections.emptyMap()); + this(url, classLoader, Collections.emptyMap()); } /** @@ -231,9 +231,7 @@ private void parseConfiguration() serviceConfigs.add(new OffHeapDiskStoreProviderConfiguration(diskStoreThreading.getThreadPool())); } - for (ServiceCreationConfiguration serviceConfiguration : Collections.unmodifiableList(serviceConfigs)) { - serviceConfigurations.add(serviceConfiguration); - } + serviceConfigurations.addAll(serviceConfigs); for (ConfigurationParser.CacheDefinition cacheDefinition : configurationParser.getCacheElements()) { String alias = cacheDefinition.id(); From 278cbbb96084f97c34e56d7d34ecfdf0dbac651c Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 28 Dec 2017 16:55:29 -0500 Subject: [PATCH 077/779] Unnecessary semi-columns --- buildSrc/src/main/groovy/scripts/Utils.groovy | 4 ++-- docs/build.gradle | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/buildSrc/src/main/groovy/scripts/Utils.groovy b/buildSrc/src/main/groovy/scripts/Utils.groovy index b674c95236..6f46430b9d 100644 --- a/buildSrc/src/main/groovy/scripts/Utils.groovy +++ b/buildSrc/src/main/groovy/scripts/Utils.groovy @@ -37,7 +37,7 @@ class Utils { try { def proc = cmd.execute() revision = proc.text.trim() - } catch (IOException ioex) { + } catch (IOException) { revision = 'Unknown' } } @@ -96,7 +96,7 @@ class Utils { static def jvmForHome(File home) { def java = Jvm.forHome(home).javaExecutable - def versionCommand = "$java -version".execute(); + def versionCommand = "$java -version".execute() def version = JavaVersion.toVersion((versionCommand.err.text =~ /\w+ version "(.+)"/)[0][1]) return Jvm.discovered(home, version) } diff --git a/docs/build.gradle b/docs/build.gradle index a980e66ef1..10eebf4563 100644 --- a/docs/build.gradle +++ b/docs/build.gradle @@ -47,7 +47,7 @@ task copyImages(type: Copy) { asciidoctor.dependsOn copyCSS, copyImages asciidoctor { - separateOutputDirs = false; + separateOutputDirs = false attributes 'skip-front-matter': 'true' resources { From 4fffc3f92f84c5c4438a23077c5286d7dcffc2a9 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 28 Dec 2017 16:55:54 -0500 Subject: [PATCH 078/779] Compress css fields --- docs/css/ehcache.css | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/docs/css/ehcache.css b/docs/css/ehcache.css index 39e0ce70aa..ba6d54f6b8 100644 --- a/docs/css/ehcache.css +++ b/docs/css/ehcache.css @@ -270,8 +270,8 @@ select { #preamble { position: fixed; - top: 0px; - left: 0px; + top: 0; + left: 0; height: 100%; background-color: #5d6e7e; padding: 15px 10px; @@ -643,10 +643,7 @@ p a > code:hover { #header, #content, #footnotes, #footer { width: 100%; - margin-left: auto; - margin-right: auto; - margin-top: 0; - margin-bottom: 0; + margin: 0 auto; max-width: 62.5em; *zoom: 1; position: relative; @@ -870,9 +867,7 @@ p a > code:hover { } #content #toc { - border-style: solid; - border-width: 1px; - border-color: #e0e0dc; + border: 1px solid #e0e0dc; margin-bottom: 1.25em; padding: 1.25em; background: #f8f8f7; @@ -1005,9 +1000,7 @@ table.tableblock #preamble > .sectionbody > .paragraph:first-of-type p { } .exampleblock > .content { - border-style: solid; - border-width: 1px; - border-color: #e6e6e6; + border: 1px solid #e6e6e6; margin-bottom: 1.25em; padding: 1.25em; background: #fff; @@ -1024,9 +1017,7 @@ table.tableblock #preamble > .sectionbody > .paragraph:first-of-type p { } .sidebarblock { - border-style: solid; - border-width: 1px; - border-color: #e0e0dc; + border: 1px solid #e0e0dc; margin-bottom: 1.25em; padding: 1.25em; background: #f8f8f7; @@ -1432,9 +1423,7 @@ ul.checklist li > p:first-child > input[type="checkbox"]:first-child { } ul.inline { - margin: 0 auto .625em auto; - margin-left: -1.375em; - margin-right: 0; + margin: 0 0 .625em -1.375em; padding: 0; list-style: none; overflow: hidden From 0bf2ffcafe9247141d055bcd76b4cd8fd42d30a0 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 28 Dec 2017 20:54:24 -0500 Subject: [PATCH 079/779] Remove many useless code in OnHeapStore --- .../impl/internal/store/heap/OnHeapStore.java | 45 +++++++------------ 1 file changed, 17 insertions(+), 28 deletions(-) diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index f745c38ab7..80f29fd8a0 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -159,7 +159,7 @@ public class OnHeapStore implements Store, HigherCachingTier { @SuppressWarnings("unchecked") private volatile InvalidationListener invalidationListener = (InvalidationListener) NULL_INVALIDATION_LISTENER; - private CacheConfigurationChangeListener cacheConfigurationChangeListener = new CacheConfigurationChangeListener() { + private final CacheConfigurationChangeListener cacheConfigurationChangeListener = new CacheConfigurationChangeListener() { @Override public void cacheConfigurationChange(CacheConfigurationChangeEvent event) { if(event.getProperty().equals(CacheConfigurationProperty.UPDATE_SIZE)) { @@ -219,7 +219,7 @@ public OnHeapStore(final Configuration config, final TimeSource timeSource throw new NullPointerException("sizeOfEngine must not be null"); } this.sizeOfEngine = sizeOfEngine; - this.byteSized = this.sizeOfEngine instanceof NoopSizeOfEngine ? false : true; + this.byteSized = !(this.sizeOfEngine instanceof NoopSizeOfEngine); this.capacity = byteSized ? ((MemoryUnit) heapPool.getUnit()).toBytes(heapPool.getSize()) : heapPool.getSize(); this.timeSource = timeSource; if (config.getEvictionAdvisor() == null) { @@ -273,10 +273,10 @@ public OnHeapStore(final Configuration config, final TimeSource timeSource @Override public ValueHolder get(final K key) throws StoreAccessException { checkKey(key); - return internalGet(key, true); + return internalGet(key); } - private OnHeapValueHolder internalGet(final K key, final boolean updateAccess) throws StoreAccessException { + private OnHeapValueHolder internalGet(K key) throws StoreAccessException { getObserver.begin(); try { OnHeapValueHolder mapping = getQuiet(key); @@ -286,9 +286,8 @@ private OnHeapValueHolder internalGet(final K key, final boolean updateAccess return null; } - if (updateAccess) { - setAccessTimeAndExpiryThenReturnMappingOutsideLock(key, mapping, timeSource.getTimeMillis()); - } + setAccessTimeAndExpiryThenReturnMappingOutsideLock(key, mapping, timeSource.getTimeMillis()); + getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); return mapping; } catch (RuntimeException re) { @@ -416,21 +415,17 @@ public boolean remove(final K key) throws StoreAccessException { @Override public ValueHolder putIfAbsent(final K key, final V value) throws StoreAccessException { - return putIfAbsent(key, value, false); - } - - private OnHeapValueHolder putIfAbsent(final K key, final V value, boolean returnCurrentMapping) throws StoreAccessException { putIfAbsentObserver.begin(); checkKey(key); checkValue(value); - final AtomicReference> returnValue = new AtomicReference<>(null); - final AtomicBoolean entryActuallyAdded = new AtomicBoolean(); - final long now = timeSource.getTimeMillis(); - final StoreEventSink eventSink = storeEventDispatcher.eventSink(); + AtomicReference> returnValue = new AtomicReference<>(null); + AtomicBoolean entryActuallyAdded = new AtomicBoolean(); + long now = timeSource.getTimeMillis(); + StoreEventSink eventSink = storeEventDispatcher.eventSink(); try { - OnHeapValueHolder inCache = map.compute(key, (mappedKey, mappedValue) -> { + map.compute(key, (mappedKey, mappedValue) -> { if (mappedValue == null || mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { if (mappedValue != null) { updateUsageInBytesIfRequired(- mappedValue.size()); @@ -461,10 +456,6 @@ private OnHeapValueHolder putIfAbsent(final K key, final V value, boolean ret } else { putIfAbsentObserver.end(StoreOperationOutcomes.PutIfAbsentOutcome.HIT); } - - if (returnCurrentMapping) { - return inCache; - } } catch (RuntimeException re) { storeEventDispatcher.releaseEventSinkAfterFailure(eventSink, re); throw handleRuntimeException(re); @@ -643,7 +634,7 @@ public boolean hasNext() { } @Override - public Cache.Entry> next() throws StoreAccessException { + public Cache.Entry> next() { Entry> next = it.next(); final K key = next.getKey(); final OnHeapValueHolder value = next.getValue(); @@ -875,7 +866,7 @@ public void silentInvalidateAll(final BiFunction, Void> biFunc } @Override - public void silentInvalidateAllWithHash(long hash, BiFunction, Void> biFunction) throws StoreAccessException { + public void silentInvalidateAllWithHash(long hash, BiFunction, Void> biFunction) { silentInvalidateAllWithHashObserver.begin(); int intHash = HashUtils.longHashToInt(hash); Collection>> removed = map.removeAllWithHash(intHash); @@ -902,7 +893,7 @@ public void setInvalidationListener(final InvalidationListener providedInv } @Override - public void invalidateAllWithHash(long hash) throws StoreAccessException { + public void invalidateAllWithHash(long hash) { invalidateAllWithHashObserver.begin(); int intHash = HashUtils.longHashToInt(hash); Collection>> removed = map.removeAllWithHash(intHash); @@ -1270,7 +1261,7 @@ public StoreEventSource getStoreEventSource() { return storeEventDispatcher; } - private OnHeapValueHolder setAccessTimeAndExpiryThenReturnMappingOutsideLock(K key, OnHeapValueHolder valueHolder, long now) { + private void setAccessTimeAndExpiryThenReturnMappingOutsideLock(K key, OnHeapValueHolder valueHolder, long now) { Duration duration; try { duration = expiry.getExpiryForAccess(key, valueHolder); @@ -1285,9 +1276,7 @@ private OnHeapValueHolder setAccessTimeAndExpiryThenReturnMappingOutsideLock( if (Duration.ZERO.equals(duration)) { // Expires mapping through computeIfPresent expireMappingUnderLock(key, valueHolder); - return null; } - return valueHolder; } private OnHeapValueHolder setAccessTimeAndExpiryThenReturnMappingUnderLock(K key, OnHeapValueHolder valueHolder, long now, @@ -1435,7 +1424,7 @@ private OnHeapValueHolder importValueFromLowerTier(K key, ValueHolder valu private OnHeapValueHolder cloneValueHolder(K key, ValueHolder valueHolder, long now, Duration expiration, boolean sizingEnabled) throws LimitExceededException { V realValue = valueHolder.value(); boolean evictionAdvice = checkEvictionAdvice(key, realValue); - OnHeapValueHolder clonedValueHolder = null; + OnHeapValueHolder clonedValueHolder; if(valueCopier instanceof SerializingCopier) { if (valueHolder instanceof BinaryValueHolder && ((BinaryValueHolder) valueHolder).isBinaryValueAvailable()) { clonedValueHolder = new SerializedOnHeapValueHolder<>(valueHolder, ((BinaryValueHolder) valueHolder).getBinaryValue(), @@ -1696,7 +1685,7 @@ public void stop() { @Override public CachingTier createCachingTier(Configuration storeConfig, ServiceConfiguration... serviceConfigs) { - OnHeapStore cachingTier = createStoreInternal(storeConfig, NullStoreEventDispatcher.nullStoreEventDispatcher(), serviceConfigs); + OnHeapStore cachingTier = createStoreInternal(storeConfig, NullStoreEventDispatcher.nullStoreEventDispatcher(), serviceConfigs); Collection> tieredOps = new ArrayList<>(); MappedOperationStatistic get = From a669072cc4e27c6ea9cf4f5a784f006978334610 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 28 Dec 2017 21:13:00 -0500 Subject: [PATCH 080/779] Support Java 10 and more. It seems commons lang code doesn't support it correctly yet --- .../classes/commonslang/JavaVersion.java | 378 +++++++++--------- .../classes/commonslang/JavaVersionTest.java | 62 +++ 2 files changed, 252 insertions(+), 188 deletions(-) create mode 100644 impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java index 87187cd545..32963290b9 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java @@ -22,7 +22,7 @@ package org.ehcache.impl.internal.classes.commonslang; /** - *

An enum representing all the versions of the Java specification. + * An enum representing all the versions of the Java specification. * This is intended to mirror available values from the * java.specification.version System property. * @@ -30,195 +30,197 @@ */ public enum JavaVersion { - /** - * The Java version reported by Android. This is not an official Java version number. - */ - JAVA_0_9(1.5f, "0.9"), - - /** - * Java 1.1. - */ - JAVA_1_1(1.1f, "1.1"), - - /** - * Java 1.2. - */ - JAVA_1_2(1.2f, "1.2"), - - /** - * Java 1.3. - */ - JAVA_1_3(1.3f, "1.3"), - - /** - * Java 1.4. - */ - JAVA_1_4(1.4f, "1.4"), - - /** - * Java 1.5. - */ - JAVA_1_5(1.5f, "1.5"), - - /** - * Java 1.6. - */ - JAVA_1_6(1.6f, "1.6"), - - /** - * Java 1.7. - */ - JAVA_1_7(1.7f, "1.7"), - - /** - * Java 1.8. - */ - JAVA_1_8(1.8f, "1.8"), - - /** - * Java 1.9. - */ - JAVA_1_9(1.9f, "1.9"), - - /** - * Java 1.x, x > 9. Mainly introduced to avoid to break when a new version of Java is used. - */ - JAVA_RECENT(maxVersion(), Float.toString(maxVersion())); - - /** - * The float value. - */ - private final float value; - /** - * The standard name. - */ - private final String name; - - /** - * Constructor. - * - * @param value the float value - * @param name the standard name, not null - */ - JavaVersion(final float value, final String name) { - this.value = value; - this.name = name; + /** + * The Java version reported by Android. This is not an official Java version number. + */ + JAVA_0_9(1.5f, "0.9"), + + /** + * Java 1.1. + */ + JAVA_1_1(1.1f, "1.1"), + + /** + * Java 1.2. + */ + JAVA_1_2(1.2f, "1.2"), + + /** + * Java 1.3. + */ + JAVA_1_3(1.3f, "1.3"), + + /** + * Java 1.4. + */ + JAVA_1_4(1.4f, "1.4"), + + /** + * Java 1.5. + */ + JAVA_1_5(1.5f, "1.5"), + + /** + * Java 1.6. + */ + JAVA_1_6(1.6f, "1.6"), + + /** + * Java 1.7. + */ + JAVA_1_7(1.7f, "1.7"), + + /** + * Java 1.8. + */ + JAVA_1_8(1.8f, "1.8"), + + /** + * Java 1.9. + * + * @deprecated As of release 3.5, replaced by {@link #JAVA_9} + */ + @Deprecated + JAVA_1_9(9.0f, "9"), + + /** + * Java 9 + */ + JAVA_9(9.0f, "9"), + + /** + * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used. + */ + JAVA_RECENT(maxVersion(), Float.toString(maxVersion())); + + /** + * The float value. + */ + private final float value; + /** + * The standard name. + */ + private final String name; + + /** + * Constructor. + * + * @param value the float value + * @param name the standard name, not null + */ + JavaVersion(final float value, final String name) { + this.value = value; + this.name = name; + } + + //----------------------------------------------------------------------- + /** + *

Whether this version of Java is at least the version of Java passed in.

+ * + *

For example:
+ * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}

+ * + * @param requiredVersion the version to check against, not null + * @return true if this version is equal to or greater than the specified version + */ + public boolean atLeast(final JavaVersion requiredVersion) { + return this.value >= requiredVersion.value; + } + + /** + * Transforms the given string with a Java version number to the + * corresponding constant of this enumeration class. This method is used + * internally. + * + * @param nom the Java version as string + * @return the corresponding enumeration constant or null if the + * version is unknown + */ + // helper for static importing + static JavaVersion getJavaVersion(final String nom) { + return get(nom); + } + + /** + * Transforms the given string with a Java version number to the + * corresponding constant of this enumeration class. This method is used + * internally. + * + * @param nom the Java version as string + * @return the corresponding enumeration constant or null if the + * version is unknown + */ + static JavaVersion get(final String nom) { + if (nom == null) { + return null; } - - //----------------------------------------------------------------------- - /** - *

Whether this version of Java is at least the version of Java passed in. - * - *

For example:
- * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)} - * - * @param requiredVersion the version to check against, not null - * @return true if this version is equal to or greater than the specified version - */ - public boolean atLeast(final JavaVersion requiredVersion) { - return this.value >= requiredVersion.value; - } - - /** - * Transforms the given string with a Java version number to the - * corresponding constant of this enumeration class. This method is used - * internally. - * - * @param nom the Java version as string - * @return the corresponding enumeration constant or null if the - * version is unknown - */ - // helper for static importing - static JavaVersion getJavaVersion(final String nom) { - return get(nom); - } - - /** - * Transforms the given string with a Java version number to the - * corresponding constant of this enumeration class. This method is used - * internally. - * - * @param nom the Java version as string - * @return the corresponding enumeration constant or null if the - * version is unknown - */ - static JavaVersion get(final String nom) { - if ("0.9".equals(nom)) { - return JAVA_0_9; - } else if ("1.1".equals(nom)) { - return JAVA_1_1; - } else if ("1.2".equals(nom)) { - return JAVA_1_2; - } else if ("1.3".equals(nom)) { - return JAVA_1_3; - } else if ("1.4".equals(nom)) { - return JAVA_1_4; - } else if ("1.5".equals(nom)) { - return JAVA_1_5; - } else if ("1.6".equals(nom)) { - return JAVA_1_6; - } else if ("1.7".equals(nom)) { - return JAVA_1_7; - } else if ("1.8".equals(nom)) { - return JAVA_1_8; - } else if ("1.9".equals(nom)) { - return JAVA_1_9; - } - if (nom == null) { - return null; - } - final float v = toFloatVersion(nom); - if ((v - 1.) < 1.) { // then we need to check decimals > .9 - final int firstComma = Math.max(nom.indexOf('.'), nom.indexOf(',')); - final int end = Math.max(nom.length(), nom.indexOf(',', firstComma)); - if (Float.parseFloat(nom.substring(firstComma + 1, end)) > .9f) { - return JAVA_RECENT; - } - } - return null; + switch (nom) { + case "0.9": + return JAVA_0_9; + case "1.1": + return JAVA_1_1; + case "1.2": + return JAVA_1_2; + case "1.3": + return JAVA_1_3; + case "1.4": + return JAVA_1_4; + case "1.5": + return JAVA_1_5; + case "1.6": + return JAVA_1_6; + case "1.7": + return JAVA_1_7; + case "1.8": + return JAVA_1_8; + case "9": + return JAVA_9; } - - //----------------------------------------------------------------------- - /** - *

The string value is overridden to return the standard name. - * - *

For example, "1.5". - * - * @return the name, not null - */ - @Override - public String toString() { - return name; + return JAVA_RECENT; + } + + //----------------------------------------------------------------------- + /** + *

The string value is overridden to return the standard name.

+ * + *

For example, "1.5".

+ * + * @return the name, not null + */ + @Override + public String toString() { + return name; + } + + /** + * Gets the Java Version from the system or 99.0 if the {@code java.specification.version} system property is not set. + * + * @return the value of {@code java.specification.version} system property or 99.0 if it is not set. + */ + private static float maxVersion() { + final float v = toFloatVersion(System.getProperty("java.specification.version", "99.0")); + if (v > 0) { + return v; } - - /** - * Gets the Java Version from the system or 2.0 if the {@code java.version} system property is not set. - * - * @return the value of {@code java.version} system property or 2.0 if it is not set. - */ - private static float maxVersion() { - final float v = toFloatVersion(System.getProperty("java.version", "2.0")); - if (v > 0) { - return v; - } - return 2f; - } - - /** - * Parses a float value from a String. - * - * @param value the String to parse. - * @return the float value represented by teh string or -1 if the given String can not be parsed. - */ - private static float toFloatVersion(final String value) { - final String[] toParse = value.split("\\."); - if (toParse.length >= 2) { - try { - return Float.parseFloat(toParse[0] + '.' + toParse[1]); - } catch (final NumberFormatException nfe) { - // no-op, let use default - } - } - return -1; + return 99f; + } + + /** + * Parses a float value from a String. + * + * @param value the String to parse. + * @return the float value represented by the string or -1 if the given String can not be parsed. + */ + private static float toFloatVersion(final String value) { + if (value.contains(".")) { + final String[] toParse = value.split("\\."); + if (toParse.length >= 2) { + return Float.parseFloat(toParse[0] + '.' + toParse[1]); + } + } else { + return Float.parseFloat(value); } + return -1; + } } + diff --git a/impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java b/impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java new file mode 100644 index 0000000000..cb09e0ec1c --- /dev/null +++ b/impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java @@ -0,0 +1,62 @@ +package org.ehcache.impl.internal.classes.commonslang; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.*; + +/** + * @author Henri Tremblay + */ +public class JavaVersionTest { + + private String specification; + + @Before + public void before() { + specification = System.getProperty("java.specification.version"); + System.setProperty("java.specification.version", "20"); + } + + @After + public void after() { + System.setProperty("java.specification.version", specification); + } + + @Test + public void javaRecent() { + assertThat(JavaVersion.JAVA_RECENT.toString()).isEqualTo("20.0"); + } + + @Test + public void getJavaVersion() { + assertThat(JavaVersion.getJavaVersion(null)).isNull(); + assertThat(JavaVersion.getJavaVersion("0.9")).isEqualTo(JavaVersion.JAVA_0_9); + assertThat(JavaVersion.getJavaVersion("1.1")).isEqualTo(JavaVersion.JAVA_1_1); + assertThat(JavaVersion.getJavaVersion("1.2")).isEqualTo(JavaVersion.JAVA_1_2); + assertThat(JavaVersion.getJavaVersion("1.3")).isEqualTo(JavaVersion.JAVA_1_3); + assertThat(JavaVersion.getJavaVersion("1.4")).isEqualTo(JavaVersion.JAVA_1_4); + assertThat(JavaVersion.getJavaVersion("1.5")).isEqualTo(JavaVersion.JAVA_1_5); + assertThat(JavaVersion.getJavaVersion("1.6")).isEqualTo(JavaVersion.JAVA_1_6); + assertThat(JavaVersion.getJavaVersion("1.7")).isEqualTo(JavaVersion.JAVA_1_7); + assertThat(JavaVersion.getJavaVersion("1.8")).isEqualTo(JavaVersion.JAVA_1_8); + assertThat(JavaVersion.getJavaVersion("9")).isEqualTo(JavaVersion.JAVA_9); + assertThat(JavaVersion.getJavaVersion("10")).isEqualTo(JavaVersion.JAVA_RECENT); + } + + @Test + public void atLeast_true() { + assertThat(JavaVersion.JAVA_1_8.atLeast(JavaVersion.JAVA_1_7)).isTrue(); + assertThat(JavaVersion.JAVA_9.atLeast(JavaVersion.JAVA_1_8)).isTrue(); + assertThat(JavaVersion.JAVA_9.atLeast(JavaVersion.JAVA_9)).isTrue(); + assertThat(JavaVersion.getJavaVersion("10").atLeast(JavaVersion.JAVA_9)).isTrue(); + } + + @Test + public void atLeast_false() { + assertThat(JavaVersion.JAVA_1_7.atLeast(JavaVersion.JAVA_1_8)).isFalse(); + assertThat(JavaVersion.JAVA_1_8.atLeast(JavaVersion.JAVA_9)).isFalse(); + assertThat(JavaVersion.JAVA_9.atLeast(JavaVersion.getJavaVersion("10"))).isFalse(); + } +} From 48667ac0aedb2a0685811c37d22743a158e9a7e0 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 28 Dec 2017 22:56:50 -0500 Subject: [PATCH 081/779] We do know we are over Java 4 and using autoboxing --- .../classes/commonslang/ClassUtils.java | 63 +---- .../classes/commonslang/JavaVersion.java | 226 ------------------ .../classes/commonslang/SystemUtils.java | 100 -------- .../commonslang/reflect/ConstructorUtils.java | 2 +- .../classes/commonslang/JavaVersionTest.java | 62 ----- 5 files changed, 13 insertions(+), 440 deletions(-) delete mode 100644 impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java delete mode 100644 impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/SystemUtils.java delete mode 100644 impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java index 1b863ae7f5..ac9c248c21 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/ClassUtils.java @@ -109,10 +109,9 @@ public ClassUtils() { * * @param classArray the array of Classes to check, may be {@code null} * @param toClassArray the array of Classes to try to assign into, may be {@code null} - * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers * @return {@code true} if assignment possible */ - public static boolean isAssignable(Class[] classArray, Class[] toClassArray, final boolean autoboxing) { + public static boolean isAssignable(Class[] classArray, Class[] toClassArray) { if (!ArrayUtils.isSameLength(classArray, toClassArray)) { return false; } @@ -123,48 +122,13 @@ public static boolean isAssignable(Class[] classArray, Class[] toClassArra toClassArray = ArrayUtils.EMPTY_CLASS_ARRAY; } for (int i = 0; i < classArray.length; i++) { - if (!isAssignable(classArray[i], toClassArray[i], autoboxing)) { + if (!isAssignable(classArray[i], toClassArray[i])) { return false; } } return true; } - /** - *

Checks if one {@code Class} can be assigned to a variable of - * another {@code Class}. - * - *

Unlike the {@link Class#isAssignableFrom(java.lang.Class)} method, - * this method takes into account widenings of primitive classes and - * {@code null}s. - * - *

Primitive widenings allow an int to be assigned to a long, float or - * double. This method returns the correct result for these cases. - * - *

{@code Null} may be assigned to any reference type. This method - * will return {@code true} if {@code null} is passed in and the - * toClass is non-primitive. - * - *

Specifically, this method tests whether the type represented by the - * specified {@code Class} parameter can be converted to the type - * represented by this {@code Class} object via an identity conversion - * widening primitive or widening reference conversion. See - * The Java Language Specification, - * sections 5.1.1, 5.1.2 and 5.1.4 for details. - * - *

Since Lang 3.0, this method will default behavior for - * calculating assignability between primitive and wrapper types corresponding - * to the running Java version; i.e. autoboxing will be the default - * behavior in VMs running Java versions > 1.5. - * - * @param cls the Class to check, may be null - * @param toClass the Class to try to assign into, returns false if null - * @return {@code true} if assignment possible - */ - public static boolean isAssignable(final Class cls, final Class toClass) { - return isAssignable(cls, toClass, SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_5)); - } - /** *

Checks if one {@code Class} can be assigned to a variable of * another {@code Class}. @@ -189,10 +153,9 @@ public static boolean isAssignable(final Class cls, final Class toClass) { * * @param cls the Class to check, may be null * @param toClass the Class to try to assign into, returns false if null - * @param autoboxing whether to use implicit autoboxing/unboxing between primitives and wrappers * @return {@code true} if assignment possible */ - public static boolean isAssignable(Class cls, final Class toClass, final boolean autoboxing) { + public static boolean isAssignable(Class cls, final Class toClass) { if (toClass == null) { return false; } @@ -201,18 +164,16 @@ public static boolean isAssignable(Class cls, final Class toClass, final b return !toClass.isPrimitive(); } //autoboxing: - if (autoboxing) { - if (cls.isPrimitive() && !toClass.isPrimitive()) { - cls = primitiveToWrapper(cls); - if (cls == null) { - return false; - } + if (cls.isPrimitive() && !toClass.isPrimitive()) { + cls = primitiveToWrapper(cls); + if (cls == null) { + return false; } - if (toClass.isPrimitive() && !cls.isPrimitive()) { - cls = wrapperToPrimitive(cls); - if (cls == null) { - return false; - } + } + if (toClass.isPrimitive() && !cls.isPrimitive()) { + cls = wrapperToPrimitive(cls); + if (cls == null) { + return false; } } if (cls.equals(toClass)) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java deleted file mode 100644 index 32963290b9..0000000000 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/JavaVersion.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/* - * This is a modified version of the original Apache class. It has had unused - * members removed. - */ -package org.ehcache.impl.internal.classes.commonslang; - -/** - * An enum representing all the versions of the Java specification. - * This is intended to mirror available values from the - * java.specification.version System property. - * - * @since 3.0 - */ -public enum JavaVersion { - - /** - * The Java version reported by Android. This is not an official Java version number. - */ - JAVA_0_9(1.5f, "0.9"), - - /** - * Java 1.1. - */ - JAVA_1_1(1.1f, "1.1"), - - /** - * Java 1.2. - */ - JAVA_1_2(1.2f, "1.2"), - - /** - * Java 1.3. - */ - JAVA_1_3(1.3f, "1.3"), - - /** - * Java 1.4. - */ - JAVA_1_4(1.4f, "1.4"), - - /** - * Java 1.5. - */ - JAVA_1_5(1.5f, "1.5"), - - /** - * Java 1.6. - */ - JAVA_1_6(1.6f, "1.6"), - - /** - * Java 1.7. - */ - JAVA_1_7(1.7f, "1.7"), - - /** - * Java 1.8. - */ - JAVA_1_8(1.8f, "1.8"), - - /** - * Java 1.9. - * - * @deprecated As of release 3.5, replaced by {@link #JAVA_9} - */ - @Deprecated - JAVA_1_9(9.0f, "9"), - - /** - * Java 9 - */ - JAVA_9(9.0f, "9"), - - /** - * The most recent java version. Mainly introduced to avoid to break when a new version of Java is used. - */ - JAVA_RECENT(maxVersion(), Float.toString(maxVersion())); - - /** - * The float value. - */ - private final float value; - /** - * The standard name. - */ - private final String name; - - /** - * Constructor. - * - * @param value the float value - * @param name the standard name, not null - */ - JavaVersion(final float value, final String name) { - this.value = value; - this.name = name; - } - - //----------------------------------------------------------------------- - /** - *

Whether this version of Java is at least the version of Java passed in.

- * - *

For example:
- * {@code myVersion.atLeast(JavaVersion.JAVA_1_4)}

- * - * @param requiredVersion the version to check against, not null - * @return true if this version is equal to or greater than the specified version - */ - public boolean atLeast(final JavaVersion requiredVersion) { - return this.value >= requiredVersion.value; - } - - /** - * Transforms the given string with a Java version number to the - * corresponding constant of this enumeration class. This method is used - * internally. - * - * @param nom the Java version as string - * @return the corresponding enumeration constant or null if the - * version is unknown - */ - // helper for static importing - static JavaVersion getJavaVersion(final String nom) { - return get(nom); - } - - /** - * Transforms the given string with a Java version number to the - * corresponding constant of this enumeration class. This method is used - * internally. - * - * @param nom the Java version as string - * @return the corresponding enumeration constant or null if the - * version is unknown - */ - static JavaVersion get(final String nom) { - if (nom == null) { - return null; - } - switch (nom) { - case "0.9": - return JAVA_0_9; - case "1.1": - return JAVA_1_1; - case "1.2": - return JAVA_1_2; - case "1.3": - return JAVA_1_3; - case "1.4": - return JAVA_1_4; - case "1.5": - return JAVA_1_5; - case "1.6": - return JAVA_1_6; - case "1.7": - return JAVA_1_7; - case "1.8": - return JAVA_1_8; - case "9": - return JAVA_9; - } - return JAVA_RECENT; - } - - //----------------------------------------------------------------------- - /** - *

The string value is overridden to return the standard name.

- * - *

For example, "1.5".

- * - * @return the name, not null - */ - @Override - public String toString() { - return name; - } - - /** - * Gets the Java Version from the system or 99.0 if the {@code java.specification.version} system property is not set. - * - * @return the value of {@code java.specification.version} system property or 99.0 if it is not set. - */ - private static float maxVersion() { - final float v = toFloatVersion(System.getProperty("java.specification.version", "99.0")); - if (v > 0) { - return v; - } - return 99f; - } - - /** - * Parses a float value from a String. - * - * @param value the String to parse. - * @return the float value represented by the string or -1 if the given String can not be parsed. - */ - private static float toFloatVersion(final String value) { - if (value.contains(".")) { - final String[] toParse = value.split("\\."); - if (toParse.length >= 2) { - return Float.parseFloat(toParse[0] + '.' + toParse[1]); - } - } else { - return Float.parseFloat(value); - } - return -1; - } -} - diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/SystemUtils.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/SystemUtils.java deleted file mode 100644 index 08d23aef09..0000000000 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/SystemUtils.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You 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. - */ - -/* - * This is a modified version of the original Apache class. It has had unused - * members removed. - */ -package org.ehcache.impl.internal.classes.commonslang; - -/** - *

- * Helpers for {@code java.lang.System}. - *

- * If a system property cannot be read due to security restrictions, the corresponding field in this class will be set - * to {@code null} and a message will be written to {@code System.err}. - *

- * #ThreadSafe# - * - * @since 1.0 - */ -public class SystemUtils { - - /** - * The {@code java.specification.version} System Property. Java Runtime Environment specification version. - *

- * Defaults to {@code null} if the runtime does not have security access to read this property or the property does - * not exist. - *

- * This value is initialized when the class is loaded. If {@link System#setProperty(String,String)} or - * {@link System#setProperties(java.util.Properties)} is called after this class is loaded, the value will be out of - * sync with that System property. - * - * @since Java 1.3 - */ - public static final String JAVA_SPECIFICATION_VERSION = getSystemProperty("java.specification.version"); - private static final JavaVersion JAVA_SPECIFICATION_VERSION_AS_ENUM = JavaVersion.get(JAVA_SPECIFICATION_VERSION); - - // ----------------------------------------------------------------------- - /** - * Gets a System property, defaulting to {@code null} if the property cannot be read. - *

- * If a {@code SecurityException} is caught, the return value is {@code null} and a message is written to - * {@code System.err}. - * - * @param property the system property name - * @return the system property value or {@code null} if a security problem occurs - */ - private static String getSystemProperty(final String property) { - try { - return System.getProperty(property); - } catch (final SecurityException ex) { - // we are not allowed to look at this property - System.err.println("Caught a SecurityException reading the system property '" + property - + "'; the SystemUtils property value will default to null."); - return null; - } - } - - /** - * Is the Java version at least the requested version. - *

- * Example input: - *

    - *
  • {@code 1.2f} to test for Java 1.2
  • - *
  • {@code 1.31f} to test for Java 1.3.1
  • - *
- * - * @param requiredVersion the required version, for example 1.31f - * @return {@code true} if the actual version is equal or greater than the required version - */ - public static boolean isJavaVersionAtLeast(final JavaVersion requiredVersion) { - return JAVA_SPECIFICATION_VERSION_AS_ENUM.atLeast(requiredVersion); - } - - // ----------------------------------------------------------------------- - /** - * SystemUtils instances should NOT be constructed in standard programming. Instead, the class should be used as - * {@code SystemUtils.FILE_SEPARATOR}. - *

- * This constructor is public to permit tools that require a JavaBean instance to operate. - */ - public SystemUtils() { - super(); - } - -} diff --git a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java index 10a5cf336e..19521b6bf4 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/ConstructorUtils.java @@ -178,7 +178,7 @@ public static Constructor getMatchingAccessibleConstructor(final Class // return best match: for (Constructor ctor : ctors) { // compare parameters - if (ClassUtils.isAssignable(parameterTypes, ctor.getParameterTypes(), true)) { + if (ClassUtils.isAssignable(parameterTypes, ctor.getParameterTypes())) { // get accessible version of constructor ctor = getAccessibleConstructor(ctor); if (ctor != null) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java b/impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java deleted file mode 100644 index cb09e0ec1c..0000000000 --- a/impl/src/test/java/org/ehcache/impl/internal/classes/commonslang/JavaVersionTest.java +++ /dev/null @@ -1,62 +0,0 @@ -package org.ehcache.impl.internal.classes.commonslang; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.*; - -/** - * @author Henri Tremblay - */ -public class JavaVersionTest { - - private String specification; - - @Before - public void before() { - specification = System.getProperty("java.specification.version"); - System.setProperty("java.specification.version", "20"); - } - - @After - public void after() { - System.setProperty("java.specification.version", specification); - } - - @Test - public void javaRecent() { - assertThat(JavaVersion.JAVA_RECENT.toString()).isEqualTo("20.0"); - } - - @Test - public void getJavaVersion() { - assertThat(JavaVersion.getJavaVersion(null)).isNull(); - assertThat(JavaVersion.getJavaVersion("0.9")).isEqualTo(JavaVersion.JAVA_0_9); - assertThat(JavaVersion.getJavaVersion("1.1")).isEqualTo(JavaVersion.JAVA_1_1); - assertThat(JavaVersion.getJavaVersion("1.2")).isEqualTo(JavaVersion.JAVA_1_2); - assertThat(JavaVersion.getJavaVersion("1.3")).isEqualTo(JavaVersion.JAVA_1_3); - assertThat(JavaVersion.getJavaVersion("1.4")).isEqualTo(JavaVersion.JAVA_1_4); - assertThat(JavaVersion.getJavaVersion("1.5")).isEqualTo(JavaVersion.JAVA_1_5); - assertThat(JavaVersion.getJavaVersion("1.6")).isEqualTo(JavaVersion.JAVA_1_6); - assertThat(JavaVersion.getJavaVersion("1.7")).isEqualTo(JavaVersion.JAVA_1_7); - assertThat(JavaVersion.getJavaVersion("1.8")).isEqualTo(JavaVersion.JAVA_1_8); - assertThat(JavaVersion.getJavaVersion("9")).isEqualTo(JavaVersion.JAVA_9); - assertThat(JavaVersion.getJavaVersion("10")).isEqualTo(JavaVersion.JAVA_RECENT); - } - - @Test - public void atLeast_true() { - assertThat(JavaVersion.JAVA_1_8.atLeast(JavaVersion.JAVA_1_7)).isTrue(); - assertThat(JavaVersion.JAVA_9.atLeast(JavaVersion.JAVA_1_8)).isTrue(); - assertThat(JavaVersion.JAVA_9.atLeast(JavaVersion.JAVA_9)).isTrue(); - assertThat(JavaVersion.getJavaVersion("10").atLeast(JavaVersion.JAVA_9)).isTrue(); - } - - @Test - public void atLeast_false() { - assertThat(JavaVersion.JAVA_1_7.atLeast(JavaVersion.JAVA_1_8)).isFalse(); - assertThat(JavaVersion.JAVA_1_8.atLeast(JavaVersion.JAVA_9)).isFalse(); - assertThat(JavaVersion.JAVA_9.atLeast(JavaVersion.getJavaVersion("10"))).isFalse(); - } -} From 424f5af9c2fc0cdf8017c8843284b656e24bc27a Mon Sep 17 00:00:00 2001 From: Venkata Sairam Madduri Date: Wed, 3 Jan 2018 14:10:08 +0530 Subject: [PATCH 082/779] Upgrade tc-core and tc-platform versions --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index df52ccf164..f512918e87 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,9 +7,9 @@ slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre8 +terracottaPlatformVersion = 5.4.0-pre9 terracottaApisVersion = 1.4.0-pre8 -terracottaCoreVersion = 5.4.0-pre14 +terracottaCoreVersion = 5.4.0-pre15 terracottaPassthroughTestingVersion = 1.4.0-pre9 # Test lib versions From 99fdff5cad7446a0571d2562cefd3ec0cf63b502 Mon Sep 17 00:00:00 2001 From: Venkata Sairam Madduri Date: Wed, 3 Jan 2018 16:21:33 +0530 Subject: [PATCH 083/779] Fix findbugs error in ClusteringServiceConfigurationParser.java --- .../config/xml/ClusteringServiceConfigurationParser.java | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java index f967887b96..40aa9e4ba0 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/config/xml/ClusteringServiceConfigurationParser.java @@ -155,6 +155,10 @@ public ServiceCreationConfiguration parseServiceCreationConfi */ serverConfig = processServerSideConfig(item); break; + default: + throw new XmlConfigurationException( + String.format("Unknown XML configuration element <%s> in <%s>", + item.getNodeName(), fragment.getTagName())); } } } From 1853e8b03c3db48379cb3d3fb8e17d88917f58a3 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 27 Dec 2017 16:25:13 -0500 Subject: [PATCH 084/779] ValueSupplier can be replaced by a simple Supplier --- .../ehcache/jsr107/EhcacheExpiryWrapper.java | 6 +- .../jsr107/ExpiryPolicyToEhcacheExpiry.java | 6 +- ...che107ConfigurationIntegrationDocTest.java | 5 +- .../jsr107/ConfigurationMergerTest.java | 5 +- .../java/org/ehcache/jsr107/UnwrapTest.java | 4 +- .../main/java/org/ehcache/ValueSupplier.java | 4 + .../java/org/ehcache/expiry/ExpiryPolicy.java | 16 ++- .../internal/store/ClusteredValueHolder.java | 2 +- .../internal/store/ClusteredStoreTest.java | 22 ++-- .../ExpiryChainResolverExpiryTest.java | 23 ++-- .../org/ehcache/internal/TestExpiries.java | 14 +-- .../store/StoreBulkComputeIfAbsentTest.java | 6 +- .../internal/store/StoreBulkComputeTest.java | 2 +- .../store/StoreComputeIfAbsentTest.java | 6 +- .../internal/store/StoreComputeTest.java | 12 +- .../store/StoreEvictionEventListenerTest.java | 2 +- .../store/StoreExpiryEventListenerTest.java | 4 +- .../ehcache/internal/store/StoreGetTest.java | 4 +- .../internal/store/StoreIteratorNextTest.java | 2 +- .../internal/store/StoreIteratorTest.java | 2 +- .../internal/store/StorePutIfAbsentTest.java | 4 +- .../store/StoreReplaceKeyValueTest.java | 4 +- .../store/StoreReplaceKeyValueValueTest.java | 4 +- .../store/StoreValueHolderValueTest.java | 4 +- ...horitativeTierComputeIfAbsentAndFault.java | 4 +- .../tier/AuthoritativeTierGetAndFault.java | 4 +- .../internal/tier/CachingTierClear.java | 6 +- .../tier/CachingTierGetOrComputeIfAbsent.java | 8 +- .../internal/tier/CachingTierInvalidate.java | 4 +- .../internal/tier/CachingTierRemove.java | 6 +- .../main/java/org/ehcache/core/Ehcache.java | 6 +- .../java/org/ehcache/core/EhcacheBase.java | 9 +- .../ehcache/core/EhcacheWithLoaderWriter.java | 6 +- .../java/org/ehcache/core/SpecIterator.java | 2 +- .../org/ehcache/core/config/ExpiryUtils.java | 18 +-- .../core/events/NullStoreEventDispatcher.java | 11 +- .../ehcache/core/events/StoreEventSink.java | 10 +- .../core/internal/util/ValueSuppliers.java | 3 + .../core/spi/store/AbstractValueHolder.java | 2 +- .../org/ehcache/core/spi/store/Store.java | 3 +- .../test/java/org/ehcache/core/CacheTest.java | 10 +- .../ehcache/core/EhcacheBasicCrudBase.java | 18 +-- .../core/EhcacheBasicIteratorTest.java | 10 +- .../ehcache/core/EhcacheBulkMethodsTest.java | 2 +- .../ehcache/core/EhcacheLoaderWriterTest.java | 5 +- .../spi/store/AbstractValueHolderTest.java | 32 ++--- .../java/org/ehcache/core/util/Matchers.java | 13 +- .../config/builders/ExpiryPolicyBuilder.java | 6 +- .../events/AbstractStoreEventDispatcher.java | 10 +- .../FudgingInvocationScopedEventSink.java | 4 +- .../events/InvocationScopedEventSink.java | 18 +-- .../store/basic/EmptyValueHolder.java | 2 +- .../impl/internal/store/heap/OnHeapStore.java | 19 ++- .../heap/holders/CopiedOnHeapValueHolder.java | 2 +- .../holders/SerializedOnHeapValueHolder.java | 4 +- .../store/offheap/AbstractOffHeapStore.java | 15 ++- .../offheap/BasicOffHeapValueHolder.java | 2 +- .../offheap/BinaryOffHeapValueHolder.java | 2 +- .../store/offheap/LazyOffHeapValueHolder.java | 2 +- .../store/offheap/OffHeapValueHolder.java | 4 +- .../OffHeapValueHolderPortability.java | 2 +- .../test/java/org/ehcache/docs/Ehcache3.java | 8 +- .../java/org/ehcache/docs/GettingStarted.java | 12 +- .../FudgingInvocationScopedEventSinkTest.java | 32 +++-- .../events/InvocationScopedEventSinkTest.java | 8 +- .../ScopedStoreEventDispatcherTest.java | 4 +- .../events/TestStoreEventDispatcher.java | 26 ++-- .../store/heap/BaseOnHeapStoreTest.java | 82 ++++++------- .../heap/OnHeapStoreBulkMethodsTest.java | 81 ++++++------ .../store/heap/OnHeapStoreByValueTest.java | 6 +- .../store/heap/OnHeapStoreEvictionTest.java | 6 +- .../store/heap/OnHeapStoreKeyCopierTest.java | 6 +- .../heap/OnHeapStoreValueCopierTest.java | 40 +++--- .../bytesized/OnHeapStoreBulkMethodsTest.java | 14 +-- .../heap/bytesized/OversizeMappingTest.java | 2 +- .../holders/CopiedOnHeapValueHolderTest.java | 4 +- .../SerializedOnHeapValueHolderTest.java | 18 +-- .../offheap/AbstractOffHeapStoreTest.java | 43 ++++--- .../offheap/BasicOffHeapValueHolderTest.java | 2 +- .../offheap/BinaryOffHeapValueHolderTest.java | 2 +- .../offheap/LazyOffHeapValueHolderTest.java | 2 +- .../store/tiering/TieredStoreMutatorTest.java | 6 +- .../store/tiering/TieredStoreSPITest.java | 2 +- .../store/tiering/TieredStoreTest.java | 37 +++--- .../tiering/TieredStoreWith3TiersSPITest.java | 2 +- .../ehcache/impl/internal/util/Matchers.java | 28 ++--- .../internal/SoftLockValueCombinedCopier.java | 4 +- .../transactions/xa/internal/XAStore.java | 46 ++++--- .../xa/internal/XATransactionContext.java | 6 +- .../xa/internal/XAValueHolder.java | 4 +- .../transactions/xa/internal/XAStoreTest.java | 116 +++++++++--------- .../xa/internal/XATransactionContextTest.java | 36 +++--- .../xa/internal/XAValueHolderTest.java | 2 +- .../test/java/com/pany/ehcache/MyExpiry.java | 8 +- 94 files changed, 557 insertions(+), 585 deletions(-) diff --git a/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java b/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java index 1d2b92f398..1ee32df8c5 100644 --- a/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java +++ b/107/src/main/java/org/ehcache/jsr107/EhcacheExpiryWrapper.java @@ -15,10 +15,10 @@ */ package org.ehcache.jsr107; -import org.ehcache.ValueSupplier; import org.ehcache.expiry.ExpiryPolicy; import java.time.Duration; +import java.util.function.Supplier; /** * EhcacheExpiryWrapper @@ -37,12 +37,12 @@ public Duration getExpiryForCreation(K key, V value) { } @Override - public Duration getExpiryForAccess(K key, ValueSupplier value) { + public Duration getExpiryForAccess(K key, Supplier value) { return wrappedExpiry.getExpiryForAccess(key, value); } @Override - public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { return wrappedExpiry.getExpiryForUpdate(key, oldValue, newValue); } } diff --git a/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java b/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java index 740161bfe9..55e9eb9e8a 100644 --- a/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java +++ b/107/src/main/java/org/ehcache/jsr107/ExpiryPolicyToEhcacheExpiry.java @@ -15,11 +15,11 @@ */ package org.ehcache.jsr107; -import org.ehcache.ValueSupplier; import org.ehcache.core.config.ExpiryUtils; import java.io.Closeable; import java.io.IOException; +import java.util.function.Supplier; import javax.cache.expiry.Duration; import javax.cache.expiry.ExpiryPolicy; @@ -43,7 +43,7 @@ public java.time.Duration getExpiryForCreation(K key, V value) { } @Override - public java.time.Duration getExpiryForAccess(K key, ValueSupplier value) { + public java.time.Duration getExpiryForAccess(K key, Supplier value) { if (isShortCircuitAccessCalls()) { return null; } @@ -60,7 +60,7 @@ public java.time.Duration getExpiryForAccess(K key, ValueSupplier v } @Override - public java.time.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public java.time.Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { try { Duration duration = expiryPolicy.getExpiryForUpdate(); if (duration == null) { diff --git a/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java b/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java index a00c93186d..d54c7ae2b7 100644 --- a/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java +++ b/107/src/test/java/org/ehcache/docs/EhCache107ConfigurationIntegrationDocTest.java @@ -22,7 +22,6 @@ import org.ehcache.config.ResourceType; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.core.config.DefaultConfiguration; -import org.ehcache.core.internal.util.ValueSuppliers; import org.ehcache.impl.config.persistence.DefaultPersistenceConfiguration; import org.ehcache.jsr107.Eh107Configuration; import org.ehcache.jsr107.EhcacheCachingProvider; @@ -131,9 +130,9 @@ public void testGettingToEhcacheConfiguration() { assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForCreation(random.nextLong(), Long.toOctalString(random.nextLong())), equalTo(org.ehcache.expiry.ExpiryPolicy.INFINITE)); assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForAccess(random.nextLong(), - ValueSuppliers.supplierOf(Long.toOctalString(random.nextLong()))), nullValue()); + () -> Long.toOctalString(random.nextLong())), nullValue()); assertThat(runtimeConfiguration.getExpiryPolicy().getExpiryForUpdate(random.nextLong(), - ValueSuppliers.supplierOf(Long.toOctalString(random.nextLong())), Long.toOctalString(random.nextLong())), nullValue()); + () -> Long.toOctalString(random.nextLong()), Long.toOctalString(random.nextLong())), nullValue()); } @Test diff --git a/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java b/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java index 9f091a4535..fcd51cf393 100644 --- a/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java +++ b/107/src/test/java/org/ehcache/jsr107/ConfigurationMergerTest.java @@ -51,7 +51,6 @@ import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; @@ -175,8 +174,8 @@ public void jsr107ExpiryGetsOverriddenByTemplate() throws Exception { assertThat(factory.called, is(false)); Eh107Expiry expiryPolicy = configHolder.cacheResources.getExpiryPolicy(); org.ehcache.expiry.ExpiryPolicy expiry = configHolder.cacheConfiguration.getExpiryPolicy(); - assertThat(expiryPolicy.getExpiryForAccess(42, supplierOf("Yay")), is(expiry.getExpiryForAccess(42, supplierOf("Yay")))); - assertThat(expiryPolicy.getExpiryForUpdate(42, supplierOf("Yay"), "Lala"), is(expiry.getExpiryForUpdate(42, supplierOf("Yay"), "Lala"))); + assertThat(expiryPolicy.getExpiryForAccess(42, () -> "Yay"), is(expiry.getExpiryForAccess(42, () -> "Yay"))); + assertThat(expiryPolicy.getExpiryForUpdate(42, () -> "Yay", "Lala"), is(expiry.getExpiryForUpdate(42, () -> "Yay", "Lala"))); assertThat(expiryPolicy.getExpiryForCreation(42, "Yay"), is(expiry.getExpiryForCreation(42, "Yay"))); } diff --git a/107/src/test/java/org/ehcache/jsr107/UnwrapTest.java b/107/src/test/java/org/ehcache/jsr107/UnwrapTest.java index f9926e51c5..e89a692516 100644 --- a/107/src/test/java/org/ehcache/jsr107/UnwrapTest.java +++ b/107/src/test/java/org/ehcache/jsr107/UnwrapTest.java @@ -77,7 +77,6 @@ public void testCacheEntryEventUnwrap() { assertThat(cacheEntryEvent.unwrap(cacheEntryEvent.getClass()), is(instanceOf(Eh107CacheEntryEvent.NormalEvent.class))); } - @SuppressWarnings("unchecked") private class EhEvent implements CacheEvent { @Override public org.ehcache.event.EventType getType() { @@ -99,8 +98,9 @@ public String getOldValue() { throw new UnsupportedOperationException("Implement me!"); } + @SuppressWarnings("deprecation") @Override - public org.ehcache.Cache getSource() { + public org.ehcache.Cache getSource() { throw new UnsupportedOperationException("Implement me!"); } } diff --git a/api/src/main/java/org/ehcache/ValueSupplier.java b/api/src/main/java/org/ehcache/ValueSupplier.java index 65a8a4b4bb..505813e4cc 100644 --- a/api/src/main/java/org/ehcache/ValueSupplier.java +++ b/api/src/main/java/org/ehcache/ValueSupplier.java @@ -22,7 +22,11 @@ * This indicates that the value needs to be computed before it can be retrieved, such as deserialization. * * @param the value type + * + * @deprecated Now using {@code Supplier} for {@link org.ehcache.expiry.ExpiryPolicy} */ +@Deprecated +@FunctionalInterface public interface ValueSupplier { /** diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java index 4c5557584c..907dd70afd 100644 --- a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java +++ b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java @@ -16,24 +16,22 @@ package org.ehcache.expiry; -import org.ehcache.ValueSupplier; - import java.time.Duration; +import java.util.function.Supplier; /** * A policy object that governs expiration for mappings in a {@link org.ehcache.Cache Cache}. *

- * Previous values are not accessible directly but are rather available through a {@link ValueSupplier value supplier} + * Previous values are not accessible directly but are rather available through a value {@code Supplier} * to indicate that access can require computation (such as deserialization). *

* {@link Duration#isNegative() Negative duration} are not supported, expiry policy implementation returning such a * duration will result in immediate expiry, as if the duration was {@link Duration#ZERO zero}. *

* NOTE: Some cache configurations (eg. caches with eventual consistency) may use local (ie. non-consistent) state - * to decide whether to call {@link #getExpiryForUpdate(Object, ValueSupplier, Object)} vs. + * to decide whether to call {@link #getExpiryForUpdate(Object, Supplier, Object)} vs. * {@link #getExpiryForCreation(Object, Object)}. For these cache configurations it is advised to return the same * value for both of these methods - *

* * @param the key type for the cache * @param the value type for the cache @@ -56,12 +54,12 @@ public Duration getExpiryForCreation(Object key, Object value) { } @Override - public Duration getExpiryForAccess(Object key, ValueSupplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { return null; } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + public Duration getExpiryForUpdate(Object key, Supplier oldValue, Object newValue) { return null; } }; @@ -93,7 +91,7 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object * @param value a value supplier for the accessed entry * @return an expiration {@code Duration}, {@code null} means unchanged */ - Duration getExpiryForAccess(K key, ValueSupplier value); + Duration getExpiryForAccess(K key, Supplier value); /** @@ -110,6 +108,6 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object * @param newValue the new value of the entry * @return an expiration {@code Duration}, {@code null} means unchanged */ - Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue); + Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue); } diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredValueHolder.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredValueHolder.java index f11db85e8b..37359949dc 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredValueHolder.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredValueHolder.java @@ -44,7 +44,7 @@ protected TimeUnit nativeTimeUnit() { } @Override - public V value() { + public V get() { return value; } } diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java index b7e041a94b..99f908cc85 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java @@ -139,7 +139,7 @@ public void testGet() throws Exception { assertThat(store.get(1L), nullValue()); validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.MISS)); store.put(1L, "one"); - assertThat(store.get(1L).value(), is("one")); + assertThat(store.get(1L).get(), is("one")); validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.MISS, StoreOperationOutcomes.GetOutcome.HIT)); } @@ -318,7 +318,7 @@ public void testClearTimeout() throws Exception { public void testPutIfAbsent() throws Exception { assertThat(store.putIfAbsent(1L, "one"), nullValue()); validateStats(store, EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT)); - assertThat(store.putIfAbsent(1L, "another one").value(), is("one")); + assertThat(store.putIfAbsent(1L, "another one").get(), is("one")); validateStats(store, EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT, StoreOperationOutcomes.PutIfAbsentOutcome.HIT)); } @@ -387,7 +387,7 @@ public void testReplace() throws Exception { assertThat(store.replace(1L, "one"), nullValue()); validateStats(store, EnumSet.of(StoreOperationOutcomes.ReplaceOutcome.MISS)); store.put(1L, "one"); - assertThat(store.replace(1L, "another one").value(), is("one")); + assertThat(store.replace(1L, "another one").get(), is("one")); validateStats(store, EnumSet.of(StoreOperationOutcomes.ReplaceOutcome.MISS, StoreOperationOutcomes.ReplaceOutcome.REPLACED)); } @@ -461,10 +461,10 @@ public void testBulkComputePutAll() throws Exception { Ehcache.PutAllFunction putAllFunction = new Ehcache.PutAllFunction<>(null, map, null); Map> valueHolderMap = store.bulkCompute(new HashSet<>(Arrays.asList(1L, 2L)), putAllFunction); - assertThat(valueHolderMap.get(1L).value(), is(map.get(1L))); - assertThat(store.get(1L).value(), is(map.get(1L))); - assertThat(valueHolderMap.get(2L).value(), is(map.get(2L))); - assertThat(store.get(2L).value(), is(map.get(2L))); + assertThat(valueHolderMap.get(1L).get(), is(map.get(1L))); + assertThat(store.get(1L).get(), is(map.get(1L))); + assertThat(valueHolderMap.get(2L).get(), is(map.get(2L))); + assertThat(store.get(2L).get(), is(map.get(2L))); assertThat(putAllFunction.getActualPutCount().get(), is(2)); validateStats(store, EnumSet.of(StoreOperationOutcomes.PutOutcome.PUT)); //outcome of the initial store put } @@ -501,10 +501,10 @@ public void testBulkComputeIfAbsentGetAll() throws Exception { Ehcache.GetAllFunction getAllAllFunction = new Ehcache.GetAllFunction<>(); Map> valueHolderMap = store.bulkComputeIfAbsent(new HashSet<>(Arrays.asList(1L, 2L)), getAllAllFunction); - assertThat(valueHolderMap.get(1L).value(), is("one")); - assertThat(store.get(1L).value(), is("one")); - assertThat(valueHolderMap.get(2L).value(), is("two")); - assertThat(store.get(2L).value(), is("two")); + assertThat(valueHolderMap.get(1L).get(), is("one")); + assertThat(store.get(1L).get(), is("one")); + assertThat(valueHolderMap.get(2L).get(), is("two")); + assertThat(store.get(2L).get(), is("two")); } @Test(expected = UnsupportedOperationException.class) diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java index ad45fd8be6..4fe0b0e9dc 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/operations/ExpiryChainResolverExpiryTest.java @@ -16,7 +16,6 @@ package org.ehcache.clustered.client.internal.store.operations; -import org.ehcache.ValueSupplier; import org.ehcache.clustered.client.TestTimeSource; import org.ehcache.clustered.client.internal.store.ChainBuilder; import org.ehcache.clustered.client.internal.store.ResolvedChain; @@ -75,9 +74,9 @@ public void testGetExpiryForAccessIsIgnored() { ResolvedChain resolvedChain = chainResolver.resolve(chain, 1L, timeSource.getTimeMillis()); - verify(expiry, times(0)).getExpiryForAccess(anyLong(), any(ValueSupplier.class)); + verify(expiry, times(0)).getExpiryForAccess(anyLong(), any()); verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); - verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString()); + verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(), anyString()); assertThat(resolvedChain.isCompacted(), is(true)); } @@ -103,7 +102,7 @@ public void testGetExpiryForCreationIsInvokedOnlyOnce() { InOrder inOrder = inOrder(expiry); inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); - inOrder.verify(expiry, times(3)).getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString()); + inOrder.verify(expiry, times(3)).getExpiryForUpdate(anyLong(), any(), anyString()); assertThat(resolvedChain.isCompacted(), is(true)); } @@ -126,7 +125,7 @@ public void testGetExpiryForCreationIsNotInvokedForReplacedChains() { ResolvedChain resolvedChain = chainResolver.resolve(chain, 1L, timeSource.getTimeMillis()); verify(expiry, times(0)).getExpiryForCreation(anyLong(), anyString()); - verify(expiry, times(3)).getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString()); + verify(expiry, times(3)).getExpiryForUpdate(anyLong(), any(), anyString()); assertThat(resolvedChain.isCompacted(), is(true)); } @@ -152,8 +151,8 @@ public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { InOrder inOrder = inOrder(expiry); - verify(expiry, times(0)).getExpiryForAccess(anyLong(), any(ValueSupplier.class)); - inOrder.verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString()); + verify(expiry, times(0)).getExpiryForAccess(anyLong(), any()); + inOrder.verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(), anyString()); inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); assertThat(resolvedChain.isCompacted(), is(true)); @@ -174,9 +173,9 @@ public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { inOrder = inOrder(expiry); - verify(expiry, times(0)).getExpiryForAccess(anyLong(), any(ValueSupplier.class)); + verify(expiry, times(0)).getExpiryForAccess(anyLong(), any()); inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); - inOrder.verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString()); + inOrder.verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(), anyString()); inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); assertThat(resolvedChain.isCompacted(), is(true)); @@ -207,7 +206,7 @@ public void testNullGetExpiryForUpdate() { ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenReturn(null); + when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenReturn(null); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "Replaced", -10L)); @@ -228,7 +227,7 @@ public void testGetExpiryForUpdateUpdatesExpirationTimeStamp() { ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenReturn(Duration.ofMillis(2L)); + when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenReturn(Duration.ofMillis(2L)); List> list = new ArrayList<>(); list.add(new PutOperation<>(1L, "Replaced", -10L)); @@ -249,7 +248,7 @@ public void testExpiryThrowsException() { ExpiryPolicy expiry = mock(ExpiryPolicy.class); ExpiryChainResolver chainResolver = new ExpiryChainResolver<>(codec, expiry); - when(expiry.getExpiryForUpdate(anyLong(), any(ValueSupplier.class), anyString())).thenThrow(new RuntimeException("Test Update Expiry")); + when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenThrow(new RuntimeException("Test Update Expiry")); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenThrow(new RuntimeException("Test Create Expiry")); List> list = new ArrayList<>(); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java b/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java index 1ac7fba865..a4674aa5e8 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/TestExpiries.java @@ -16,10 +16,10 @@ package org.ehcache.internal; -import org.ehcache.ValueSupplier; import org.ehcache.expiry.ExpiryPolicy; import java.time.Duration; +import java.util.function.Supplier; /** * TestExpiries @@ -34,12 +34,12 @@ public Duration getExpiryForCreation(K key, V value) { } @Override - public Duration getExpiryForAccess(K key, ValueSupplier value) { + public Duration getExpiryForAccess(K key, Supplier value) { return duration; } @Override - public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { return duration; } }; @@ -53,12 +53,12 @@ public Duration getExpiryForCreation(K key, V value) { } @Override - public Duration getExpiryForAccess(K key, ValueSupplier value) { + public Duration getExpiryForAccess(K key, Supplier value) { return null; } @Override - public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { return duration; } }; @@ -72,12 +72,12 @@ public Duration getExpiryForCreation(K key, V value) { } @Override - public Duration getExpiryForAccess(K key, ValueSupplier value) { + public Duration getExpiryForAccess(K key, Supplier value) { return access; } @Override - public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { return update; } }; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java index b7bc1a8198..4b1b6f1607 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java @@ -103,7 +103,7 @@ public void missingIterableEntriesAreIgnoredByTheStore() throws Exception { kvStore.bulkComputeIfAbsent(inputKeys, entries -> emptySet()); for (Map.Entry mappedEntry : mappedEntries.entrySet()) { - assertThat(kvStore.get(mappedEntry.getKey()).value(), is(mappedEntry.getValue())); + assertThat(kvStore.get(mappedEntry.getKey()).get(), is(mappedEntry.getValue())); } } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); @@ -137,7 +137,7 @@ public void mappingIsSameInTheStoreForEntriesReturnedWithDifferentValueFromMappi }); for (Map.Entry mappedEntry : mappedEntries.entrySet()) { - assertThat(kvStore.get(mappedEntry.getKey()).value(), is(mappedEntry.getValue())); + assertThat(kvStore.get(mappedEntry.getKey()).get(), is(mappedEntry.getValue())); } } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); @@ -192,7 +192,7 @@ public void computeValuesForEveryKeyUsingAMappingFunction() throws Exception { }); for (Map.Entry entry : computedEntries.entrySet()) { - assertThat(kvStore.get(entry.getKey()).value(), is(entry.getValue())); + assertThat(kvStore.get(entry.getKey()).get(), is(entry.getValue())); } } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java index 4156a33b8e..16959921f2 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java @@ -204,7 +204,7 @@ public void computeValuesForEveryKeyUsingARemappingFunction() throws Exception { }); for (K inputKey : inputKeys) { - assertThat(kvStore.get(inputKey).value(), is(computedEntries.get(inputKey))); + assertThat(kvStore.get(inputKey).get(), is(computedEntries.get(inputKey))); } } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java index b12916a0dc..f005eb5343 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java @@ -128,7 +128,7 @@ public void testComputePutsValueInStoreWhenKeyIsAbsent() throws Exception { assertThat(kvStore.get(key), nullValue()); try { kvStore.computeIfAbsent(key, keyParam -> value); - assertThat(kvStore.get(key).value(), is(value)); + assertThat(kvStore.get(key).get(), is(value)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -151,7 +151,7 @@ public void testFunctionNotInvokedWhenPresent() throws Exception { } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } - assertThat(kvStore.get(key).value(), is(value)); + assertThat(kvStore.get(key).get(), is(value)); } @SPITest @@ -212,7 +212,7 @@ public void testComputeIfAbsentValuePresentExpiresOnAccess() throws LegalSPITest fail("Should not be invoked"); return newValue; }); - assertThat(result.value(), is(value)); + assertThat(result.get(), is(value)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java index fcd632d07f..5a35c180f2 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java @@ -125,7 +125,7 @@ public void testComputePutsValueInStore() throws Exception { try { kvStore.compute(key, (keyParam, oldValue) -> value); - assertThat(kvStore.get(key).value(), is(value)); + assertThat(kvStore.get(key).get(), is(value)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -144,7 +144,7 @@ public void testOverwriteExitingValue() throws Exception { try { kvStore.put(key, value); kvStore.compute(key, (keyParam, oldValue) -> value2); - assertThat(kvStore.get(key).value(), is(value2)); + assertThat(kvStore.get(key).get(), is(value2)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -177,7 +177,7 @@ public void testException() throws Exception { try { kvStore.put(key, value); - assertThat(kvStore.get(key).value(), is(value)); + assertThat(kvStore.get(key).get(), is(value)); kvStore.compute(key, (keyParam, oldValue) -> { throw re; @@ -188,7 +188,7 @@ public void testException() throws Exception { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } - assertThat(kvStore.get(key).value(), is(value)); + assertThat(kvStore.get(key).get(), is(value)); } @SPITest @@ -203,7 +203,7 @@ public void testComputeExpiresOnAccess() throws Exception { kvStore.put(key, value); Store.ValueHolder result = kvStore.compute(key, (k, v) -> v, () -> false); - assertThat(result.value(), is(value)); + assertThat(result.get(), is(value)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -222,7 +222,7 @@ public void testComputeExpiresOnUpdate() throws Exception { kvStore.put(key, value); Store.ValueHolder result = kvStore.compute(key, (k, v) -> newValue, () -> false); - assertThat(result.value(), is(newValue)); + assertThat(result.get(), is(newValue)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java index 02da9d3dd1..a418d58ff5 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java @@ -89,7 +89,7 @@ public void testReplaceTwoArgsOnEviction() throws Exception { kvStore.put(k2, v2); verifyListenerInteractions(listener); kvStore.replace(getOnlyKey(kvStore.iterator()), v3); - assertThat(kvStore.get(getOnlyKey(kvStore.iterator())).value(), is(v3)); + assertThat(kvStore.get(getOnlyKey(kvStore.iterator())).get(), is(v3)); } @SPITest diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java index 7ad67a3414..e84765df24 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreExpiryEventListenerTest.java @@ -137,7 +137,7 @@ public void testComputeOnExpiration() throws Exception { kvStore.put(k, v); StoreEventListener listener = addListener(kvStore); timeSource.advanceTime(1); - assertThat(kvStore.compute(k, (mappedKey, mappedValue) -> v2).value(), is(v2)); + assertThat(kvStore.compute(k, (mappedKey, mappedValue) -> v2).get(), is(v2)); verifyListenerInteractions(listener); } @@ -147,7 +147,7 @@ public void testComputeIfAbsentOnExpiration() throws Exception { StoreEventListener listener = addListener(kvStore); timeSource.advanceTime(1); - assertThat(kvStore.computeIfAbsent(k, mappedKey -> v2).value(), is(v2)); + assertThat(kvStore.computeIfAbsent(k, mappedKey -> v2).get(), is(v2)); verifyListenerInteractions(listener); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java index 2749193376..af2b044204 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java @@ -108,7 +108,7 @@ public void existingKeyMappedInStoreReturnsCorrectValueHolder() kvStore.put(key, value); try { - assertThat(kvStore.get(key).value(), is(equalTo(value))); + assertThat(kvStore.get(key).get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -161,7 +161,7 @@ public void testGetExpiresOnAccess() throws LegalSPITesterException { try { kvStore.put(key, value); - assertThat(kvStore.get(key).value(), is(value)); + assertThat(kvStore.get(key).get(), is(value)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java index 322da98667..71221ff927 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java @@ -66,7 +66,7 @@ public void nextReturnsNextElement() try { Cache.Entry> entry = iterator.next(); assertThat(entry.getKey(), is(equalTo(key))); - assertThat(entry.getValue().value(), is(equalTo(value))); + assertThat(entry.getValue().get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java index 3fabd91235..649dd356f7 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java @@ -80,7 +80,7 @@ public void iterableContainsValuesInAnyOrder() while (iterator.hasNext()) { Cache.Entry> nextEntry = iterator.next(); keys.add(nextEntry.getKey()); - values.add(nextEntry.getValue().value()); + values.add(nextEntry.getValue().get()); } assertThat(keys, containsInAnyOrder(equalTo(key1), equalTo(key2), equalTo(key3))); assertThat(values, containsInAnyOrder(equalTo(value1), equalTo(value2), equalTo(value3))); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java index b22c512085..384e3d5215 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java @@ -94,7 +94,7 @@ public void doesntMapKeyToValueWhenMappingExists() V updatedValue = factory.createValue(2); try { - assertThat(kvStore.putIfAbsent(key, updatedValue).value(), is(equalTo(value))); + assertThat(kvStore.putIfAbsent(key, updatedValue).get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -187,7 +187,7 @@ public void testPutIfAbsentValuePresentExpiresOnAccess() throws LegalSPITesterEx try { kvStore.put(key, value); - assertThat(kvStore.putIfAbsent(key, newValue).value(), is(value)); + assertThat(kvStore.putIfAbsent(key, newValue).get(), is(value)); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java index 524c086a1f..112d94be2a 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java @@ -75,7 +75,7 @@ public void replaceKeyAndValue() throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } - assertThat(kvStore.get(key).value(), is(equalTo(newValue))); + assertThat(kvStore.get(key).get(), is(equalTo(newValue))); } @SPITest @@ -91,7 +91,7 @@ public void replaceReturnsOldValue() V newValue = factory.createValue(2); try { - assertThat(kvStore.replace(key, newValue).value(), is(equalTo(originalValue))); + assertThat(kvStore.replace(key, newValue).get(), is(equalTo(originalValue))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java index 1ba79839f9..a1c2c60ddc 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java @@ -77,7 +77,7 @@ public void replaceCorrectKeyAndValue() throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } - assertThat(kvStore.get(key).value(), is(equalTo(newValue))); + assertThat(kvStore.get(key).get(), is(equalTo(newValue))); } @SPITest @@ -99,7 +99,7 @@ public void replaceCorrectKeyAndWrongValue() throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } - assertThat(kvStore.get(key).value(), is(not(equalTo(wrongValue)))); + assertThat(kvStore.get(key).get(), is(not(equalTo(wrongValue)))); } @SPITest diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreValueHolderValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreValueHolderValueTest.java index be69354a3f..ee0c59289d 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreValueHolderValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreValueHolderValueTest.java @@ -24,7 +24,7 @@ import static org.hamcrest.core.Is.is; /** - * Test the {@link Store.ValueHolder#value()} contract of the + * Test the {@link Store.ValueHolder#get(Object)} contract of the * {@link Store.ValueHolder Store.ValueHolder} interface. * * @author Aurelien Broszniowski @@ -43,7 +43,7 @@ public void valueIsHeldByValueHolder() Store.ValueHolder valueHolder = factory.newValueHolder(value); try { - assertThat(valueHolder.value(), is(equalTo(value))); + assertThat(valueHolder.get(), is(equalTo(value))); } catch (Exception e) { System.err.println("Warning, an exception is thrown due to the SPI test"); e.printStackTrace(); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java index d747cdc834..d0ff40933e 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java @@ -81,10 +81,10 @@ public void marksTheMappingAsNotEvictableAndComputeValue() throws LegalSPITester try { assertThat(tier.get(key), is(nullValue())); - assertThat(tier.computeIfAbsentAndFault(key, k -> factory.createValue(1L)).value(), is(equalTo(value))); + assertThat(tier.computeIfAbsentAndFault(key, k -> factory.createValue(1L)).get(), is(equalTo(value))); fillTierOverCapacity(tier, factory); - assertThat(tier.get(key).value(), is(equalTo(value))); + assertThat(tier.get(key).get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java index 07a05de242..5a02869a92 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java @@ -86,11 +86,11 @@ public void marksTheMappingAsNotEvictableAndReturnsValue() throws LegalSPITester try { tier.put(key, value); - assertThat(tier.getAndFault(key).value(), is(equalTo(value))); + assertThat(tier.getAndFault(key).get(), is(equalTo(value))); fillTierOverCapacity(tier, factory); - assertThat(tier.get(key).value(), is(equalTo(value))); + assertThat(tier.get(key).get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java index 05f61adb36..1dfdeba49a 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java @@ -66,7 +66,7 @@ public void removeMapping() throws LegalSPITesterException { V newValue= factory.createValue(2); final Store.ValueHolder originalValueHolder = mock(Store.ValueHolder.class); - when(originalValueHolder.value()).thenReturn(originalValue); + when(originalValueHolder.get()).thenReturn(originalValue); try { List keys = new ArrayList<>(); @@ -80,13 +80,13 @@ public void removeMapping() throws LegalSPITesterException { tier.clear(); final Store.ValueHolder newValueHolder = mock(Store.ValueHolder.class); - when(newValueHolder.value()).thenReturn(newValue); + when(newValueHolder.get()).thenReturn(newValue); for (K key : keys) { tier.invalidate(key); Store.ValueHolder newReturnedValueHolder = tier.getOrComputeIfAbsent(key, o -> newValueHolder); - assertThat(newReturnedValueHolder.value(), is(equalTo(newValueHolder.value()))); + assertThat(newReturnedValueHolder.get(), is(equalTo(newValueHolder.get()))); } } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java index 6464b91de9..ddc5b52ebf 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java @@ -64,14 +64,14 @@ public void returnTheValueHolderNotInTheCachingTier() throws LegalSPITesterExcep V value = factory.createValue(1); final Store.ValueHolder computedValueHolder = mock(Store.ValueHolder.class); - when(computedValueHolder.value()).thenReturn(value); + when(computedValueHolder.get()).thenReturn(value); tier = factory.newCachingTier(1L); try { Store.ValueHolder valueHolder = tier.getOrComputeIfAbsent(key, k -> computedValueHolder); - assertThat(valueHolder.value(), is(equalTo(value))); + assertThat(valueHolder.get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } @@ -83,7 +83,7 @@ public void returnTheValueHolderCurrentlyInTheCachingTier() throws LegalSPITeste K key = factory.createKey(1); V value = factory.createValue(1); final Store.ValueHolder computedValueHolder = mock(Store.ValueHolder.class); - when(computedValueHolder.value()).thenReturn(value); + when(computedValueHolder.get()).thenReturn(value); when(computedValueHolder.expirationTime(any(TimeUnit.class))).thenReturn(Store.ValueHolder.NO_EXPIRE); tier = factory.newCachingTier(); @@ -94,7 +94,7 @@ public void returnTheValueHolderCurrentlyInTheCachingTier() throws LegalSPITeste Store.ValueHolder valueHolder = tier.getOrComputeIfAbsent(key, k -> null); - assertThat(valueHolder.value(), is(equalTo(value))); + assertThat(valueHolder.get(), is(equalTo(value))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java index b6ca9df440..b55f142175 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java @@ -64,7 +64,7 @@ public void invalidateKey() throws LegalSPITesterException { // register invalidation listener final AtomicBoolean invalidated = new AtomicBoolean(false); tier.setInvalidationListener((key1, valueHolder) -> { - assertThat(valueHolder.value(), is(value)); + assertThat(valueHolder.get(), is(value)); invalidated.set(true); }); @@ -132,7 +132,7 @@ public void invalidateAll() throws LegalSPITesterException { private Store.ValueHolder wrap(final V value) { return new Store.ValueHolder() { @Override - public V value() { + public V get() { return value; } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java index 7da1abd7e5..9f57a95dbf 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java @@ -61,7 +61,7 @@ public void removeMapping() throws LegalSPITesterException { V newValue = factory.createValue(2); final Store.ValueHolder valueHolder = mock(Store.ValueHolder.class); - when(valueHolder.value()).thenReturn(originalValue); + when(valueHolder.get()).thenReturn(originalValue); tier = factory.newCachingTier(1L); @@ -71,10 +71,10 @@ public void removeMapping() throws LegalSPITesterException { tier.invalidate(key); final Store.ValueHolder newValueHolder = mock(Store.ValueHolder.class); - when(newValueHolder.value()).thenReturn(newValue); + when(newValueHolder.get()).thenReturn(newValue); Store.ValueHolder newReturnedValueHolder = tier.getOrComputeIfAbsent(key, o -> newValueHolder); - assertThat(newReturnedValueHolder.value(), is(equalTo(newValueHolder.value()))); + assertThat(newReturnedValueHolder.get(), is(equalTo(newValueHolder.get()))); } catch (StoreAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index 7eb2668abc..f0af8fd4e9 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -159,7 +159,7 @@ protected Map getAllInternal(Set keys, boolean includeNulls) for (Map.Entry> entry : computedMap.entrySet()) { keyCount++; if (entry.getValue() != null) { - result.put(entry.getKey(), entry.getValue().value()); + result.put(entry.getKey(), entry.getValue().get()); hits++; } else if (includeNulls) { result.put(entry.getKey(), null); @@ -268,7 +268,7 @@ public V putIfAbsent(final K key, final V value) { return null; } else { putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return inCache.value(); + return inCache.get(); } } catch (StoreAccessException e) { try { @@ -331,7 +331,7 @@ public V replace(final K key, final V value) { } else { replaceObserver.end(ReplaceOutcome.MISS_NOT_PRESENT); } - return old == null ? null : old.value(); + return old == null ? null : old.get(); } catch (StoreAccessException e) { try { return resilienceStrategy.replaceFailure(key, value, e); diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index c9ede1eceb..0862d6de16 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -58,7 +58,6 @@ import java.util.function.Function; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.terracotta.statistics.StatisticBuilder.operation; /** @@ -158,7 +157,7 @@ protected V getNoLoader(K key) { return null; } else { getObserver.end(GetOutcome.HIT); - return valueHolder.value(); + return valueHolder.get(); } } catch (StoreAccessException e) { try { @@ -243,7 +242,7 @@ protected static boolean newValueAlreadyExpired(Logger logger, ExpiryPoli if (oldValue == null) { duration = expiry.getExpiryForCreation(key, newValue); } else { - duration = expiry.getExpiryForUpdate(key, supplierOf(oldValue), newValue); + duration = expiry.getExpiryForUpdate(key, () -> oldValue, newValue); } } catch (RuntimeException re) { logger.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); @@ -476,7 +475,7 @@ public void remove() { if (current == null) { throw new IllegalStateException("No current element"); } - EhcacheBase.this.remove(current.getKey(), current.getValue().value()); + EhcacheBase.this.remove(current.getKey(), current.getValue().get()); current = null; } } @@ -495,7 +494,7 @@ public K getKey() { @Override public V getValue() { - return storeEntry.getValue().value(); + return storeEntry.getValue().get(); } } diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index b9e866fce4..af9e9c02bd 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -142,7 +142,7 @@ public V get(final K key) throws CacheLoadingException { return null; } else { getObserver.end(GetOutcome.HIT); - return valueHolder.value(); + return valueHolder.get(); } } catch (StoreAccessException e) { try { @@ -288,7 +288,7 @@ protected Map getAllInternal(Set keys, boolean includeNulls) for (Map.Entry> entry : computedMap.entrySet()) { keyCount++; if (entry.getValue() != null) { - result.put(entry.getKey(), entry.getValue().value()); + result.put(entry.getKey(), entry.getValue().get()); hits++; } else if (includeNulls && failures.isEmpty()) { result.put(entry.getKey(), null); @@ -602,7 +602,7 @@ public V putIfAbsent(final K key, final V value) throws CacheWritingException { return null; } else { putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return inCache.value(); + return inCache.get(); } } catch (StoreAccessException e) { try { diff --git a/core/src/main/java/org/ehcache/core/SpecIterator.java b/core/src/main/java/org/ehcache/core/SpecIterator.java index b772a6fa88..6d198293a5 100644 --- a/core/src/main/java/org/ehcache/core/SpecIterator.java +++ b/core/src/main/java/org/ehcache/core/SpecIterator.java @@ -59,7 +59,7 @@ public Cache.Entry next() { current = next; - final V nextValue = nextValueHolder.value(); + final V nextValue = nextValueHolder.get(); return new Cache.Entry() { @Override public K getKey() { diff --git a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java index 7e76e3553c..1386fd7e1a 100644 --- a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java +++ b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java @@ -16,13 +16,13 @@ package org.ehcache.core.config; -import org.ehcache.ValueSupplier; import org.ehcache.expiry.ExpiryPolicy; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; /** * ExpiryUtils @@ -50,13 +50,13 @@ public org.ehcache.expiry.Duration getExpiryForCreation(K key, V value) { } @Override - public org.ehcache.expiry.Duration getExpiryForAccess(K key, ValueSupplier value) { - return convertDuration(expiryPolicy.getExpiryForAccess(key, value)); + public org.ehcache.expiry.Duration getExpiryForAccess(K key, org.ehcache.ValueSupplier value) { + return convertDuration(expiryPolicy.getExpiryForAccess(key, () -> value.value())); } @Override - public org.ehcache.expiry.Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { - return convertDuration(expiryPolicy.getExpiryForUpdate(key, oldValue, newValue)); + public org.ehcache.expiry.Duration getExpiryForUpdate(K key, org.ehcache.ValueSupplier oldValue, V newValue) { + return convertDuration(expiryPolicy.getExpiryForUpdate(key, () -> oldValue.value(), newValue)); } @Override @@ -114,14 +114,14 @@ public Duration getExpiryForCreation(K key, V value) { } @Override - public Duration getExpiryForAccess(K key, ValueSupplier value) { - org.ehcache.expiry.Duration duration = expiry.getExpiryForAccess(key, value); + public Duration getExpiryForAccess(K key, Supplier value) { + org.ehcache.expiry.Duration duration = expiry.getExpiryForAccess(key, () -> value.get()); return convertDuration(duration); } @Override - public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { - org.ehcache.expiry.Duration duration = expiry.getExpiryForUpdate(key, oldValue, newValue); + public Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { + org.ehcache.expiry.Duration duration = expiry.getExpiryForUpdate(key, () -> oldValue.get(), newValue); return convertDuration(duration); } diff --git a/core/src/main/java/org/ehcache/core/events/NullStoreEventDispatcher.java b/core/src/main/java/org/ehcache/core/events/NullStoreEventDispatcher.java index 8723d1b365..8bc80d7c4a 100644 --- a/core/src/main/java/org/ehcache/core/events/NullStoreEventDispatcher.java +++ b/core/src/main/java/org/ehcache/core/events/NullStoreEventDispatcher.java @@ -16,10 +16,11 @@ package org.ehcache.core.events; -import org.ehcache.ValueSupplier; import org.ehcache.core.spi.store.events.StoreEventFilter; import org.ehcache.core.spi.store.events.StoreEventListener; +import java.util.function.Supplier; + /** * NullStoreEventDispatcher */ @@ -31,12 +32,12 @@ public static StoreEventDispatcher nullStoreEventDispatcher() { private final StoreEventSink storeEventSink = new StoreEventSink() { @Override - public void evicted(K key, ValueSupplier value) { + public void evicted(K key, Supplier value) { // Do nothing } @Override - public void expired(K key, ValueSupplier value) { + public void expired(K key, Supplier value) { // Do nothing } @@ -46,12 +47,12 @@ public void created(K key, V value) { } @Override - public void updated(K key, ValueSupplier previousValue, V newValue) { + public void updated(K key, Supplier previousValue, V newValue) { // Do nothing } @Override - public void removed(K key, ValueSupplier removed) { + public void removed(K key, Supplier removed) { // Do nothing } }; diff --git a/core/src/main/java/org/ehcache/core/events/StoreEventSink.java b/core/src/main/java/org/ehcache/core/events/StoreEventSink.java index 4dbe7426ad..f817573a1b 100644 --- a/core/src/main/java/org/ehcache/core/events/StoreEventSink.java +++ b/core/src/main/java/org/ehcache/core/events/StoreEventSink.java @@ -16,7 +16,7 @@ package org.ehcache.core.events; -import org.ehcache.ValueSupplier; +import java.util.function.Supplier; /** * Interface on which {@link org.ehcache.core.spi.store.Store} operations are to record events. @@ -29,7 +29,7 @@ public interface StoreEventSink { * @param key removed key * @param value value supplier of removed value */ - void removed(K key, ValueSupplier value); + void removed(K key, Supplier value); /** * Indicates the mapping was updated. @@ -38,7 +38,7 @@ public interface StoreEventSink { * @param oldValue value supplier of old value * @param newValue the new value */ - void updated(K key, ValueSupplier oldValue, V newValue); + void updated(K key, Supplier oldValue, V newValue); /** * Indicates the mapping was expired. @@ -46,7 +46,7 @@ public interface StoreEventSink { * @param key the expired key * @param value value supplier of expired value */ - void expired(K key, ValueSupplier value); + void expired(K key, Supplier value); /** * Indicates a mapping was created. @@ -62,5 +62,5 @@ public interface StoreEventSink { * @param key the evicted key * @param value value supplier of evicted value */ - void evicted(K key, ValueSupplier value); + void evicted(K key, Supplier value); } diff --git a/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java b/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java index 1beeb2d5fe..0dad3efa24 100644 --- a/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java +++ b/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java @@ -20,7 +20,10 @@ /** * Utility for creating basic {@link ValueSupplier} instances + * + * @deprecated Now using {@code Supplier} for {@link org.ehcache.expiry.ExpiryPolicy} */ +@Deprecated public class ValueSuppliers { /** diff --git a/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java b/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java index 0d431929be..d258771e5e 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java +++ b/core/src/main/java/org/ehcache/core/spi/store/AbstractValueHolder.java @@ -177,6 +177,6 @@ public long getId() { @Override public String toString() { - return format("%s", value()); + return format("%s", get()); } } diff --git a/core/src/main/java/org/ehcache/core/spi/store/Store.java b/core/src/main/java/org/ehcache/core/spi/store/Store.java index 8765c9d351..cea0dccfa3 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/Store.java +++ b/core/src/main/java/org/ehcache/core/spi/store/Store.java @@ -17,7 +17,6 @@ package org.ehcache.core.spi.store; import org.ehcache.Cache; -import org.ehcache.ValueSupplier; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; @@ -461,7 +460,7 @@ public interface Store extends ConfigurationChangeSupport { * * @param the value type */ - interface ValueHolder extends ValueSupplier { + interface ValueHolder extends Supplier { /** * Constant value indicating no expiration - an eternal mapping. diff --git a/core/src/test/java/org/ehcache/core/CacheTest.java b/core/src/test/java/org/ehcache/core/CacheTest.java index 627b2ff688..3642bb2b91 100644 --- a/core/src/test/java/org/ehcache/core/CacheTest.java +++ b/core/src/test/java/org/ehcache/core/CacheTest.java @@ -226,7 +226,7 @@ public void testPutIfAbsent() throws StoreAccessException { } return new Store.ValueHolder() { @Override - public Object value() { + public Object get() { return existingValue.get(); } @@ -273,7 +273,7 @@ public long getId() { } return new Store.ValueHolder() { @Override - public Object value() { + public Object get() { return toReturn; } @@ -316,9 +316,9 @@ public long getId() { InternalCache ehcache = getCache(store); ehcache.init(); assertThat(ehcache.putIfAbsent("foo", value), nullValue()); - assertThat(ehcache.putIfAbsent("foo", "foo"), CoreMatchers.is(value)); - assertThat(ehcache.putIfAbsent("foo", "foobar"), CoreMatchers.is(value)); - assertThat(ehcache.putIfAbsent("foo", value), CoreMatchers.is(value)); + assertThat(ehcache.putIfAbsent("foo", "foo"), CoreMatchers.is(value)); + assertThat(ehcache.putIfAbsent("foo", "foobar"), CoreMatchers.is(value)); + assertThat(ehcache.putIfAbsent("foo", value), CoreMatchers.is(value)); } @Test diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java index 99baf09644..910548921a 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java @@ -258,7 +258,7 @@ protected static class FakeStore implements Store { private final Set failingKeys; public FakeStore(final Map entries) { - this(entries, Collections.emptySet()); + this(entries, Collections.emptySet()); } public FakeStore(final Map entries, final Set failingKeys) { @@ -282,7 +282,7 @@ public FakeStore(final Map entries, final Set failingKey protected Map getEntryMap() { final Map result = new HashMap<>(); for (final Map.Entry entry : this.entries.entrySet()) { - result.put(entry.getKey(), entry.getValue().value()); + result.put(entry.getKey(), entry.getValue().get()); } return Collections.unmodifiableMap(result); } @@ -338,7 +338,7 @@ public RemoveStatus remove(final String key, final String value) throws StoreAcc final ValueHolder currentValue = this.entries.get(key); if (currentValue == null) { return RemoveStatus.KEY_MISSING; - } else if (!currentValue.value().equals(value)) { + } else if (!currentValue.get().equals(value)) { return RemoveStatus.KEY_PRESENT; } this.entries.remove(key); @@ -362,7 +362,7 @@ public ReplaceStatus replace(final String key, final String oldValue, final Stri if (currentValue == null) { return ReplaceStatus.MISS_NOT_PRESENT; } - if (!currentValue.value().equals(oldValue)) { + if (!currentValue.get().equals(oldValue)) { return ReplaceStatus.MISS_PRESENT; } this.entries.put(key, new FakeValueHolder(newValue)); @@ -457,9 +457,9 @@ private FakeValueHolder computeInternal( final BiFunction mappingFunction, final Supplier replaceEqual) throws StoreAccessException { - String remappedValue = null; + String remappedValue; try { - remappedValue = mappingFunction.apply(key, (currentValue == null ? null : currentValue.value())); + remappedValue = mappingFunction.apply(key, (currentValue == null ? null : currentValue.get())); } catch (StorePassThroughException cpte) { Throwable cause = cpte.getCause(); if(cause instanceof RuntimeException) { @@ -508,7 +508,7 @@ public ValueHolder computeIfAbsent(final String key, final Function entries, final SetemptySet() + ? Collections.emptySet() : Collections.unmodifiableSet(new HashSet<>(failingKeys))); } diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java index 819a59d274..67be0b252a 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java @@ -63,7 +63,7 @@ public class EhcacheBasicIteratorTest extends EhcacheBasicCrudBase { */ @Test public void testIteratorEmptyStoreGet() throws Exception { - this.store = new FakeStore(Collections.emptyMap()); + this.store = new FakeStore(Collections.emptyMap()); final InternalCache ehcache = this.getEhcache(); assertThat(ehcache.iterator(), is(notNullValue())); } @@ -73,7 +73,7 @@ public void testIteratorEmptyStoreGet() throws Exception { */ @Test public void testIteratorEmptyStoreHasNext() throws Exception { - this.store = new FakeStore(Collections.emptyMap()); + this.store = new FakeStore(Collections.emptyMap()); final InternalCache ehcache = this.getEhcache(); final Iterator> iterator = ehcache.iterator(); assertThat(iterator.hasNext(), is(false)); @@ -84,7 +84,7 @@ public void testIteratorEmptyStoreHasNext() throws Exception { */ @Test public void testIteratorEmptyStoreNext() throws Exception { - this.store = new FakeStore(Collections.emptyMap()); + this.store = new FakeStore(Collections.emptyMap()); final InternalCache ehcache = this.getEhcache(); final Iterator> iterator = ehcache.iterator(); try { @@ -100,7 +100,7 @@ public void testIteratorEmptyStoreNext() throws Exception { */ @Test public void testIteratorEmptyStoreRemoveBeforeNext() throws Exception { - this.store = new FakeStore(Collections.emptyMap()); + this.store = new FakeStore(Collections.emptyMap()); final InternalCache ehcache = this.getEhcache(); final Iterator> iterator = ehcache.iterator(); try { @@ -209,7 +209,7 @@ public void testIteratorNonEmptyNextAfterLast() throws Exception { public void testIteratorStoreAccessException() throws Exception { @SuppressWarnings("unchecked") Store.ValueHolder valueHolder = mock(Store.ValueHolder.class); - doReturn("bar").when(valueHolder).value(); + doReturn("bar").when(valueHolder).get(); @SuppressWarnings("unchecked") Cache.Entry> storeEntry = mock(Cache.Entry.class); diff --git a/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java b/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java index df879ecbeb..5205bbcb7f 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java @@ -149,7 +149,7 @@ public String toString() { static ValueHolder valueHolder(final V value) { return new ValueHolder() { @Override - public V value() { + public V get() { return value; } diff --git a/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java b/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java index 05c29dfe12..b169b68b9e 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java @@ -29,7 +29,6 @@ import org.junit.Before; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.slf4j.LoggerFactory; import java.util.function.BiFunction; @@ -84,7 +83,7 @@ public void testGet() throws Exception { public void testGetThrowsOnCompute() throws Exception { when(store.computeIfAbsent(any(Number.class), anyFunction())).thenThrow(new StoreAccessException("boom")); String expected = "foo"; - when((String)cache.getCacheLoaderWriter().load(any(Number.class))).thenReturn(expected); + when(cache.getCacheLoaderWriter().load(any(Number.class))).thenReturn(expected); assertThat(cache.get(1), is(expected)); verify(store).remove(1); } @@ -382,7 +381,7 @@ public void testThreeArgReplaceThrowsOnWrite() throws Exception { @SuppressWarnings("unchecked") final Store.ValueHolder mock = mock(Store.ValueHolder.class); - when(mock.value()).thenReturn(applied); + when(mock.get()).thenReturn(applied); return mock; }); doThrow(new Exception()).when(cache.getCacheLoaderWriter()).write(any(Number.class), anyString()); diff --git a/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java b/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java index 964f50b379..7de1a6b0b3 100644 --- a/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java +++ b/core/src/test/java/org/ehcache/core/spi/store/AbstractValueHolderTest.java @@ -107,7 +107,7 @@ public void testEquals() throws Exception { public void testSubclassEquals() throws Exception { assertThat(new AbstractValueHolder(-1, 1000L) { @Override - public String value() { + public String get() { return "aaa"; } @@ -118,19 +118,19 @@ protected TimeUnit nativeTimeUnit() { @Override public int hashCode() { - return super.hashCode() + value().hashCode(); + return super.hashCode() + get().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof AbstractValueHolder) { AbstractValueHolder other = (AbstractValueHolder) obj; - return super.equals(obj) && value().equals(other.value()); + return super.equals(obj) && get().equals(other.get()); } return false; } }.equals(new AbstractValueHolder(-1, 1L) { @Override - public String value() { + public String get() { return "aaa"; } @@ -141,14 +141,14 @@ protected TimeUnit nativeTimeUnit() { @Override public int hashCode() { - return super.hashCode() + value().hashCode(); + return super.hashCode() + get().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof AbstractValueHolder) { AbstractValueHolder other = (AbstractValueHolder)obj; - return super.equals(obj) && value().equals(other.value()); + return super.equals(obj) && get().equals(other.get()); } return false; } @@ -156,7 +156,7 @@ public boolean equals(Object obj) { assertThat(new AbstractValueHolder(-1, 1000L) { @Override - public String value() { + public String get() { return "aaa"; } @@ -167,19 +167,19 @@ protected TimeUnit nativeTimeUnit() { @Override public int hashCode() { - return super.hashCode() + value().hashCode(); + return super.hashCode() + get().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof AbstractValueHolder) { AbstractValueHolder other = (AbstractValueHolder) obj; - return super.equals(obj) && value().equals(other.value()); + return super.equals(obj) && get().equals(other.get()); } return false; } }.equals(new AbstractValueHolder(-1, 1L) { @Override - public String value() { + public String get() { return "bbb"; } @@ -190,14 +190,14 @@ protected TimeUnit nativeTimeUnit() { @Override public int hashCode() { - return super.hashCode() + value().hashCode(); + return super.hashCode() + get().hashCode(); } @Override public boolean equals(Object obj) { if (obj instanceof AbstractValueHolder) { AbstractValueHolder other = (AbstractValueHolder)obj; - return super.equals(obj) && value().equals(other.value()); + return super.equals(obj) && get().equals(other.get()); } return false; } @@ -215,7 +215,7 @@ protected TimeUnit nativeTimeUnit() { } @Override - public String value() { + public String get() { return "abc"; } }; @@ -233,7 +233,7 @@ protected TimeUnit nativeTimeUnit() { return timeUnit; } @Override - public String value() { + public String get() { throw new UnsupportedOperationException(); } }; @@ -245,7 +245,7 @@ protected TimeUnit nativeTimeUnit() { return timeUnit; } @Override - public String value() { + public String get() { throw new UnsupportedOperationException(); } }; @@ -258,7 +258,7 @@ protected TimeUnit nativeTimeUnit() { } @Override - public String value() { + public String get() { throw new UnsupportedOperationException(); } }; diff --git a/core/src/test/java/org/ehcache/core/util/Matchers.java b/core/src/test/java/org/ehcache/core/util/Matchers.java index 72201329bc..9ec3ee8769 100644 --- a/core/src/test/java/org/ehcache/core/util/Matchers.java +++ b/core/src/test/java/org/ehcache/core/util/Matchers.java @@ -16,11 +16,12 @@ package org.ehcache.core.util; -import org.ehcache.ValueSupplier; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; +import java.util.function.Supplier; + import static org.hamcrest.Matchers.equalTo; /** @@ -28,15 +29,15 @@ */ public class Matchers { - public static Matcher> holding(final V value) { + public static Matcher> holding(final V value) { return holding(equalTo(value)); } - public static Matcher> holding(final Matcher matcher) { - return new TypeSafeMatcher>() { + public static Matcher> holding(final Matcher matcher) { + return new TypeSafeMatcher>() { @Override - protected boolean matchesSafely(ValueSupplier item) { - return matcher.matches(item.value()); + protected boolean matchesSafely(Supplier item) { + return matcher.matches(item.get()); } @Override diff --git a/impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java b/impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java index e543ca5a48..75c289b179 100644 --- a/impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java +++ b/impl/src/main/java/org/ehcache/config/builders/ExpiryPolicyBuilder.java @@ -15,12 +15,12 @@ */ package org.ehcache.config.builders; -import org.ehcache.ValueSupplier; import org.ehcache.config.Builder; import org.ehcache.expiry.ExpiryPolicy; import java.time.Duration; import java.util.Objects; +import java.util.function.Supplier; /** * Builder and utilities for getting predefined {@link ExpiryPolicy} instances. @@ -152,12 +152,12 @@ public Duration getExpiryForCreation(Object key, Object value) { } @Override - public Duration getExpiryForAccess(Object key, ValueSupplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { return access; } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + public Duration getExpiryForUpdate(Object key, Supplier oldValue, Object newValue) { return update; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/events/AbstractStoreEventDispatcher.java b/impl/src/main/java/org/ehcache/impl/internal/events/AbstractStoreEventDispatcher.java index 8e73521cc7..0671909c8e 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/events/AbstractStoreEventDispatcher.java +++ b/impl/src/main/java/org/ehcache/impl/internal/events/AbstractStoreEventDispatcher.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.events; -import org.ehcache.ValueSupplier; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; import org.ehcache.core.spi.store.events.StoreEventFilter; @@ -26,6 +25,7 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.LinkedBlockingQueue; +import java.util.function.Supplier; /** * AbstractStoreEventDispatcher @@ -49,17 +49,17 @@ public void reset() { } @Override - public void removed(Object key, ValueSupplier value) { + public void removed(Object key, Supplier value) { // Do nothing } @Override - public void updated(Object key, ValueSupplier oldValue, Object newValue) { + public void updated(Object key, Supplier oldValue, Object newValue) { // Do nothing } @Override - public void expired(Object key, ValueSupplier value) { + public void expired(Object key, Supplier value) { // Do nothing } @@ -69,7 +69,7 @@ public void created(Object key, Object value) { } @Override - public void evicted(Object key, ValueSupplier value) { + public void evicted(Object key, Supplier value) { // Do nothing } }; diff --git a/impl/src/main/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSink.java b/impl/src/main/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSink.java index 430a52ef5e..5079c5ce22 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSink.java +++ b/impl/src/main/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSink.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.events; -import org.ehcache.ValueSupplier; import org.ehcache.event.EventType; import org.ehcache.core.spi.store.events.StoreEventFilter; import org.ehcache.core.spi.store.events.StoreEventListener; @@ -24,6 +23,7 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.BlockingQueue; +import java.util.function.Supplier; /** * This class is responsible for handling the event fudging that needs to happen @@ -45,7 +45,7 @@ class FudgingInvocationScopedEventSink extends InvocationScopedEventSink value) { + public void evicted(K key, Supplier value) { V eventFudgingValue = handleEvictionPostWriteOnSameKey(key); super.evicted(key, value); if (eventFudgingValue != null) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/events/InvocationScopedEventSink.java b/impl/src/main/java/org/ehcache/impl/internal/events/InvocationScopedEventSink.java index 66f743ccfa..21a961e38a 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/events/InvocationScopedEventSink.java +++ b/impl/src/main/java/org/ehcache/impl/internal/events/InvocationScopedEventSink.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.events; -import org.ehcache.ValueSupplier; import org.ehcache.event.EventType; import org.ehcache.core.spi.store.events.StoreEventFilter; import org.ehcache.core.spi.store.events.StoreEventListener; @@ -26,6 +25,7 @@ import java.util.Iterator; import java.util.Set; import java.util.concurrent.BlockingQueue; +import java.util.function.Supplier; import static org.ehcache.impl.internal.events.StoreEvents.createEvent; import static org.ehcache.impl.internal.events.StoreEvents.evictEvent; @@ -54,24 +54,24 @@ class InvocationScopedEventSink implements CloseableStoreEventSink { } @Override - public void removed(K key, ValueSupplier value) { - V removedValue = value.value(); + public void removed(K key, Supplier value) { + V removedValue = value.get(); if (acceptEvent(EventType.REMOVED, key, removedValue, null)) { handleEvent(key, new FireableStoreEventHolder<>(removeEvent(key, removedValue))); } } @Override - public void updated(K key, ValueSupplier oldValue, V newValue) { - V oldValueValue = oldValue.value(); + public void updated(K key, Supplier oldValue, V newValue) { + V oldValueValue = oldValue.get(); if (acceptEvent(EventType.UPDATED, key, oldValueValue, newValue)) { handleEvent(key, new FireableStoreEventHolder<>(updateEvent(key, oldValueValue, newValue))); } } @Override - public void expired(K key, ValueSupplier value) { - V expired = value.value(); + public void expired(K key, Supplier value) { + V expired = value.get(); if (acceptEvent(EventType.EXPIRED, key, expired, null)) { handleEvent(key, new FireableStoreEventHolder<>(expireEvent(key, expired))); } @@ -85,8 +85,8 @@ public void created(K key, V value) { } @Override - public void evicted(K key, ValueSupplier value) { - V evicted = value.value(); + public void evicted(K key, Supplier value) { + V evicted = value.get(); if (acceptEvent(EventType.EVICTED, key, evicted, null)) { handleEvent(key, new FireableStoreEventHolder<>(evictEvent(key, evicted))); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/basic/EmptyValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/basic/EmptyValueHolder.java index 4566dffc04..18077b2fa8 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/basic/EmptyValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/basic/EmptyValueHolder.java @@ -34,7 +34,7 @@ public static Store.ValueHolder empty() { } @Override - public V value() { + public V get() { return null; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index 80f29fd8a0..2479fe0919 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -95,7 +95,6 @@ import static org.ehcache.config.Eviction.noAdvice; import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; import static org.ehcache.core.exceptions.StorePassThroughException.handleRuntimeException; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.terracotta.statistics.StatisticBuilder.operation; /** @@ -481,7 +480,7 @@ public RemoveStatus remove(final K key, final V value) throws StoreAccessExcepti updateUsageInBytesIfRequired(- mappedValue.size()); fireOnExpirationEvent(mappedKey, mappedValue, eventSink); return null; - } else if (value.equals(mappedValue.value())) { + } else if (value.equals(mappedValue.get())) { updateUsageInBytesIfRequired(- mappedValue.size()); eventSink.removed(mappedKey, mappedValue); outcome.set(RemoveStatus.REMOVED); @@ -574,7 +573,7 @@ public ReplaceStatus replace(final K key, final V oldValue, final V newValue) th map.computeIfPresent(key, (mappedKey, mappedValue) -> { final long now = timeSource.getTimeMillis(); - V existingValue = mappedValue.value(); + V existingValue = mappedValue.get(); if (mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { fireOnExpirationEvent(mappedKey, mappedValue, eventSink); updateUsageInBytesIfRequired(- mappedValue.size()); @@ -701,7 +700,7 @@ public ValueHolder getOrComputeIfAbsent(final K key, final Function resolveFault(final K key, Backend backEnd, long now, Fault fault) throws StoreAccessException { try { - final ValueHolder value = fault.get(); + final ValueHolder value = fault.getValueHolder(); final OnHeapValueHolder newValue; if(value != null) { newValue = importValueFromLowerTier(key, value, now, backEnd, fault); @@ -906,7 +905,7 @@ public void invalidateAllWithHash(long hash) { private ValueHolder getValue(final ValueHolder cachedValue) { if (cachedValue instanceof Fault) { - return ((Fault)cachedValue).get(); + return ((Fault)cachedValue).getValueHolder(); } else { return cachedValue; } @@ -944,7 +943,7 @@ private void complete(ValueHolder value) { } } - private ValueHolder get() { + private ValueHolder getValueHolder() { synchronized (this) { if (!complete) { try { @@ -983,7 +982,7 @@ private void fail(final Throwable t) { } @Override - public V value() { + public V get() { throw new UnsupportedOperationException(); } @@ -1068,7 +1067,7 @@ public ValueHolder compute(final K key, final BiFunction newUpdateValueHolder(K key, OnHeapValueHolder ol } if (Duration.ZERO.equals(duration)) { eventSink.updated(key, oldValue, newValue); - eventSink.expired(key, supplierOf(newValue)); + eventSink.expired(key, () -> newValue); return null; } @@ -1422,7 +1421,7 @@ private OnHeapValueHolder importValueFromLowerTier(K key, ValueHolder valu } private OnHeapValueHolder cloneValueHolder(K key, ValueHolder valueHolder, long now, Duration expiration, boolean sizingEnabled) throws LimitExceededException { - V realValue = valueHolder.value(); + V realValue = valueHolder.get(); boolean evictionAdvice = checkEvictionAdvice(key, realValue); OnHeapValueHolder clonedValueHolder; if(valueCopier instanceof SerializingCopier) { diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java index fe1b46c9a5..ecb1fbb8c6 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolder.java @@ -73,7 +73,7 @@ public CopiedOnHeapValueHolder(V value, long creationTime, long expirationTime, } @Override - public V value() { + public V get() { return valueCopier.copyForRead(copiedValue); } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java index 3d01646c55..a6435c93ff 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolder.java @@ -63,7 +63,7 @@ public SerializedOnHeapValueHolder(Store.ValueHolder valueHolder, ByteBuffer } @Override - public final V value() { + public final V get() { try { return serializer.read(buffer.duplicate()); } catch (ClassNotFoundException cnfe) { @@ -91,7 +91,7 @@ public boolean equals(Object other) { if (!super.equals(that)) return false; try { - if (!serializer.equals(that.value(), buffer)) return false; + if (!serializer.equals(that.get(), buffer)) return false; } catch (ClassNotFoundException cnfe) { throw new SerializerException(cnfe); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index 146ec84ad9..137d78481d 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -57,7 +57,6 @@ import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; import static org.ehcache.core.exceptions.StorePassThroughException.handleRuntimeException; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.terracotta.statistics.StatisticBuilder.operation; public abstract class AbstractOffHeapStore implements AuthoritativeTier, LowerCachingTier { @@ -378,7 +377,7 @@ public RemoveStatus remove(final K key, final V value) throws StoreAccessExcepti if (mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue, eventSink); return null; - } else if (mappedValue.value().equals(value)) { + } else if (mappedValue.get().equals(value)) { removed.set(true); eventSink.removed(mappedKey, mappedValue); return null; @@ -464,7 +463,7 @@ public ReplaceStatus replace(final K key, final V oldValue, final V newValue) th onExpiration(mappedKey, mappedValue, eventSink); } return null; - } else if (oldValue.equals(mappedValue.value())) { + } else if (oldValue.equals(mappedValue.get())) { replaced.set(true); return newUpdatedValueHolder(mappedKey, newValue, mappedValue, now, eventSink); } else { @@ -558,7 +557,7 @@ public ValueHolder compute(final K key, final BiFunction newUpdatedValueHolder(K key, V value, OffHeapValue LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); } if (Duration.ZERO.equals(duration)) { - eventSink.expired(key, supplierOf(value)); + eventSink.expired(key, () -> value); return null; } @@ -1066,11 +1065,11 @@ private OffHeapValueHolder newCreateValueHolder(K key, V value, long now, Sto private OffHeapValueHolder newTransferValueHolder(ValueHolder valueHolder) { if (valueHolder instanceof BinaryValueHolder && ((BinaryValueHolder) valueHolder).isBinaryValueAvailable()) { - return new BinaryOffHeapValueHolder<>(valueHolder.getId(), valueHolder.value(), ((BinaryValueHolder) valueHolder).getBinaryValue(), + return new BinaryOffHeapValueHolder<>(valueHolder.getId(), valueHolder.get(), ((BinaryValueHolder) valueHolder).getBinaryValue(), valueHolder.creationTime(OffHeapValueHolder.TIME_UNIT), valueHolder.expirationTime(OffHeapValueHolder.TIME_UNIT), valueHolder.lastAccessTime(OffHeapValueHolder.TIME_UNIT), valueHolder.hits()); } else { - return new BasicOffHeapValueHolder<>(valueHolder.getId(), valueHolder.value(), valueHolder.creationTime(OffHeapValueHolder.TIME_UNIT), + return new BasicOffHeapValueHolder<>(valueHolder.getId(), valueHolder.get(), valueHolder.creationTime(OffHeapValueHolder.TIME_UNIT), valueHolder.expirationTime(OffHeapValueHolder.TIME_UNIT), valueHolder.lastAccessTime(OffHeapValueHolder.TIME_UNIT), valueHolder .hits()); } @@ -1138,7 +1137,7 @@ private OffHeapEvictionAdvisorWrapper(EvictionAdvisor dele @Override public boolean adviseAgainstEviction(K key, OffHeapValueHolder value) { try { - return delegate.adviseAgainstEviction(key, value.value()); + return delegate.adviseAgainstEviction(key, value.get()); } catch (Exception e) { LOG.error("Exception raised while running eviction advisor " + "- Eviction will assume entry is NOT advised against eviction", e); diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolder.java index 8a518c5956..b23cec62d4 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolder.java @@ -57,7 +57,7 @@ void detach() { } @Override - public V value() { + public V get() { return value; } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java index 81d0b5133c..14d49e8bd2 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolder.java @@ -70,7 +70,7 @@ void detach() { } @Override - public V value() { + public V get() { return value; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java index 5b5216d03c..1e2c8d80dd 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolder.java @@ -49,7 +49,7 @@ public LazyOffHeapValueHolder(long id, ByteBuffer binaryValue, Serializer ser } @Override - public V value() { + public V get() { forceDeserialization(); return value; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapValueHolder.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapValueHolder.java index 1990aeba91..daab162d26 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapValueHolder.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapValueHolder.java @@ -45,14 +45,14 @@ public boolean equals(Object other) { OffHeapValueHolder that = (OffHeapValueHolder)other; if (!super.equals(that)) return false; - return value().equals(that.value()); + return get().equals(that.get()); } @Override public int hashCode() { int result = 1; - result = 31 * result + value().hashCode(); + result = 31 * result + get().hashCode(); result = 31 * result + super.hashCode(); return result; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/portability/OffHeapValueHolderPortability.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/portability/OffHeapValueHolderPortability.java index 20f1d1c1fa..e360648906 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/portability/OffHeapValueHolderPortability.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/portability/OffHeapValueHolderPortability.java @@ -49,7 +49,7 @@ public ByteBuffer encode(OffHeapValueHolder valueHolder) { if (valueHolder instanceof BinaryValueHolder && ((BinaryValueHolder)valueHolder).isBinaryValueAvailable()) { serialized = ((BinaryValueHolder)valueHolder).getBinaryValue(); } else { - serialized = serializer.serialize(valueHolder.value()); + serialized = serializer.serialize(valueHolder.get()); } ByteBuffer byteBuffer = ByteBuffer.allocate(serialized.remaining() + FIELDS_OVERHEAD); byteBuffer.putLong(valueHolder.getId()); diff --git a/impl/src/test/java/org/ehcache/docs/Ehcache3.java b/impl/src/test/java/org/ehcache/docs/Ehcache3.java index 7bee442b26..fe4d6bf46b 100644 --- a/impl/src/test/java/org/ehcache/docs/Ehcache3.java +++ b/impl/src/test/java/org/ehcache/docs/Ehcache3.java @@ -17,7 +17,6 @@ import org.ehcache.Cache; import org.ehcache.CacheManager; -import org.ehcache.ValueSupplier; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; @@ -27,6 +26,7 @@ import org.junit.Test; import java.time.Duration; +import java.util.function.Supplier; public class Ehcache3 { @@ -46,12 +46,12 @@ public Duration getExpiryForCreation(Long key, String value) { } @Override - public Duration getExpiryForAccess(Long key, ValueSupplier value) { + public Duration getExpiryForAccess(Long key, Supplier value) { return null; // Keeping the existing expiry } @Override - public Duration getExpiryForUpdate(Long key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(Long key, Supplier oldValue, String newValue) { return null; // Keeping the existing expiry } }); @@ -96,7 +96,7 @@ private CacheManager initCacheManager() { .build(true); } - private void sleep(int millisecondsToSleep) throws Exception { + private void sleep(int millisecondsToSleep) { timeSource.advanceTime(millisecondsToSleep); } } diff --git a/impl/src/test/java/org/ehcache/docs/GettingStarted.java b/impl/src/test/java/org/ehcache/docs/GettingStarted.java index 2679e4ee1f..5653d8f9de 100644 --- a/impl/src/test/java/org/ehcache/docs/GettingStarted.java +++ b/impl/src/test/java/org/ehcache/docs/GettingStarted.java @@ -19,7 +19,6 @@ import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.PersistentCacheManager; -import org.ehcache.ValueSupplier; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; @@ -46,6 +45,7 @@ import java.time.Duration; import java.util.EnumSet; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import static java.util.Collections.singletonMap; import static org.hamcrest.Matchers.equalTo; @@ -130,7 +130,7 @@ public void testCacheEventListener() { } @Test - public void writeThroughCache() throws ClassNotFoundException { + public void writeThroughCache() { // tag::writeThroughCache[] CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); @@ -148,7 +148,7 @@ public void writeThroughCache() throws ClassNotFoundException { } @Test - public void writeBehindCache() throws ClassNotFoundException { + public void writeBehindCache() { // tag::writeBehindCache[] CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().build(true); @@ -173,7 +173,7 @@ public void writeBehindCache() throws ClassNotFoundException { } @Test - public void registerListenerAtRuntime() throws InterruptedException { + public void registerListenerAtRuntime() { CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder() .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.heap(10L))) @@ -362,12 +362,12 @@ public Duration getExpiryForCreation(Long key, String value) { } @Override - public Duration getExpiryForAccess(Long key, ValueSupplier value) { + public Duration getExpiryForAccess(Long key, Supplier value) { throw new UnsupportedOperationException("TODO Implement me!"); } @Override - public Duration getExpiryForUpdate(Long key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(Long key, Supplier oldValue, String newValue) { throw new UnsupportedOperationException("TODO Implement me!"); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSinkTest.java b/impl/src/test/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSinkTest.java index d078fda150..1095e6d94d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSinkTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/events/FudgingInvocationScopedEventSinkTest.java @@ -18,7 +18,6 @@ import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.event.EventType; -import org.ehcache.core.spi.store.events.StoreEventFilter; import org.ehcache.core.spi.store.events.StoreEventListener; import org.hamcrest.Matcher; import org.junit.Before; @@ -29,7 +28,6 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.ehcache.impl.internal.store.offheap.AbstractOffHeapStoreTest.eventType; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -61,7 +59,7 @@ public void setUp() { @Test public void testEvictedDifferentKeyNoImpact() { eventSink.created("k1", "v1"); - eventSink.evicted("k2", supplierOf("v2")); + eventSink.evicted("k2", () -> "v2"); eventSink.close(); InOrder inOrder = inOrder(listener); @@ -72,8 +70,8 @@ public void testEvictedDifferentKeyNoImpact() { @Test public void testEvictedSameKeyAfterUpdateReplacesWithEvictCreate() { - eventSink.updated("k1", supplierOf("v0"), "v1"); - eventSink.evicted("k1", supplierOf("v0")); + eventSink.updated("k1", () -> "v0", "v1"); + eventSink.evicted("k1", () -> "v0"); eventSink.close(); InOrder inOrder = inOrder(listener); @@ -84,9 +82,9 @@ public void testEvictedSameKeyAfterUpdateReplacesWithEvictCreate() { @Test public void testEvictedSameKeyAfterCreateFudgesExpiryToo() { - eventSink.expired("k1", supplierOf("v0")); + eventSink.expired("k1", () -> "v0"); eventSink.created("k1", "v1"); - eventSink.evicted("k1", supplierOf("v0")); + eventSink.evicted("k1", () -> "v0"); eventSink.close(); InOrder inOrder = inOrder(listener); @@ -97,10 +95,10 @@ public void testEvictedSameKeyAfterCreateFudgesExpiryToo() { @Test public void testEvictedSameKeyAfterUpdateReplacesWithEvictCreateEvenWithMultipleEvictsInBetween() { - eventSink.updated("k1", supplierOf("v0"), "v1"); - eventSink.evicted("k2", supplierOf("v2")); - eventSink.evicted("k3", supplierOf("v3")); - eventSink.evicted("k1", supplierOf("v0")); + eventSink.updated("k1", () -> "v0", "v1"); + eventSink.evicted("k2", () -> "v2"); + eventSink.evicted("k3", () -> "v3"); + eventSink.evicted("k1", () -> "v0"); eventSink.close(); InOrder inOrder = inOrder(listener); @@ -111,11 +109,11 @@ public void testEvictedSameKeyAfterUpdateReplacesWithEvictCreateEvenWithMultiple @Test public void testEvictedSameKeyAfterCreateFudgesExpiryTooEvenWithMultipleEvictsInBetween() { - eventSink.expired("k1", supplierOf("v0")); + eventSink.expired("k1", () -> "v0"); eventSink.created("k1", "v1"); - eventSink.evicted("k2", supplierOf("v2")); - eventSink.evicted("k3", supplierOf("v3")); - eventSink.evicted("k1", supplierOf("v0")); + eventSink.evicted("k2", () -> "v2"); + eventSink.evicted("k3", () -> "v3"); + eventSink.evicted("k1", () -> "v0"); eventSink.close(); InOrder inOrder = inOrder(listener); @@ -126,9 +124,9 @@ public void testEvictedSameKeyAfterCreateFudgesExpiryTooEvenWithMultipleEvictsIn @Test public void testEvictedKeyDoesNotFudgeOlderEvents() { - eventSink.updated("k1", supplierOf("v0"), "v1"); + eventSink.updated("k1", () -> "v0", "v1"); eventSink.created("k2", "v2"); - eventSink.evicted("k1", supplierOf("v0")); + eventSink.evicted("k1", () -> "v0"); eventSink.close(); InOrder inOrder = inOrder(listener); diff --git a/impl/src/test/java/org/ehcache/impl/internal/events/InvocationScopedEventSinkTest.java b/impl/src/test/java/org/ehcache/impl/internal/events/InvocationScopedEventSinkTest.java index e83ec9371c..d0a3b7e22a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/events/InvocationScopedEventSinkTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/events/InvocationScopedEventSinkTest.java @@ -17,7 +17,6 @@ package org.ehcache.impl.internal.events; import org.ehcache.core.spi.store.events.StoreEvent; -import org.ehcache.core.spi.store.events.StoreEventFilter; import org.ehcache.core.spi.store.events.StoreEventListener; import org.ehcache.event.EventType; import org.hamcrest.Matcher; @@ -29,7 +28,6 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.ehcache.impl.internal.store.offheap.AbstractOffHeapStoreTest.eventType; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; @@ -58,11 +56,11 @@ public void setUp() { @Test public void testReset() { eventSink.created("k1", "v1"); - eventSink.evicted("k1", supplierOf("v2")); + eventSink.evicted("k1", () -> "v2"); eventSink.reset(); eventSink.created("k1", "v1"); - eventSink.updated("k1", supplierOf("v1"), "v2"); - eventSink.evicted("k1", supplierOf("v2")); + eventSink.updated("k1", () -> "v1", "v2"); + eventSink.evicted("k1", () -> "v2"); eventSink.close(); InOrder inOrder = inOrder(listener); diff --git a/impl/src/test/java/org/ehcache/impl/internal/events/ScopedStoreEventDispatcherTest.java b/impl/src/test/java/org/ehcache/impl/internal/events/ScopedStoreEventDispatcherTest.java index bb9066a316..00cd7eceff 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/events/ScopedStoreEventDispatcherTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/events/ScopedStoreEventDispatcherTest.java @@ -30,9 +30,7 @@ import java.util.Random; import java.util.concurrent.CountDownLatch; -import java.util.function.BiFunction; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.ehcache.impl.internal.util.Matchers.eventOfType; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; @@ -109,7 +107,7 @@ public void testEventFiltering() { dispatcher.addEventFilter(filter); StoreEventSink sink = dispatcher.eventSink(); - sink.removed("gone", supplierOf("really gone")); + sink.removed("gone", () -> "really gone"); sink.created("new", "and shiny"); dispatcher.releaseEventSink(sink); diff --git a/impl/src/test/java/org/ehcache/impl/internal/events/TestStoreEventDispatcher.java b/impl/src/test/java/org/ehcache/impl/internal/events/TestStoreEventDispatcher.java index 578951a29a..6292adc84d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/events/TestStoreEventDispatcher.java +++ b/impl/src/test/java/org/ehcache/impl/internal/events/TestStoreEventDispatcher.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.events; -import org.ehcache.ValueSupplier; import org.ehcache.event.EventType; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; @@ -26,6 +25,7 @@ import java.util.HashSet; import java.util.Set; +import java.util.function.Supplier; /** * TestStoreEventDispatcher @@ -92,9 +92,9 @@ public boolean isEventOrdering() { private class EventBridge implements StoreEventSink { @Override - public void evicted(K key, ValueSupplier value) { - if (accepted(EventType.EVICTED, key, value.value(), null)) { - StoreEvent event = StoreEvents.evictEvent(key, value.value()); + public void evicted(K key, Supplier value) { + if (accepted(EventType.EVICTED, key, value.get(), null)) { + StoreEvent event = StoreEvents.evictEvent(key, value.get()); for (StoreEventListener listener : listeners) { listener.onEvent(event); } @@ -102,9 +102,9 @@ public void evicted(K key, ValueSupplier value) { } @Override - public void expired(K key, ValueSupplier value) { - if (accepted(EventType.EXPIRED, key, value.value(), null)) { - StoreEvent event = StoreEvents.expireEvent(key, value.value()); + public void expired(K key, Supplier value) { + if (accepted(EventType.EXPIRED, key, value.get(), null)) { + StoreEvent event = StoreEvents.expireEvent(key, value.get()); for (StoreEventListener listener : listeners) { listener.onEvent(event); } @@ -122,9 +122,9 @@ public void created(K key, V value) { } @Override - public void updated(K key, ValueSupplier previousValue, V newValue) { - if (accepted(EventType.UPDATED, key, previousValue.value(), newValue)) { - StoreEvent event = StoreEvents.updateEvent(key, previousValue.value(), newValue); + public void updated(K key, Supplier previousValue, V newValue) { + if (accepted(EventType.UPDATED, key, previousValue.get(), newValue)) { + StoreEvent event = StoreEvents.updateEvent(key, previousValue.get(), newValue); for (StoreEventListener listener : listeners) { listener.onEvent(event); } @@ -132,9 +132,9 @@ public void updated(K key, ValueSupplier previousValue, V newValue) { } @Override - public void removed(K key, ValueSupplier removed) { - if (accepted(EventType.REMOVED, key, removed.value(), null)) { - StoreEvent event = StoreEvents.removeEvent(key, removed.value()); + public void removed(K key, Supplier removed) { + if (accepted(EventType.REMOVED, key, removed.get(), null)) { + StoreEvent event = StoreEvents.removeEvent(key, removed.get()); for (StoreEventListener listener : listeners) { listener.onEvent(event); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java index b3bff8a817..c70e458e38 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java @@ -16,7 +16,6 @@ package org.ehcache.impl.internal.store.heap; import org.ehcache.Cache.Entry; -import org.ehcache.ValueSupplier; import org.ehcache.config.Eviction; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.builders.ExpiryPolicyBuilder; @@ -54,6 +53,7 @@ import java.util.concurrent.Exchanger; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import static org.ehcache.config.builders.ExpiryPolicyBuilder.expiry; import static org.ehcache.impl.internal.util.Matchers.holding; @@ -177,7 +177,7 @@ public void testEvictWithBrokenEvictionAdvisorDoesEvict() throws Exception { public void testGet() throws Exception { OnHeapStore store = newStore(); store.put("key", "value"); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.HIT)); } @@ -196,7 +196,7 @@ public void testGetExpired() throws Exception { OnHeapStore store = newStore(timeSource, ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); timeSource.advanceTime(1); assertThat(store.get("key"), nullValue()); @@ -214,7 +214,7 @@ public void testGetNoExpired() throws Exception { StoreEventSink eventSink = getStoreEventSink(); store.put("key", "value"); timeSource.advanceTime(1); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); verify(eventSink, never()).expired(anyString(), anyValueSupplier()); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.GetOutcome.HIT)); } @@ -273,7 +273,7 @@ public void testPut() throws Exception { verify(eventSink).created(eq("key"), eq("value")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.PutOutcome.PUT)); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -287,7 +287,7 @@ public void testPutOverwrite() throws Exception { store.put("key", "value2"); verify(eventSink).updated(eq("key"), argThat(holding("value")), eq("value2")); verifyListenerReleaseEventsInOrder(eventDispatcher); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(store.get("key").get(), equalTo("value2")); } @Test @@ -321,7 +321,7 @@ public void testPutIfAbsentNoValue() throws Exception { verify(eventSink).created(eq("key"), eq("value")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT)); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -329,7 +329,7 @@ public void testPutIfAbsentValuePresent() throws Exception { OnHeapStore store = newStore(); store.put("key", "value"); ValueHolder prev = store.putIfAbsent("key", "value2"); - assertThat(prev.value(), equalTo("value")); + assertThat(prev.get(), equalTo("value")); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.HIT)); } @@ -354,7 +354,7 @@ public void testPutIfAbsentExpired() throws Exception { timeSource.advanceTime(1); ValueHolder prev = store.putIfAbsent("key", "value2"); assertThat(prev, nullValue()); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(store.get("key").get(), equalTo("value2")); checkExpiryEvent(getStoreEventSink(), "key", "value"); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ExpirationOutcome.SUCCESS)); } @@ -395,7 +395,7 @@ public void testRemoveTwoArgNoMatch() throws Exception { RemoveStatus removed = store.remove("key", "not value"); assertThat(removed, equalTo(RemoveStatus.KEY_PRESENT)); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ConditionalRemoveOutcome.MISS)); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -406,7 +406,7 @@ public void testRemoveTwoArgExpired() throws Exception { ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(1))); store.put("key", "value"); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); timeSource.advanceTime(1); RemoveStatus removed = store.remove("key", "value"); assertThat(removed, equalTo(RemoveStatus.KEY_MISSING)); @@ -423,8 +423,8 @@ public void testReplaceTwoArgPresent() throws Exception { store.put("key", "value"); ValueHolder existing = store.replace("key", "value2"); - assertThat(existing.value(), equalTo("value")); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(existing.get(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value2")); verify(eventSink).updated(eq("key"), argThat(holding("value")), eq("value2")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ReplaceOutcome.REPLACED)); @@ -466,7 +466,7 @@ public void testReplaceThreeArgMatch() throws Exception { ReplaceStatus replaced = store.replace("key", "value", "value2"); assertThat(replaced, equalTo(ReplaceStatus.HIT)); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(store.get("key").get(), equalTo("value2")); verify(eventSink).updated(eq("key"), argThat(holding("value")), eq("value2")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ConditionalReplaceOutcome.REPLACED)); @@ -579,7 +579,7 @@ public void testComputeReplaceTrue() throws Exception { ValueHolder newValue = store.compute("key", (mappedKey, mappedValue) -> mappedValue, () -> true); - assertThat(newValue.value(), equalTo("value")); + assertThat(newValue.get(), equalTo("value")); assertThat(createTime + 1, equalTo(newValue.creationTime(TimeUnit.MILLISECONDS))); assertThat(accessTime + 1, equalTo(newValue.lastAccessTime(TimeUnit.MILLISECONDS))); verify(eventSink).updated(eq("key"), argThat(holding("value")), eq("value")); @@ -600,7 +600,7 @@ public void testComputeReplaceFalse() throws Exception { ValueHolder newValue = store.compute("key", (mappedKey, mappedValue) -> mappedValue, () -> false); - assertThat(newValue.value(), equalTo("value")); + assertThat(newValue.get(), equalTo("value")); assertThat(createTime, equalTo(newValue.creationTime(TimeUnit.MILLISECONDS))); assertThat(accessTime + 1, equalTo(newValue.lastAccessTime(TimeUnit.MILLISECONDS))); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ComputeOutcome.HIT)); @@ -618,11 +618,11 @@ public void testCompute() throws Exception { return "value"; }); - assertThat(newValue.value(), equalTo("value")); + assertThat(newValue.get(), equalTo("value")); verify(eventSink).created(eq("key"), eq("value")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ComputeOutcome.PUT)); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -661,7 +661,7 @@ public void testComputeException() throws Exception { } catch (StoreAccessException cae) { assertThat(cae.getCause(), is((Throwable)RUNTIME_EXCEPTION)); } - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -678,11 +678,11 @@ public void testComputeExistingValue() throws Exception { return "value2"; }); - assertThat(newValue.value(), equalTo("value2")); + assertThat(newValue.get(), equalTo("value2")); verify(eventSink).updated(eq("key"), argThat(holding("value")), eq("value2")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ComputeOutcome.PUT)); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(store.get("key").get(), equalTo("value2")); } @Test @@ -699,8 +699,8 @@ public void testComputeExpired() throws Exception { return "value2"; }); - assertThat(newValue.value(), equalTo("value2")); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(newValue.get(), equalTo("value2")); + assertThat(store.get("key").get(), equalTo("value2")); checkExpiryEvent(eventSink, "key", "value"); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ExpirationOutcome.SUCCESS)); } @@ -748,11 +748,11 @@ public void testComputeIfAbsent() throws Exception { return "value"; }); - assertThat(newValue.value(), equalTo("value")); + assertThat(newValue.get(), equalTo("value")); verify(eventSink).created(eq("key"), eq("value")); verifyListenerReleaseEventsInOrder(eventDispatcher); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ComputeIfAbsentOutcome.PUT)); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -765,9 +765,9 @@ public void testComputeIfAbsentExisting() throws Exception { return null; }); - assertThat(newValue.value(), equalTo("value")); + assertThat(newValue.get(), equalTo("value")); StatisticsTestUtils.validateStats(store, EnumSet.of(StoreOperationOutcomes.ComputeIfAbsentOutcome.HIT)); - assertThat(store.get("key").value(), equalTo("value")); + assertThat(store.get("key").get(), equalTo("value")); } @Test @@ -812,8 +812,8 @@ public void testComputeIfAbsentExpired() throws Exception { return "value2"; }); - assertThat(newValue.value(), equalTo("value2")); - assertThat(store.get("key").value(), equalTo("value2")); + assertThat(newValue.get(), equalTo("value2")); + assertThat(store.get("key").get(), equalTo("value2")); final String value = "value"; verify(eventSink).expired(eq("key"), argThat(holding(value))); verify(eventSink).created(eq("key"), eq("value2")); @@ -832,12 +832,12 @@ public Duration getExpiryForCreation(String key, String value) { } @Override - public Duration getExpiryForAccess(String key, ValueSupplier value) { + public Duration getExpiryForAccess(String key, Supplier value) { throw new AssertionError(); } @Override - public Duration getExpiryForUpdate(String key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(String key, Supplier oldValue, String newValue) { throw new AssertionError(); } }); @@ -858,12 +858,12 @@ public Duration getExpiryForCreation(String key, String value) { } @Override - public Duration getExpiryForAccess(String key, ValueSupplier value) { + public Duration getExpiryForAccess(String key, Supplier value) { throw RUNTIME_EXCEPTION; } @Override - public Duration getExpiryForUpdate(String key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(String key, Supplier oldValue, String newValue) { return null; } }); @@ -883,12 +883,12 @@ public Duration getExpiryForCreation(String key, String value) { } @Override - public Duration getExpiryForAccess(String key, ValueSupplier value) { + public Duration getExpiryForAccess(String key, Supplier value) { return ExpiryPolicy.INFINITE; } @Override - public Duration getExpiryForUpdate(String key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(String key, Supplier oldValue, String newValue) { if (timeSource.getTimeMillis() > 0) { throw new RuntimeException(); } @@ -944,7 +944,7 @@ public void testGetOfComputeIfAbsentExpiresWithLoaderWriter() throws Exception { @SuppressWarnings("unchecked") final ValueHolder vh = mock(ValueHolder.class); - when(vh.value()).thenReturn("newvalue"); + when(vh.get()).thenReturn("newvalue"); when(vh.expirationTime(TimeUnit.MILLISECONDS)).thenReturn(2L); ValueHolder newValue = store.getOrComputeIfAbsent("key", s -> vh); @@ -1056,7 +1056,7 @@ public void testGetOrComputeIfAbsentContention() throws InterruptedException { try { ValueHolder result = store.getOrComputeIfAbsent("42", key -> new CopiedOnHeapValueHolder<>("theAnswer!", System .currentTimeMillis(), -1, false, new IdentityCopier<>())); - assertThat(result.value(), is("theAnswer!")); + assertThat(result.get(), is("theAnswer!")); endLatch.countDown(); } catch (Exception e) { e.printStackTrace(); @@ -1245,8 +1245,8 @@ public void testIteratorExpiryHappensUnderExpiredKeyLockScope() throws Exception } @SuppressWarnings("unchecked") - private ValueSupplier anyValueSupplier() { - return any(ValueSupplier.class); + private Supplier anyValueSupplier() { + return any(Supplier.class); } private void verifyListenerReleaseEventsInOrder(StoreEventDispatcher listener) { @@ -1298,14 +1298,14 @@ private static Map observe(Iterator map = new HashMap<>(); while (iter.hasNext()) { Entry> entry = iter.next(); - map.put(entry.getKey(), entry.getValue().value()); + map.put(entry.getKey(), entry.getValue().get()); } return map; } private static void assertEntry(Entry> entry, String key, String value) { assertThat(entry.getKey(), equalTo(key)); - assertThat(entry.getValue().value(), equalTo(value)); + assertThat(entry.getValue().get(), equalTo(value)); } private static class TestTimeSource implements TimeSource { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java index b22f899844..df46fc646d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreBulkMethodsTest.java @@ -77,10 +77,9 @@ public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { when(config.getKeyType()).thenReturn(Number.class); when(config.getValueType()).thenReturn(Number.class); when(config.getResourcePools()).thenReturn(newResourcePoolsBuilder().heap(Long.MAX_VALUE, EntryUnit.ENTRIES).build()); - Store.Configuration configuration = config; - OnHeapStore store = new OnHeapStore(configuration, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, - new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); + OnHeapStore store = new OnHeapStore<>(config, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, + new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); store.put(1, 2); store.put(2, 3); store.put(3, 4); @@ -111,17 +110,17 @@ public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { check.put(5, 0); check.put(6, 0); - assertThat(result.get(1).value(), Matchers.is(check.get(1))); - assertThat(result.get(2).value(), Matchers.is(check.get(2))); - assertThat(result.get(3).value(), Matchers.is(check.get(3))); + assertThat(result.get(1).get(), Matchers.is(check.get(1))); + assertThat(result.get(2).get(), Matchers.is(check.get(2))); + assertThat(result.get(3).get(), Matchers.is(check.get(3))); assertThat(result.get(4), nullValue()); - assertThat(result.get(5).value(), Matchers.is(check.get(5))); - assertThat(result.get(6).value(), Matchers.is(check.get(6))); + assertThat(result.get(5).get(), Matchers.is(check.get(5))); + assertThat(result.get(6).get(), Matchers.is(check.get(6))); for (Number key : check.keySet()) { final Store.ValueHolder holder = store.get(key); if(holder != null) { - check.remove(key, holder.value()); + check.remove(key, holder.get()); } } assertThat(check.size(), is(1)); @@ -147,11 +146,11 @@ public void testBulkComputeHappyPath() throws Exception { }); assertThat(result.size(), is(2)); - assertThat(result.get(1).value(), Matchers.equalTo("un")); - assertThat(result.get(2).value(), Matchers.equalTo("deux")); + assertThat(result.get(1).get(), Matchers.equalTo("un")); + assertThat(result.get(2).get(), Matchers.equalTo("deux")); - assertThat(store.get(1).value(), Matchers.equalTo("un")); - assertThat(store.get(2).value(), Matchers.equalTo("deux")); + assertThat(store.get(1).get(), Matchers.equalTo("un")); + assertThat(store.get(2).get(), Matchers.equalTo("deux")); } @Test @@ -159,7 +158,7 @@ public void testBulkComputeStoreRemovesValueWhenFunctionReturnsNullMappings() th Store.Configuration configuration = mockStoreConfig(); @SuppressWarnings("unchecked") - OnHeapStore store = new OnHeapStore(configuration, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); + OnHeapStore store = new OnHeapStore(configuration, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); store.put(1, "one"); store.put(2, "two"); store.put(3, "three"); @@ -176,7 +175,7 @@ public void testBulkComputeStoreRemovesValueWhenFunctionReturnsNullMappings() th assertThat(store.get(1), is(nullValue())); assertThat(store.get(2), is(nullValue())); - assertThat(store.get(3).value(), Matchers.equalTo("three")); + assertThat(store.get(3).get(), Matchers.equalTo("three")); assertThat(store.get(5), is(nullValue())); } @@ -204,11 +203,11 @@ public void testBulkComputeRemoveNullValueEntriesFromFunctionReturn() throws Exc assertThat(result.size(), is(3)); assertThat(result.get(1), is(nullValue())); - assertThat(result.get(2).value(), Matchers.equalTo("two")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); assertThat(result.get(3), is(nullValue())); assertThat(store.get(1),is(nullValue())); - assertThat(store.get(2).value(), Matchers.equalTo("two")); + assertThat(store.get(2).get(), Matchers.equalTo("two")); assertThat(store.get(3),is(nullValue())); } @@ -239,16 +238,16 @@ public void testBulkComputeIfAbsentFunctionDoesNotGetPresentKeys() throws Except }); assertThat(result.size(), is(6)); - assertThat(result.get(1).value(), Matchers.equalTo("one")); - assertThat(result.get(2).value(), Matchers.equalTo("two")); - assertThat(result.get(3).value(), Matchers.equalTo("three")); + assertThat(result.get(1).get(), Matchers.equalTo("one")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); + assertThat(result.get(3).get(), Matchers.equalTo("three")); assertThat(result.get(4), is(nullValue())); assertThat(result.get(5), is(nullValue())); assertThat(result.get(6), is(nullValue())); - assertThat(store.get(1).value(), Matchers.equalTo("one")); - assertThat(store.get(2).value(), Matchers.equalTo("two")); - assertThat(store.get(3).value(), Matchers.equalTo("three")); + assertThat(store.get(1).get(), Matchers.equalTo("one")); + assertThat(store.get(2).get(), Matchers.equalTo("two")); + assertThat(store.get(3).get(), Matchers.equalTo("three")); assertThat(store.get(4), is(nullValue())); assertThat(store.get(5), is(nullValue())); assertThat(store.get(6), is(nullValue())); @@ -279,19 +278,19 @@ public void testBulkComputeIfAbsentDoesNotOverridePresentKeys() throws Exception }); assertThat(result.size(), is(6)); - assertThat(result.get(1).value(), Matchers.equalTo("one")); - assertThat(result.get(2).value(), Matchers.equalTo("two")); - assertThat(result.get(3).value(), Matchers.equalTo("three")); - assertThat(result.get(4).value(), Matchers.equalTo("quatre")); - assertThat(result.get(5).value(), Matchers.equalTo("cinq")); - assertThat(result.get(6).value(), Matchers.equalTo("six")); - - assertThat(store.get(1).value(), Matchers.equalTo("one")); - assertThat(store.get(2).value(), Matchers.equalTo("two")); - assertThat(store.get(3).value(), Matchers.equalTo("three")); - assertThat(store.get(4).value(), Matchers.equalTo("quatre")); - assertThat(store.get(5).value(), Matchers.equalTo("cinq")); - assertThat(store.get(6).value(), Matchers.equalTo("six")); + assertThat(result.get(1).get(), Matchers.equalTo("one")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); + assertThat(result.get(3).get(), Matchers.equalTo("three")); + assertThat(result.get(4).get(), Matchers.equalTo("quatre")); + assertThat(result.get(5).get(), Matchers.equalTo("cinq")); + assertThat(result.get(6).get(), Matchers.equalTo("six")); + + assertThat(store.get(1).get(), Matchers.equalTo("one")); + assertThat(store.get(2).get(), Matchers.equalTo("two")); + assertThat(store.get(3).get(), Matchers.equalTo("three")); + assertThat(store.get(4).get(), Matchers.equalTo("quatre")); + assertThat(store.get(5).get(), Matchers.equalTo("cinq")); + assertThat(store.get(6).get(), Matchers.equalTo("six")); } @Test @@ -321,13 +320,13 @@ public void testBulkComputeIfAbsentDoNothingOnNullValues() throws Exception { }); assertThat(result.size(), is(3)); - assertThat(result.get(2).value(), Matchers.equalTo("two")); - assertThat(result.get(1).value(), Matchers.equalTo("one")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); + assertThat(result.get(1).get(), Matchers.equalTo("one")); assertThat(result.get(5), is(nullValue())); - assertThat(store.get(1).value(), Matchers.equalTo("one")); - assertThat(store.get(2).value(), Matchers.equalTo("two")); - assertThat(store.get(3).value(), Matchers.equalTo("three")); + assertThat(store.get(1).get(), Matchers.equalTo("one")); + assertThat(store.get(2).get(), Matchers.equalTo("two")); + assertThat(store.get(3).get(), Matchers.equalTo("three")); assertThat(store.get(5), is(nullValue())); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java index 1f3643042a..b5e5e8f050 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java @@ -75,7 +75,7 @@ public void testKeyCopierCalledOnGetOrComputeIfAbsent() throws Exception { ValueHolder computed = store.getOrComputeIfAbsent(1L, key -> new AbstractValueHolder(-1, -1) { @Override - public Long value() { + public Long get() { return key * 1000L; } @@ -84,7 +84,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } }); - assertThat(computed.value(), is(1000L)); + assertThat(computed.get(), is(1000L)); assertThat(keyCopier.copyForWriteCount, is(1)); assertThat(keyCopier.copyForReadCount, is(0)); } @@ -125,7 +125,7 @@ public void testValueUniqueObject() throws Exception { value.clear(); ValueHolder valueHolder = store.get(key); - if (valueHolder.value() == value || ! valueHolder.value().equals(Collections.singletonList("value"))) { + if (valueHolder.get() == value || ! valueHolder.get().equals(Collections.singletonList("value"))) { throw new AssertionError(); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java index e9a84a589b..e8668d228f 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java @@ -87,7 +87,7 @@ public void testFaultsDoNotGetToEvictionAdvisor() throws StoreAccessException { semaphore.acquireUninterruptibly(); return new OnHeapValueHolder(0, 0, false) { @Override - public String value() { + public String get() { return key; } }; @@ -180,12 +180,12 @@ public static class OnHeapStoreForTests extends OnHeapStore { @SuppressWarnings("unchecked") public OnHeapStoreForTests(final Configuration config, final TimeSource timeSource) { - super(config, timeSource, DEFAULT_COPIER, DEFAULT_COPIER, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); + super(config, timeSource, DEFAULT_COPIER, DEFAULT_COPIER, new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); } @SuppressWarnings("unchecked") public OnHeapStoreForTests(final Configuration config, final TimeSource timeSource, final SizeOfEngine engine) { - super(config, timeSource, DEFAULT_COPIER, DEFAULT_COPIER, engine, NullStoreEventDispatcher.nullStoreEventDispatcher()); + super(config, timeSource, DEFAULT_COPIER, DEFAULT_COPIER, engine, NullStoreEventDispatcher.nullStoreEventDispatcher()); } private boolean enforceCapacityWasCalled = false; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java index 575cacd21a..0b2703b008 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java @@ -101,7 +101,7 @@ public Key copyForWrite(Key obj) { } }; - store = new OnHeapStore<>(config, SystemTimeSource.INSTANCE, keyCopier, new IdentityCopier<>(), new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); + store = new OnHeapStore<>(config, SystemTimeSource.INSTANCE, keyCopier, new IdentityCopier<>(), new NoopSizeOfEngine(), NullStoreEventDispatcher.nullStoreEventDispatcher()); } @Test @@ -114,11 +114,11 @@ public void testPutAndGet() throws StoreAccessException { Store.ValueHolder firstStoreValue = store.get(KEY); Store.ValueHolder secondStoreValue = store.get(copyKey); if (copyForWrite) { - assertThat(firstStoreValue.value(), is(VALUE)); + assertThat(firstStoreValue.get(), is(VALUE)); assertThat(secondStoreValue, nullValue()); } else { assertThat(firstStoreValue, nullValue()); - assertThat(secondStoreValue.value(), is(VALUE)); + assertThat(secondStoreValue.get(), is(VALUE)); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java index da8e3bf87f..8eb89d34e5 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java @@ -110,42 +110,42 @@ public void testPutAndGet() throws StoreAccessException { Store.ValueHolder firstStoreValue = store.get(KEY); Store.ValueHolder secondStoreValue = store.get(KEY); - compareValues(VALUE, firstStoreValue.value()); - compareValues(VALUE, secondStoreValue.value()); - compareReadValues(firstStoreValue.value(), secondStoreValue.value()); + compareValues(VALUE, firstStoreValue.get()); + compareValues(VALUE, secondStoreValue.get()); + compareReadValues(firstStoreValue.get(), secondStoreValue.get()); } @Test public void testCompute() throws StoreAccessException { final Store.ValueHolder firstValue = store.compute(KEY, (aLong, value) -> VALUE); store.compute(KEY, (aLong, value) -> { - compareReadValues(value, firstValue.value()); + compareReadValues(value, firstValue.get()); return value; }); - compareValues(VALUE, firstValue.value()); + compareValues(VALUE, firstValue.get()); } @Test public void testComputeWithoutReplaceEqual() throws StoreAccessException { final Store.ValueHolder firstValue = store.compute(KEY, (aLong, value) -> VALUE, NOT_REPLACE_EQUAL); store.compute(KEY, (aLong, value) -> { - compareReadValues(value, firstValue.value()); + compareReadValues(value, firstValue.get()); return value; }, NOT_REPLACE_EQUAL); - compareValues(VALUE, firstValue.value()); + compareValues(VALUE, firstValue.get()); } @Test public void testComputeWithReplaceEqual() throws StoreAccessException { final Store.ValueHolder firstValue = store.compute(KEY, (aLong, value) -> VALUE, REPLACE_EQUAL); store.compute(KEY, (aLong, value) -> { - compareReadValues(value, firstValue.value()); + compareReadValues(value, firstValue.get()); return value; }, REPLACE_EQUAL); - compareValues(VALUE, firstValue.value()); + compareValues(VALUE, firstValue.get()); } @Test @@ -155,38 +155,38 @@ public void testComputeIfAbsent() throws StoreAccessException { fail("There should have been a mapping"); return null; }); - compareValues(VALUE, computedValue.value()); - compareReadValues(computedValue.value(), secondComputedValue.value()); + compareValues(VALUE, computedValue.get()); + compareReadValues(computedValue.get(), secondComputedValue.get()); } @Test public void testBulkCompute() throws StoreAccessException { final Map> results = store.bulkCompute(singleton(KEY), entries -> singletonMap(KEY, VALUE).entrySet()); store.bulkCompute(singleton(KEY), entries -> { - compareReadValues(results.get(KEY).value(), entries.iterator().next().getValue()); + compareReadValues(results.get(KEY).get(), entries.iterator().next().getValue()); return entries; }); - compareValues(VALUE, results.get(KEY).value()); + compareValues(VALUE, results.get(KEY).get()); } @Test public void testBulkComputeWithoutReplaceEqual() throws StoreAccessException { final Map> results = store.bulkCompute(singleton(KEY), entries -> singletonMap(KEY, VALUE).entrySet(), NOT_REPLACE_EQUAL); store.bulkCompute(singleton(KEY), entries -> { - compareReadValues(results.get(KEY).value(), entries.iterator().next().getValue()); + compareReadValues(results.get(KEY).get(), entries.iterator().next().getValue()); return entries; }, NOT_REPLACE_EQUAL); - compareValues(VALUE, results.get(KEY).value()); + compareValues(VALUE, results.get(KEY).get()); } @Test public void testBulkComputeWithReplaceEqual() throws StoreAccessException { final Map> results = store.bulkCompute(singleton(KEY), entries -> singletonMap(KEY, VALUE).entrySet(), REPLACE_EQUAL); store.bulkCompute(singleton(KEY), entries -> { - compareReadValues(results.get(KEY).value(), entries.iterator().next().getValue()); + compareReadValues(results.get(KEY).get(), entries.iterator().next().getValue()); return entries; }, REPLACE_EQUAL); - compareValues(VALUE, results.get(KEY).value()); + compareValues(VALUE, results.get(KEY).get()); } @Test @@ -196,8 +196,8 @@ public void testBulkComputeIfAbsent() throws StoreAccessException { fail("There should have been a mapping!"); return null; }); - compareValues(VALUE, results.get(KEY).value()); - compareReadValues(results.get(KEY).value(), secondResults.get(KEY).value()); + compareValues(VALUE, results.get(KEY).get()); + compareReadValues(results.get(KEY).get(), secondResults.get(KEY).get()); } @Test @@ -207,7 +207,7 @@ public void testIterator() throws StoreAccessException { assertThat(iterator.hasNext(), is(true)); while (iterator.hasNext()) { Cache.Entry> entry = iterator.next(); - compareValues(entry.getValue().value(), VALUE); + compareValues(entry.getValue().get(), VALUE); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java index 7de06463df..d7f9eefe1c 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OnHeapStoreBulkMethodsTest.java @@ -54,7 +54,7 @@ protected Store.Configuration mockStoreConfig() { } @SuppressWarnings("unchecked") - protected OnHeapStore newStore() { + protected OnHeapStore newStore() { Store.Configuration configuration = mockStoreConfig(); return new OnHeapStore(configuration, SystemTimeSource.INSTANCE, DEFAULT_COPIER, DEFAULT_COPIER, new DefaultSizeOfEngine(Long.MAX_VALUE, Long.MAX_VALUE), NullStoreEventDispatcher.nullStoreEventDispatcher()); @@ -103,17 +103,17 @@ public void testBulkComputeFunctionGetsValuesOfEntries() throws Exception { check.put(5, 0); check.put(6, 0); - assertThat(result.get(1).value(), Matchers.is(check.get(1))); - assertThat(result.get(2).value(), Matchers.is(check.get(2))); - assertThat(result.get(3).value(), Matchers.is(check.get(3))); + assertThat(result.get(1).get(), Matchers.is(check.get(1))); + assertThat(result.get(2).get(), Matchers.is(check.get(2))); + assertThat(result.get(3).get(), Matchers.is(check.get(3))); assertThat(result.get(4), nullValue()); - assertThat(result.get(5).value(), Matchers.is(check.get(5))); - assertThat(result.get(6).value(), Matchers.is(check.get(6))); + assertThat(result.get(5).get(), Matchers.is(check.get(5))); + assertThat(result.get(6).get(), Matchers.is(check.get(6))); for (Number key : check.keySet()) { final Store.ValueHolder holder = store.get(key); if(holder != null) { - check.remove(key, holder.value()); + check.remove(key, holder.get()); } } assertThat(check.size(), is(1)); diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java index 5636fd05bb..d3c17066ca 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/OversizeMappingTest.java @@ -109,7 +109,7 @@ private static void assertNullMapping(OnHeapStore store) throws } private static void assertNotNullMapping(OnHeapStore store) throws Exception { - assertThat(store.get(KEY).value(), equalTo(VALUE)); + assertThat(store.get(KEY).get(), equalTo(VALUE)); } @Test diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolderTest.java index a2bc0085fb..99fe7fe8fb 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/CopiedOnHeapValueHolderTest.java @@ -35,7 +35,7 @@ public void testValueByValue() throws Exception { CopiedOnHeapValueHolder valueHolder = new CopiedOnHeapValueHolder<>(person, -1, false, copier); person.age = 25; - assertNotSame(person, valueHolder.value()); + assertNotSame(person, valueHolder.get()); } @Test @@ -44,7 +44,7 @@ public void testValueByRef() throws Exception { CopiedOnHeapValueHolder valueHolder = new CopiedOnHeapValueHolder<>(person, -1, false, new IdentityCopier<>()); person.age = 25; - assertSame(person, valueHolder.value()); + assertSame(person, valueHolder.get()); } private static class Person { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolderTest.java index a908f15ccd..bf71cd378a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/holders/SerializedOnHeapValueHolderTest.java @@ -46,9 +46,9 @@ public void testValue() { String o = "foo"; ValueHolder vh1 = newValueHolder(o); ValueHolder vh2 = newValueHolder(o); - assertFalse(vh1.value() == vh2.value()); - assertEquals(vh1.value(), vh2.value()); - assertNotSame(vh1.value(), vh1.value()); + assertFalse(vh1.get() == vh2.get()); + assertEquals(vh1.get(), vh2.get()); + assertNotSame(vh1.get(), vh1.get()); } @Test @@ -56,10 +56,10 @@ public void testHashCode() { ValueHolder vh1 = newValueHolder(10); ValueHolder vh2 = newValueHolder(10); // make sure reading the value multiple times doesn't change the hashcode - vh1.value(); - vh1.value(); - vh2.value(); - vh2.value(); + vh1.get(); + vh1.get(); + vh2.get(); + vh2.get(); assertThat(vh1.hashCode(), is(vh2.hashCode())); } @@ -87,9 +87,9 @@ public void testSerializerGetsDifferentByteBufferOnRead() { final SerializedOnHeapValueHolder valueHolder = new SerializedOnHeapValueHolder<>("test it!", System .currentTimeMillis(), false, serializer); - new Thread(valueHolder::value).start(); + new Thread(valueHolder::get).start(); - valueHolder.value(); + valueHolder.get(); } private static class ReadExchangeSerializer implements Serializer { diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java index cbd8b9cd74..6947fc3cfe 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java @@ -17,7 +17,6 @@ package org.ehcache.impl.internal.store.offheap; import org.ehcache.Cache; -import org.ehcache.ValueSupplier; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; @@ -50,9 +49,9 @@ import java.util.Random; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import static org.ehcache.config.builders.ExpiryPolicyBuilder.expiry; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; import static org.ehcache.impl.internal.util.Matchers.valueHeld; import static org.ehcache.impl.internal.util.StatisticsTestUtils.validateStats; import static org.hamcrest.CoreMatchers.equalTo; @@ -100,7 +99,7 @@ public void testGetAndRemoveValue() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.noExpiration()); offHeapStore.put("1", "one"); - assertThat(offHeapStore.getAndRemove("1").value(), equalTo("one")); + assertThat(offHeapStore.getAndRemove("1").get(), equalTo("one")); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.HIT_REMOVED)); assertThat(offHeapStore.get("1"), is(nullValue())); } @@ -118,7 +117,7 @@ public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { timeSource.advanceTime(20); assertThat(offHeapStore.getAndRemove("1"), is(nullValue())); - assertThat(invalidated.get().value(), equalTo("one")); + assertThat(invalidated.get().get(), equalTo("one")); assertThat(invalidated.get().isExpired(timeSource.getTimeMillis(), TimeUnit.MILLISECONDS), is(true)); assertThat(getExpirationStatistic(offHeapStore).count(StoreOperationOutcomes.ExpirationOutcome.SUCCESS), is(1L)); } @@ -127,7 +126,7 @@ public void testGetAndRemoveExpiredElementReturnsNull() throws Exception { public void testInstallMapping() throws Exception { offHeapStore = createAndInitStore(timeSource, ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(15L))); - assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).value(), equalTo("one")); + assertThat(offHeapStore.installMapping("1", key -> new SimpleValueHolder<>("one", timeSource.getTimeMillis(), 15)).get(), equalTo("one")); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InstallMappingOutcome.PUT)); @@ -163,7 +162,7 @@ public void testInvalidateKeyPresent() throws Exception { offHeapStore.setInvalidationListener((key, valueHolder) -> invalidated.set(valueHolder)); offHeapStore.invalidate("1"); - assertThat(invalidated.get().value(), equalTo("one")); + assertThat(invalidated.get().get(), equalTo("one")); validateStats(offHeapStore, EnumSet.of(LowerCachingTierOperationsOutcome.InvalidateOutcome.REMOVED)); assertThat(offHeapStore.get("1"), is(nullValue())); @@ -227,9 +226,9 @@ public void testFlushUpdatesAccessStats() throws StoreAccessException { offHeapStore.put(key, value); final Store.ValueHolder secondValueHolder = offHeapStore.getAndFault(key); timeSource.advanceTime(10); - ((AbstractValueHolder) firstValueHolder).accessed(timeSource.getTimeMillis(), expiry.getExpiryForAccess(key, supplierOf(value))); + ((AbstractValueHolder) firstValueHolder).accessed(timeSource.getTimeMillis(), expiry.getExpiryForAccess(key, () -> value)); timeSource.advanceTime(10); - ((AbstractValueHolder) secondValueHolder).accessed(timeSource.getTimeMillis(), expiry.getExpiryForAccess(key, supplierOf(value))); + ((AbstractValueHolder) secondValueHolder).accessed(timeSource.getTimeMillis(), expiry.getExpiryForAccess(key, () -> value)); assertThat(offHeapStore.flush(key, new DelegatingValueHolder<>(firstValueHolder)), is(false)); assertThat(offHeapStore.flush(key, new DelegatingValueHolder<>(secondValueHolder)), is(true)); timeSource.advanceTime(10); // this should NOT affect @@ -293,7 +292,7 @@ public void testGetWithExpiryOnAccess() throws Exception { } @Test - public void testExpiryCreateException() throws Exception{ + public void testExpiryCreateException() throws Exception { offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { @@ -301,12 +300,12 @@ public Duration getExpiryForCreation(String key, String value) { } @Override - public Duration getExpiryForAccess(String key, ValueSupplier value) { + public Duration getExpiryForAccess(String key, Supplier value) { throw new AssertionError(); } @Override - public Duration getExpiryForUpdate(String key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(String key, Supplier oldValue, String newValue) { throw new AssertionError(); } }); @@ -315,7 +314,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o } @Test - public void testExpiryAccessException() throws Exception{ + public void testExpiryAccessException() throws Exception { offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { @@ -323,12 +322,12 @@ public Duration getExpiryForCreation(String key, String value) { } @Override - public Duration getExpiryForAccess(String key, ValueSupplier value) { + public Duration getExpiryForAccess(String key, Supplier value) { throw new RuntimeException(); } @Override - public Duration getExpiryForUpdate(String key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(String key, Supplier oldValue, String newValue) { return null; } }); @@ -339,7 +338,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o } @Test - public void testExpiryUpdateException() throws Exception{ + public void testExpiryUpdateException() throws Exception { offHeapStore = createAndInitStore(timeSource, new ExpiryPolicy() { @Override public Duration getExpiryForCreation(String key, String value) { @@ -347,12 +346,12 @@ public Duration getExpiryForCreation(String key, String value) { } @Override - public Duration getExpiryForAccess(String key, ValueSupplier value) { + public Duration getExpiryForAccess(String key, Supplier value) { return ExpiryPolicy.INFINITE; } @Override - public Duration getExpiryForUpdate(String key, ValueSupplier oldValue, String newValue) { + public Duration getExpiryForUpdate(String key, Supplier oldValue, String newValue) { if (timeSource.getTimeMillis() > 0) { throw new RuntimeException(); } @@ -361,7 +360,7 @@ public Duration getExpiryForUpdate(String key, ValueSupplier o }); offHeapStore.put("key", "value"); - assertThat(offHeapStore.get("key").value(), is("value")); + assertThat(offHeapStore.get("key").get(), is("value")); timeSource.advanceTime(1000); offHeapStore.put("key", "newValue"); assertNull(offHeapStore.get("key")); @@ -549,7 +548,7 @@ private OperationStatistic getExpirati TreeNode treeNode = statisticsManager.queryForSingleton(QueryBuilder.queryBuilder() .descendants() .filter(org.terracotta.context.query.Matchers.context( - org.terracotta.context.query.Matchers.allOf(org.terracotta.context.query.Matchers.identifier(org.terracotta.context.query.Matchers + org.terracotta.context.query.Matchers.allOf(org.terracotta.context.query.Matchers.identifier(org.terracotta.context.query.Matchers .subclassOf(OperationStatistic.class)), org.terracotta.context.query.Matchers.attributes(org.terracotta.context.query.Matchers.hasAttribute("name", "expiration"))))) .build()); @@ -587,8 +586,8 @@ public DelegatingValueHolder(final Store.ValueHolder valueHolder) { } @Override - public T value() { - return valueHolder.value(); + public T get() { + return valueHolder.get(); } @Override @@ -642,7 +641,7 @@ protected TimeUnit nativeTimeUnit() { } @Override - public T value() { + public T get() { return value; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolderTest.java index b25a893be4..f3eb983d42 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BasicOffHeapValueHolderTest.java @@ -38,7 +38,7 @@ public void setUp() { @Test public void testCanAccessValue() { - assertThat(valueHolder.value(), is(value)); + assertThat(valueHolder.get(), is(value)); } @Test(expected = UnsupportedOperationException.class) diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolderTest.java index 56f393f518..bad91aec6e 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/BinaryOffHeapValueHolderTest.java @@ -50,7 +50,7 @@ public void testCanAccessBinaryValue() throws ClassNotFoundException { @Test public void testCanAccessValue() { - assertThat(valueHolder.value(), is(value)); + assertThat(valueHolder.get(), is(value)); } @Test(expected = UnsupportedOperationException.class) diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolderTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolderTest.java index 93830501cb..8a042290c7 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/LazyOffHeapValueHolderTest.java @@ -42,7 +42,7 @@ public void testDelayedDeserialization() { valueHolder.detach(); serialized.clear(); - assertThat(valueHolder.value(), is(testValue)); + assertThat(valueHolder.get(), is(testValue)); } @Test diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java index 879f4aff7d..dae21e8655 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java @@ -212,7 +212,7 @@ public void testPutIfAbsent() throws Exception { // 4. Test Thread receives a value from putIfAbsent. We would expect the get to receive the same value right after // a. Test Thread -> TieredStore.putIfAbsent // b. Test Thread -> AuthoritativeTierMock.putIfAbsent - returns VALUE - assertThat(putIfAbsentToTieredStore().value(), is(VALUE)); + assertThat(putIfAbsentToTieredStore().get(), is(VALUE)); // 5. Test Thread -> TieredStore.get() // If Test Thread bugged -> Fault.get() - synchronized - blocked on the fault because thread 2 already locks the fault @@ -222,7 +222,7 @@ public void testPutIfAbsent() throws Exception { // These assertions will in fact work most of the time even if a failure occurred. Because as soon as the latches are // released by thread 3, the thread 2 will invalidate the fault assertThat(value, notNullValue()); - assertThat(value.value(), is(VALUE)); + assertThat(value.get(), is(VALUE)); // If the Test thread was blocked, Thread 3 will eventually flag the failure assertThat(failed, is(false)); @@ -251,7 +251,7 @@ public void testRemoveKeyValue() throws Exception { // Else Test Thread fixed -> new Fault ... correct value Store.ValueHolder value = getFromTieredStore(); assertThat(value, notNullValue()); - assertThat(value.value(), is(VALUE)); + assertThat(value.get(), is(VALUE)); assertThat(failed, is(false)); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java index 37ee936b26..48029eb688 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreSPITest.java @@ -225,7 +225,7 @@ public Store.ValueHolder newValueHolder(final String value) { return new Store.ValueHolder() { @Override - public String value() { + public String get() { return value; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java index aa87d16da6..bee5aac2d6 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java @@ -39,7 +39,6 @@ import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import java.util.AbstractMap; @@ -98,7 +97,7 @@ public void testGetHitsCachingTier() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.get(1).value(), Matchers.equalTo("one")); + assertThat(tieredStore.get(1).get(), Matchers.equalTo("one")); verify(numberAuthoritativeTier, times(0)).getAndFault(any(Number.class)); } @@ -116,7 +115,7 @@ public void testGetHitsAuthoritativeTier() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.get(1).value(), Matchers.equalTo("one")); + assertThat(tieredStore.get(1).get(), Matchers.equalTo("one")); verify(numberCachingTier, times(1)).getOrComputeIfAbsent(eq(1), any(Function.class)); verify(numberAuthoritativeTier, times(1)).getAndFault(any(Number.class)); @@ -166,7 +165,7 @@ public void testPutIfAbsent_whenPresent() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.putIfAbsent(1, "one").value(), Matchers.equalTo("un")); + assertThat(tieredStore.putIfAbsent(1, "one").get(), Matchers.equalTo("un")); verify(numberCachingTier, times(1)).invalidate(1); verify(numberAuthoritativeTier, times(1)).putIfAbsent(1, "one"); @@ -212,7 +211,7 @@ public void testReplace2Args_replaces() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.replace(1, "one").value(), Matchers.equalTo("un")); + assertThat(tieredStore.replace(1, "one").get(), Matchers.equalTo("un")); verify(numberCachingTier, times(1)).invalidate(eq(1)); verify(numberAuthoritativeTier, times(1)).replace(eq(1), eq("one")); @@ -275,7 +274,7 @@ public void testCompute2Args() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.compute(1, (number, charSequence) -> "one").value(), Matchers.equalTo("one")); + assertThat(tieredStore.compute(1, (number, charSequence) -> "one").get(), Matchers.equalTo("one")); verify(numberCachingTier, times(1)).invalidate(any(Number.class)); verify(numberAuthoritativeTier, times(1)).compute(eq(1), any(BiFunction.class)); @@ -292,7 +291,7 @@ public void testCompute3Args() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.compute(1, (number, charSequence) -> "one", () -> true).value(), Matchers.equalTo("one")); + assertThat(tieredStore.compute(1, (number, charSequence) -> "one", () -> true).get(), Matchers.equalTo("one")); verify(numberCachingTier, times(1)).invalidate(any(Number.class)); verify(numberAuthoritativeTier, times(1)).compute(eq(1), any(BiFunction.class), any(Supplier.class)); @@ -314,7 +313,7 @@ public void testComputeIfAbsent_computes() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.computeIfAbsent(1, number -> "one").value(), Matchers.equalTo("one")); + assertThat(tieredStore.computeIfAbsent(1, number -> "one").get(), Matchers.equalTo("one")); verify(numberCachingTier, times(1)).getOrComputeIfAbsent(eq(1), any(Function.class)); verify(numberAuthoritativeTier, times(1)).computeIfAbsentAndFault(eq(1), any(Function.class)); @@ -328,7 +327,7 @@ public void testComputeIfAbsent_doesNotCompute() throws Exception { TieredStore tieredStore = new TieredStore<>(numberCachingTier, numberAuthoritativeTier); - assertThat(tieredStore.computeIfAbsent(1, number -> "one").value(), Matchers.equalTo("one")); + assertThat(tieredStore.computeIfAbsent(1, number -> "one").get(), Matchers.equalTo("one")); verify(numberCachingTier, times(1)).getOrComputeIfAbsent(eq(1), any(Function.class)); verify(numberAuthoritativeTier, times(0)).computeIfAbsentAndFault(eq(1), any(Function.class)); @@ -362,9 +361,9 @@ public void testBulkCompute2Args() throws Exception { .asList(newMapEntry(1, "one"), newMapEntry(2, "two"), newMapEntry(3, "three")))); assertThat(result.size(), is(3)); - assertThat(result.get(1).value(), Matchers.equalTo("one")); - assertThat(result.get(2).value(), Matchers.equalTo("two")); - assertThat(result.get(3).value(), Matchers.equalTo("three")); + assertThat(result.get(1).get(), Matchers.equalTo("one")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); + assertThat(result.get(3).get(), Matchers.equalTo("three")); verify(numberCachingTier, times(1)).invalidate(1); verify(numberCachingTier, times(1)).invalidate(2); @@ -401,9 +400,9 @@ public void testBulkCompute3Args() throws Exception { .asList(newMapEntry(1, "one"), newMapEntry(2, "two"), newMapEntry(3, "three"))), () -> true); assertThat(result.size(), is(3)); - assertThat(result.get(1).value(), Matchers.equalTo("one")); - assertThat(result.get(2).value(), Matchers.equalTo("two")); - assertThat(result.get(3).value(), Matchers.equalTo("three")); + assertThat(result.get(1).get(), Matchers.equalTo("one")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); + assertThat(result.get(3).get(), Matchers.equalTo("three")); verify(numberCachingTier, times(1)).invalidate(1); verify(numberCachingTier, times(1)).invalidate(2); @@ -439,9 +438,9 @@ public void testBulkComputeIfAbsent() throws Exception { Map> result = tieredStore.bulkComputeIfAbsent(new HashSet(Arrays.asList(1, 2, 3)), numbers -> Arrays.asList(newMapEntry(1, "one"), newMapEntry(2, "two"), newMapEntry(3, "three"))); assertThat(result.size(), is(3)); - assertThat(result.get(1).value(), Matchers.equalTo("one")); - assertThat(result.get(2).value(), Matchers.equalTo("two")); - assertThat(result.get(3).value(), Matchers.equalTo("three")); + assertThat(result.get(1).get(), Matchers.equalTo("one")); + assertThat(result.get(2).get(), Matchers.equalTo("two")); + assertThat(result.get(3).get(), Matchers.equalTo("three")); verify(numberCachingTier, times(1)).invalidate(1); verify(numberCachingTier, times(1)).invalidate(2); @@ -576,7 +575,7 @@ public Store.ValueHolder newValueHolder(final CharSequence v) { return new Store.ValueHolder() { @Override - public CharSequence value() { + public CharSequence get() { return v; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java index 2f5260a8b7..892a212c7d 100755 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreWith3TiersSPITest.java @@ -239,7 +239,7 @@ public Store.ValueHolder newValueHolder(final String value) { return new Store.ValueHolder() { @Override - public String value() { + public String get() { return value; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/util/Matchers.java b/impl/src/test/java/org/ehcache/impl/internal/util/Matchers.java index bd2b3564ff..0b15d42f4d 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/util/Matchers.java +++ b/impl/src/test/java/org/ehcache/impl/internal/util/Matchers.java @@ -17,7 +17,6 @@ package org.ehcache.impl.internal.util; import org.ehcache.Cache; -import org.ehcache.ValueSupplier; import org.ehcache.event.EventType; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEvent; @@ -25,27 +24,14 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; +import java.util.function.Supplier; + /** * * @author cdennis */ public class Matchers { - public static Matcher> hasKey(final K key) { - return new TypeSafeMatcher>() { - - @Override - protected boolean matchesSafely(Cache item) { - return item.containsKey(key); - } - - @Override - public void describeTo(Description description) { - description.appendText("cache containing key '").appendValue(key).appendText("'"); - } - }; - } - public static Matcher> hasEntry(final K key, final V value) { return new TypeSafeMatcher>() { @@ -65,7 +51,7 @@ public static Matcher> valueHeld(final V value) { return new TypeSafeMatcher>() { @Override protected boolean matchesSafely(Store.ValueHolder item) { - return item.value().equals(value); + return item.get().equals(value); } @Override @@ -75,11 +61,11 @@ public void describeTo(Description description) { }; } - public static Matcher> holding(final V value) { - return new TypeSafeMatcher>() { + public static Matcher> holding(final V value) { + return new TypeSafeMatcher>() { @Override - protected boolean matchesSafely(ValueSupplier item) { - return item.value().equals(value); + protected boolean matchesSafely(Supplier item) { + return item.get().equals(value); } @Override diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockValueCombinedCopier.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockValueCombinedCopier.java index 0f97a926f2..359ce9a1a5 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockValueCombinedCopier.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockValueCombinedCopier.java @@ -36,7 +36,7 @@ public SoftLock copyForRead(SoftLock obj) { T oldValue = valueCopier.copyForRead(obj.getOldValue()); XAValueHolder valueHolder = obj.getNewValueHolder(); XAValueHolder newValueHolder = valueHolder == null ? null : new XAValueHolder<>(valueHolder, valueCopier.copyForRead(valueHolder - .value())); + .get())); return new SoftLock<>(obj.getTransactionId(), oldValue, newValueHolder); } @@ -45,7 +45,7 @@ public SoftLock copyForWrite(SoftLock obj) { T oldValue = valueCopier.copyForWrite(obj.getOldValue()); XAValueHolder valueHolder = obj.getNewValueHolder(); XAValueHolder newValueHolder = valueHolder == null ? null : new XAValueHolder<>(valueHolder, valueCopier.copyForWrite(valueHolder - .value())); + .get())); return new SoftLock<>(obj.getTransactionId(), oldValue, newValueHolder); } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java index 11bbbd936b..cc9a301d46 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java @@ -17,7 +17,6 @@ package org.ehcache.transactions.xa.internal; import org.ehcache.Cache; -import org.ehcache.ValueSupplier; import org.ehcache.config.ResourceType; import org.ehcache.core.CacheConfigurationChangeListener; import org.ehcache.config.EvictionAdvisor; @@ -78,7 +77,6 @@ import static org.ehcache.core.spi.service.ServiceUtils.findAmongst; import static org.ehcache.core.spi.service.ServiceUtils.findSingletonAmongst; -import static org.ehcache.core.internal.util.ValueSuppliers.supplierOf; /** * A {@link Store} implementation wrapping another {@link Store} driven by a JTA @@ -203,7 +201,7 @@ public ValueHolder get(K key) throws StoreAccessException { return null; } - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(softLock.getOldValue())); return null; @@ -219,7 +217,7 @@ public boolean containsKey(K key) throws StoreAccessException { return getCurrentContext().newValueHolderOf(key) != null; } ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); - return softLockValueHolder != null && softLockValueHolder.value().getTransactionId() == null && softLockValueHolder.value().getOldValue() != null; + return softLockValueHolder != null && softLockValueHolder.get().getTransactionId() == null && softLockValueHolder.get().getOldValue() != null; } @Override @@ -235,7 +233,7 @@ public PutStatus put(K key, V value) throws StoreAccessException { ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); if (softLockValueHolder != null) { - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(softLock.getOldValue())); } else { @@ -266,7 +264,7 @@ public boolean remove(K key) throws StoreAccessException { ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); boolean status = false; if (softLockValueHolder != null) { - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(softLock.getOldValue())); } else { @@ -294,7 +292,7 @@ public ValueHolder putIfAbsent(K key, V value) throws StoreAccessException { ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); if (softLockValueHolder != null) { - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(softLock.getOldValue())); return null; @@ -327,7 +325,7 @@ public RemoveStatus remove(K key, V value) throws StoreAccessException { ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); if (softLockValueHolder != null) { - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(softLock.getOldValue())); return RemoveStatus.KEY_MISSING; @@ -361,7 +359,7 @@ public ValueHolder replace(K key, V value) throws StoreAccessException { ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); if (softLockValueHolder != null) { - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(softLock.getOldValue())); return null; @@ -396,7 +394,7 @@ public ReplaceStatus replace(K key, V oldValue, V newValue) throws StoreAccessEx ValueHolder> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); if (softLockValueHolder != null) { - SoftLock softLock = softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder.get(); V previousValue = softLock.getOldValue(); if (isInDoubt(softLock)) { currentContext.addCommand(key, new StoreEvictCommand<>(previousValue)); @@ -476,10 +474,10 @@ public ValueHolder getValue() { if (!transactionContextFactory.isTouched(transactionId, next.getKey())) { ValueHolder> valueHolder = next.getValue(); - SoftLock softLock = valueHolder.value(); + SoftLock softLock = valueHolder.get(); final XAValueHolder xaValueHolder; if (softLock.getTransactionId() == transactionId) { - xaValueHolder = new XAValueHolder<>(valueHolder, softLock.getNewValueHolder().value()); + xaValueHolder = new XAValueHolder<>(valueHolder, softLock.getNewValueHolder().get()); } else if (isInDoubt(softLock)) { continue; } else { @@ -537,7 +535,7 @@ public ValueHolder compute(K key, BiFunction> softLockValueHolder = getSoftLockValueHolderFromUnderlyingStore(key); - SoftLock softLock = softLockValueHolder == null ? null : softLockValueHolder.value(); + SoftLock softLock = softLockValueHolder == null ? null : softLockValueHolder.get(); V oldValue = softLock == null ? null : softLock.getOldValue(); V newValue = mappingFunction.apply(key, oldValue); XAValueHolder xaValueHolder = newValue == null ? null : new XAValueHolder<>(newValue, timeSource.getTimeMillis()); @@ -594,14 +592,14 @@ public ValueHolder computeIfAbsent(K key, final Function(softLockValueHolder.value().getOldValue())); - xaValueHolder = new XAValueHolder<>(softLockValueHolder, softLockValueHolder.value().getNewValueHolder().value()); + } else if (isInDoubt(softLockValueHolder.get())) { + currentContext.addCommand(key, new StoreEvictCommand<>(softLockValueHolder.get().getOldValue())); + xaValueHolder = new XAValueHolder<>(softLockValueHolder, softLockValueHolder.get().getNewValueHolder().get()); } else { if (updated) { xaValueHolder = currentContext.newValueHolderOf(key); } else { - xaValueHolder = new XAValueHolder<>(softLockValueHolder, softLockValueHolder.value().getOldValue()); + xaValueHolder = new XAValueHolder<>(softLockValueHolder, softLockValueHolder.get().getOldValue()); } } @@ -801,15 +799,15 @@ public Duration getExpiryForCreation(K key, SoftLock softLock) { } @Override - public Duration getExpiryForAccess(K key, final ValueSupplier> softLock) { - if (softLock.value().getTransactionId() != null) { + public Duration getExpiryForAccess(K key, Supplier> softLock) { + if (softLock.get().getTransactionId() != null) { // phase 1 prepare, access -> forever return ExpiryPolicy.INFINITE; } else { // phase 2 commit, or during a TX's lifetime, access -> some time Duration duration; try { - duration = configuredExpiry.getExpiryForAccess(key, supplierOf(softLock.value().getOldValue())); + duration = configuredExpiry.getExpiryForAccess(key, () -> softLock.get().getOldValue()); } catch (RuntimeException re) { LOGGER.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return Duration.ZERO; @@ -819,8 +817,8 @@ public Duration getExpiryForAccess(K key, final ValueSupplier> oldSoftLockSupplier, SoftLock newSoftLock) { - SoftLock oldSoftLock = oldSoftLockSupplier.value(); + public Duration getExpiryForUpdate(K key, Supplier> oldSoftLockSupplier, SoftLock newSoftLock) { + SoftLock oldSoftLock = oldSoftLockSupplier.get(); if (oldSoftLock.getTransactionId() == null) { // phase 1 prepare, update -> forever return ExpiryPolicy.INFINITE; @@ -839,10 +837,10 @@ public Duration getExpiryForUpdate(K key, ValueSupplier> o } else { // there is an old value -> it's an UPDATE, update -> some time V value = oldSoftLock.getNewValueHolder() == null ? null : oldSoftLock - .getNewValueHolder().value(); + .getNewValueHolder().get(); Duration duration; try { - duration = configuredExpiry.getExpiryForUpdate(key, supplierOf(oldSoftLock.getOldValue()), value); + duration = configuredExpiry.getExpiryForUpdate(key, oldSoftLock::getOldValue, value); } catch (RuntimeException re) { LOGGER.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); return Duration.ZERO; diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java index 6c784b50e2..5eface9096 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java @@ -123,7 +123,7 @@ public XAValueHolder newValueHolderOf(K key) { public V newValueOf(K key) { Command command = commands.get(key); XAValueHolder valueHolder = command == null ? null : command.getNewValueHolder(); - return valueHolder == null ? null : valueHolder.value(); + return valueHolder == null ? null : valueHolder.get(); } public int prepare() throws StoreAccessException, IllegalStateException, TransactionTimeoutException { @@ -186,7 +186,7 @@ public void commit(boolean recovering) throws StoreAccessException, IllegalState for (K key : keys) { SoftLock preparedSoftLock = getFromUnderlyingStore(key); XAValueHolder newValueHolder = preparedSoftLock == null ? null : preparedSoftLock.getNewValueHolder(); - SoftLock definitiveSoftLock = newValueHolder == null ? null : new SoftLock<>(null, newValueHolder.value(), null); + SoftLock definitiveSoftLock = newValueHolder == null ? null : new SoftLock<>(null, newValueHolder.get(), null); if (preparedSoftLock != null) { if (preparedSoftLock.getTransactionId() != null && !preparedSoftLock.getTransactionId().equals(transactionId)) { @@ -298,7 +298,7 @@ private Store.ValueHolder> putIfAbsentInUnderlyingStore(Map.Entry getFromUnderlyingStore(K key) throws StoreAccessException { Store.ValueHolder> softLockValueHolder = underlyingStore.get(key); - return softLockValueHolder == null ? null : softLockValueHolder.value(); + return softLockValueHolder == null ? null : softLockValueHolder.get(); } private void evictFromUnderlyingStore(K key) throws StoreAccessException { diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java index bdcad8a840..d4e8a58205 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAValueHolder.java @@ -90,7 +90,7 @@ protected TimeUnit nativeTimeUnit() { } @Override - public V value() { + public V get() { return value; } @@ -116,7 +116,7 @@ public boolean equals(Object other) { private Object writeReplace() { return new SerializedXAValueHolder<>(getId(), creationTime(NATIVE_TIME_UNIT), lastAccessTime(NATIVE_TIME_UNIT), expirationTime(NATIVE_TIME_UNIT), - hits(), value(), valueSerialized); + hits(), get(), valueSerialized); } /** diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java index b057655e23..1334a643c9 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAStoreTest.java @@ -17,7 +17,6 @@ package org.ehcache.transactions.xa.internal; import org.ehcache.Cache; -import org.ehcache.ValueSupplier; import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePool; import org.ehcache.config.ResourceType; @@ -76,11 +75,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; import javax.transaction.HeuristicMixedException; import javax.transaction.HeuristicRollbackException; -import javax.transaction.InvalidTransactionException; -import javax.transaction.NotSupportedException; import javax.transaction.RollbackException; import javax.transaction.Status; import javax.transaction.Synchronization; @@ -104,7 +102,7 @@ import static org.mockito.Mockito.mock; /** - * Tests for {@link XAStore} and {@link org.ehcache.transactions.xa.internal.XAStore.Provider XAStore.Provider}. + * Tests for {@link XAStore} and {@link org.ehcache.transactions.xa.internal.XAStore.Provider}. */ public class XAStoreTest { @@ -179,7 +177,7 @@ public void testSimpleGetPutRemove() throws Exception { assertThat(xaStore.get(1L), is(nullValue())); assertThat(xaStore.put(1L, "1"), equalTo(Store.PutStatus.PUT)); assertThat(xaStore.put(1L, "one"), equalTo(Store.PutStatus.PUT)); - assertThat(xaStore.get(1L).value(), equalTo("one")); + assertThat(xaStore.get(1L).get(), equalTo("one")); } testTransactionManager.rollback(); @@ -190,7 +188,7 @@ public void testSimpleGetPutRemove() throws Exception { assertThat(xaStore.get(1L), is(nullValue())); assertThat(xaStore.put(1L, "1"), equalTo(Store.PutStatus.PUT)); assertThat(xaStore.put(1L, "one"), equalTo(Store.PutStatus.PUT)); - assertThat(xaStore.get(1L).value(), equalTo("one")); + assertThat(xaStore.get(1L).get(), equalTo("one")); } testTransactionManager.commit(); @@ -214,7 +212,7 @@ public void testSimpleGetPutRemove() throws Exception { assertThat(xaStore.remove(1L), equalTo(false)); assertThat(xaStore.get(1L), is(nullValue())); assertThat(xaStore.put(1L, "un"), equalTo(Store.PutStatus.PUT)); - assertThat(xaStore.get(1L).value(), equalTo("un")); + assertThat(xaStore.get(1L).get(), equalTo("un")); } testTransactionManager.commit(); @@ -348,7 +346,7 @@ public void testIterate() throws Exception { Store.Iterator>> iterator = xaStore.iterator(); while (iterator.hasNext()) { Cache.Entry> next = iterator.next(); - iterated.put(next.getKey(), next.getValue().value()); + iterated.put(next.getKey(), next.getValue().get()); } assertThat(iterated.size(), is(3)); assertThat(iterated.get(0L), equalTo("zero")); @@ -363,7 +361,7 @@ public void testIterate() throws Exception { Store.Iterator>> iterator = xaStore.iterator(); while (iterator.hasNext()) { Cache.Entry> next = iterator.next(); - iterated.put(next.getKey(), next.getValue().value()); + iterated.put(next.getKey(), next.getValue().get()); } assertThat(iterated.size(), is(3)); assertThat(iterated.get(0L), equalTo("zero")); @@ -421,9 +419,9 @@ public void testPutIfAbsent() throws Exception { testTransactionManager.begin(); { assertThat(xaStore.putIfAbsent(1L, "one"), is(nullValue())); - assertThat(xaStore.get(1L).value(), equalTo("one")); - assertThat(xaStore.putIfAbsent(1L, "un").value(), equalTo("one")); - assertThat(xaStore.get(1L).value(), equalTo("one")); + assertThat(xaStore.get(1L).get(), equalTo("one")); + assertThat(xaStore.putIfAbsent(1L, "un").get(), equalTo("one")); + assertThat(xaStore.get(1L).get(), equalTo("one")); } testTransactionManager.commit(); @@ -431,8 +429,8 @@ public void testPutIfAbsent() throws Exception { testTransactionManager.begin(); { - assertThat(xaStore.putIfAbsent(1L, "un").value(), equalTo("one")); - assertThat(xaStore.get(1L).value(), equalTo("one")); + assertThat(xaStore.putIfAbsent(1L, "un").get(), equalTo("one")); + assertThat(xaStore.get(1L).get(), equalTo("one")); assertThat(xaStore.remove(1L), equalTo(true)); assertThat(xaStore.putIfAbsent(1L, "uno"), is(nullValue())); } @@ -545,8 +543,8 @@ public void testReplace2Args() throws Exception { { assertThat(xaStore.replace(1L, "one"), is(nullValue())); assertThat(xaStore.put(1L, "one"), equalTo(Store.PutStatus.PUT)); - assertThat(xaStore.replace(1L, "un").value(), equalTo("one")); - assertThat(xaStore.replace(1L, "uno").value(), equalTo("un")); + assertThat(xaStore.replace(1L, "un").get(), equalTo("one")); + assertThat(xaStore.replace(1L, "uno").get(), equalTo("un")); } testTransactionManager.commit(); @@ -554,8 +552,8 @@ public void testReplace2Args() throws Exception { testTransactionManager.begin(); { - assertThat(xaStore.replace(1L, "een").value(), equalTo("uno")); - assertThat(xaStore.replace(1L, "eins").value(), equalTo("een")); + assertThat(xaStore.replace(1L, "een").get(), equalTo("uno")); + assertThat(xaStore.replace(1L, "eins").get(), equalTo("een")); } testTransactionManager.commit(); @@ -624,10 +622,10 @@ public void testReplace3Args() throws Exception { assertThat(xaStore.put(1L, "one"), equalTo(Store.PutStatus.PUT)); assertThat(xaStore.replace(1L, "eins", "un"), equalTo(Store.ReplaceStatus.MISS_PRESENT)); assertThat(xaStore.replace(1L, "one", "un"), equalTo(Store.ReplaceStatus.HIT)); - assertThat(xaStore.get(1L).value(), equalTo("un")); + assertThat(xaStore.get(1L).get(), equalTo("un")); assertThat(xaStore.replace(1L, "eins", "een"), equalTo(Store.ReplaceStatus.MISS_PRESENT)); assertThat(xaStore.replace(1L, "un", "uno"), equalTo(Store.ReplaceStatus.HIT)); - assertThat(xaStore.get(1L).value(), equalTo("uno")); + assertThat(xaStore.get(1L).get(), equalTo("uno")); } testTransactionManager.commit(); @@ -637,7 +635,7 @@ public void testReplace3Args() throws Exception { { assertThat(xaStore.replace(1L, "one", "uno"), equalTo(Store.ReplaceStatus.MISS_PRESENT)); assertThat(xaStore.replace(1L, "uno", "un"), equalTo(Store.ReplaceStatus.HIT)); - assertThat(xaStore.get(1L).value(), equalTo("un")); + assertThat(xaStore.get(1L).get(), equalTo("un")); assertThat(xaStore.remove(1L), equalTo(true)); assertThat(xaStore.replace(1L, "un", "eins"), equalTo(Store.ReplaceStatus.MISS_NOT_PRESENT)); } @@ -709,13 +707,13 @@ public void testCompute() throws Exception { assertThat(s, is(nullValue())); return "one"; }); - assertThat(computed1.value(), equalTo("one")); + assertThat(computed1.get(), equalTo("one")); Store.ValueHolder computed2 = xaStore.compute(1L, (aLong, s) -> { assertThat(aLong, is(1L)); assertThat(s, equalTo("one")); return "un"; }); - assertThat(computed2.value(), equalTo("un")); + assertThat(computed2.get(), equalTo("un")); Store.ValueHolder computed3 = xaStore.compute(1L, (aLong, s) -> { assertThat(aLong, is(1L)); assertThat(s, equalTo("un")); @@ -734,7 +732,7 @@ public void testCompute() throws Exception { assertThat(s, is(nullValue())); return "one"; }, () -> Boolean.FALSE); - assertThat(computed1.value(), equalTo("one")); + assertThat(computed1.get(), equalTo("one")); Store.ValueHolder computed2 = xaStore.compute(1L, (aLong, s) -> { assertThat(aLong, is(1L)); assertThat(s, equalTo("one")); @@ -753,7 +751,7 @@ public void testCompute() throws Exception { assertThat(s, is(nullValue())); return "one"; }); - assertThat(computed1.value(), equalTo("one")); + assertThat(computed1.get(), equalTo("one")); Store.ValueHolder computed2 = xaStore.compute(1L, (aLong, s) -> { assertThat(aLong, is(1L)); assertThat(s, equalTo("one")); @@ -772,13 +770,13 @@ public void testCompute() throws Exception { assertThat(s, is(nullValue())); return "one"; }); - assertThat(computed1.value(), equalTo("one")); + assertThat(computed1.get(), equalTo("one")); Store.ValueHolder computed2 = xaStore.compute(1L, (aLong, s) -> { assertThat(aLong, is(1L)); assertThat(s, equalTo("one")); return "un"; }); - assertThat(computed2.value(), equalTo("un")); + assertThat(computed2.get(), equalTo("un")); } testTransactionManager.commit(); @@ -791,7 +789,7 @@ public void testCompute() throws Exception { assertThat(s, equalTo("un")); return "eins"; }); - assertThat(computed.value(), equalTo("eins")); + assertThat(computed.get(), equalTo("eins")); } testTransactionManager.commit(); @@ -829,7 +827,7 @@ public void testCompute() throws Exception { assertThat(s, is(nullValue())); return "uno"; }); - assertThat(computed3.value(), equalTo("uno")); + assertThat(computed3.get(), equalTo("uno")); } testTransactionManager.commit(); @@ -884,12 +882,12 @@ public void testComputeIfAbsent() throws Exception { assertThat(aLong, is(1L)); return "one"; }); - assertThat(computed1.value(), equalTo("one")); + assertThat(computed1.get(), equalTo("one")); Store.ValueHolder computed2 = xaStore.computeIfAbsent(1L, aLong -> { fail("should not be absent"); throw new AssertionError(); }); - assertThat(computed2.value(), equalTo("one")); + assertThat(computed2.get(), equalTo("one")); } testTransactionManager.commit(); @@ -901,7 +899,7 @@ public void testComputeIfAbsent() throws Exception { fail("should not be absent"); throw new AssertionError(); }); - assertThat(computed1.value(), equalTo("one")); + assertThat(computed1.get(), equalTo("one")); xaStore.remove(1L); @@ -909,7 +907,7 @@ public void testComputeIfAbsent() throws Exception { assertThat(aLong, is(1L)); return "un"; }); - assertThat(computed2.value(), equalTo("un")); + assertThat(computed2.get(), equalTo("un")); } testTransactionManager.commit(); @@ -959,12 +957,12 @@ public Duration getExpiryForCreation(Object key, Object value) { } @Override - public Duration getExpiryForAccess(Object key, ValueSupplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { throw new AssertionError(); } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + public Duration getExpiryForUpdate(Object key, Supplier oldValue, Object newValue) { throw new AssertionError(); } }; @@ -999,7 +997,7 @@ public Duration getExpiryForCreation(Object key, Object value) { } @Override - public Duration getExpiryForAccess(Object key, ValueSupplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { if (testTimeSource.getTimeMillis() > 0) { throw new RuntimeException(); } @@ -1007,7 +1005,7 @@ public Duration getExpiryForAccess(Object key, ValueSupplier v } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + public Duration getExpiryForUpdate(Object key, Supplier oldValue, Object newValue) { return ExpiryPolicy.INFINITE; } }; @@ -1031,7 +1029,7 @@ public Duration getExpiryForUpdate(Object key, ValueSupplier o testTimeSource.advanceTime(1000); testTransactionManager.begin(); - assertThat(xaStore.get(1L).value(), is("one")); + assertThat(xaStore.get(1L).get(), is("one")); testTransactionManager.commit(); testTransactionManager.begin(); @@ -1049,12 +1047,12 @@ public Duration getExpiryForCreation(Object key, Object value) { } @Override - public Duration getExpiryForAccess(Object key, ValueSupplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { return ExpiryPolicy.INFINITE; } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + public Duration getExpiryForUpdate(Object key, Supplier oldValue, Object newValue) { if (testTimeSource.getTimeMillis() > 0) { throw new RuntimeException(); } @@ -1119,9 +1117,9 @@ public void testBulkCompute() throws Exception { }); assertThat(computedMap.size(), is(3)); - assertThat(computedMap.get(1L).value(), equalTo("stuff#1")); - assertThat(computedMap.get(2L).value(), equalTo("stuff#2")); - assertThat(computedMap.get(3L).value(), equalTo("stuff#3")); + assertThat(computedMap.get(1L).get(), equalTo("stuff#1")); + assertThat(computedMap.get(2L).get(), equalTo("stuff#2")); + assertThat(computedMap.get(3L).get(), equalTo("stuff#3")); computedMap = xaStore.bulkCompute(asSet(0L, 1L, 3L), entries -> { @@ -1150,8 +1148,8 @@ public void testBulkCompute() throws Exception { }); assertThat(computedMap.size(), is(3)); - assertThat(computedMap.get(0L).value(), equalTo("otherStuff#0")); - assertThat(computedMap.get(1L).value(), equalTo("otherStuff#1")); + assertThat(computedMap.get(0L).get(), equalTo("otherStuff#0")); + assertThat(computedMap.get(1L).get(), equalTo("otherStuff#1")); assertThat(computedMap.get(3L), is(nullValue())); } testTransactionManager.commit(); @@ -1192,9 +1190,9 @@ public void testBulkComputeIfAbsent() throws Exception { }); assertThat(computedMap.size(), is(3)); - assertThat(computedMap.get(1L).value(), equalTo("stuff#1")); - assertThat(computedMap.get(2L).value(), equalTo("stuff#2")); - assertThat(computedMap.get(3L).value(), equalTo("stuff#3")); + assertThat(computedMap.get(1L).get(), equalTo("stuff#1")); + assertThat(computedMap.get(2L).get(), equalTo("stuff#2")); + assertThat(computedMap.get(3L).get(), equalTo("stuff#3")); computedMap = xaStore.bulkComputeIfAbsent(asSet(0L, 1L, 3L), keys -> { Map result = new HashMap<>(); @@ -1213,9 +1211,9 @@ public void testBulkComputeIfAbsent() throws Exception { }); assertThat(computedMap.size(), is(3)); - assertThat(computedMap.get(0L).value(), equalTo("otherStuff#0")); - assertThat(computedMap.get(1L).value(), equalTo("stuff#1")); - assertThat(computedMap.get(3L).value(), equalTo("stuff#3")); + assertThat(computedMap.get(0L).get(), equalTo("otherStuff#0")); + assertThat(computedMap.get(1L).get(), equalTo("stuff#1")); + assertThat(computedMap.get(3L).get(), equalTo("stuff#3")); } testTransactionManager.commit(); @@ -1331,7 +1329,7 @@ private void assertMapping(XAStore xaStore, long key, String value Store.ValueHolder valueHolder = xaStore.get(key); if (value != null) { - assertThat(valueHolder.value(), equalTo(value)); + assertThat(valueHolder.get(), equalTo(value)); } else { assertThat(valueHolder, is(nullValue())); } @@ -1367,7 +1365,7 @@ public TestTransaction getCurrentTransaction() { } @Override - public void begin() throws NotSupportedException, SystemException { + public void begin() { currentTransaction = new TestTransaction(gtridGenerator.incrementAndGet()); } @@ -1378,17 +1376,17 @@ public void commit() throws RollbackException, HeuristicMixedException, Heuristi } @Override - public int getStatus() throws SystemException { + public int getStatus() { return 0; } @Override - public Transaction getTransaction() throws SystemException { + public Transaction getTransaction() { return currentTransaction; } @Override - public void resume(Transaction tobj) throws InvalidTransactionException, IllegalStateException, SystemException { + public void resume(Transaction tobj) { } @@ -1399,17 +1397,17 @@ public void rollback() throws IllegalStateException, SecurityException, SystemEx } @Override - public void setRollbackOnly() throws IllegalStateException, SystemException { + public void setRollbackOnly() { } @Override - public void setTransactionTimeout(int seconds) throws SystemException { + public void setTransactionTimeout(int seconds) { } @Override - public Transaction suspend() throws SystemException { + public Transaction suspend() { return null; } } diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XATransactionContextTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XATransactionContextTest.java index 1434f6edd3..40f018c9bd 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XATransactionContextTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XATransactionContextTest.java @@ -97,7 +97,7 @@ public void testSimpleCommands() throws Exception { assertThat(xaTransactionContext.removed(1L), is(false)); assertThat(xaTransactionContext.updated(1L), is(true)); assertThat(xaTransactionContext.evicted(1L), is(false)); - assertThat(xaTransactionContext.newValueHolderOf(1L).value(), equalTo("new")); + assertThat(xaTransactionContext.newValueHolderOf(1L).get(), equalTo("new")); assertThat(xaTransactionContext.oldValueOf(1L), equalTo("old")); assertThat(xaTransactionContext.newValueOf(1L), equalTo("new")); @@ -132,7 +132,7 @@ public void testCommandsOverrideEachOther() throws Exception { assertThat(xaTransactionContext.removed(1L), is(false)); assertThat(xaTransactionContext.updated(1L), is(true)); assertThat(xaTransactionContext.evicted(1L), is(false)); - assertThat(xaTransactionContext.newValueHolderOf(1L).value(), equalTo("new")); + assertThat(xaTransactionContext.newValueHolderOf(1L).get(), equalTo("new")); assertThat(xaTransactionContext.oldValueOf(1L), equalTo("old")); assertThat(xaTransactionContext.newValueOf(1L), equalTo("new")); @@ -159,7 +159,7 @@ public void testCommandsOverrideEachOther() throws Exception { assertThat(xaTransactionContext.removed(1L), is(false)); assertThat(xaTransactionContext.updated(1L), is(true)); assertThat(xaTransactionContext.evicted(1L), is(false)); - assertThat(xaTransactionContext.newValueHolderOf(1L).value(), equalTo("new2")); + assertThat(xaTransactionContext.newValueHolderOf(1L).get(), equalTo("new2")); assertThat(xaTransactionContext.oldValueOf(1L), equalTo("old2")); assertThat(xaTransactionContext.newValueOf(1L), equalTo("new2")); } @@ -176,7 +176,7 @@ public void testEvictCommandCannotBeOverridden() throws Exception { assertThat(xaTransactionContext.removed(1L), is(false)); assertThat(xaTransactionContext.updated(1L), is(true)); assertThat(xaTransactionContext.evicted(1L), is(false)); - assertThat(xaTransactionContext.newValueHolderOf(1L).value(), equalTo("new")); + assertThat(xaTransactionContext.newValueHolderOf(1L).get(), equalTo("new")); assertThat(xaTransactionContext.oldValueOf(1L), equalTo("old")); assertThat(xaTransactionContext.newValueOf(1L), equalTo("new")); @@ -238,7 +238,7 @@ public void testPrepare() throws Exception { xaTransactionContext.addCommand(3L, new StoreEvictCommand<>("three")); Store.ValueHolder> mockValueHolder = mock(Store.ValueHolder.class); - when(mockValueHolder.value()).thenReturn(new SoftLock<>(null, "two", null)); + when(mockValueHolder.get()).thenReturn(new SoftLock<>(null, "two", null)); when(underlyingStore.get(eq(2L))).thenReturn(mockValueHolder); when(underlyingStore.replace(eq(2L), eq(new SoftLock<>(null, "two", null)), eq(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "two", null)))).thenReturn(ReplaceStatus.HIT); @@ -280,7 +280,7 @@ public void testCommitNotPreparedInFlightThrows() throws Exception { @SuppressWarnings("unchecked") Store.ValueHolder> mockValueHolder = mock(Store.ValueHolder.class); - when(mockValueHolder.value()).thenReturn(new SoftLock<>(null, "two", null)); + when(mockValueHolder.get()).thenReturn(new SoftLock<>(null, "two", null)); when(underlyingStore.get(eq(2L))).thenReturn(mockValueHolder); try { @@ -304,14 +304,14 @@ public void testCommit() throws Exception { xaTransactionContext.addCommand(3L, new StoreEvictCommand<>("three")); Store.ValueHolder> mockValueHolder1 = mock(Store.ValueHolder.class); - when(mockValueHolder1.value()).thenReturn(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "one", new XAValueHolder<>("un", timeSource + when(mockValueHolder1.get()).thenReturn(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "one", new XAValueHolder<>("un", timeSource .getTimeMillis()))); when(underlyingStore.get(eq(1L))).thenReturn(mockValueHolder1); Store.ValueHolder> mockValueHolder2 = mock(Store.ValueHolder.class); - when(mockValueHolder2.value()).thenReturn(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "two", null)); + when(mockValueHolder2.get()).thenReturn(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "two", null)); when(underlyingStore.get(eq(2L))).thenReturn(mockValueHolder2); Store.ValueHolder> mockValueHolder3 = mock(Store.ValueHolder.class); - when(mockValueHolder3.value()).thenReturn(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "three", null)); + when(mockValueHolder3.get()).thenReturn(new SoftLock<>(new TransactionId(new TestXid(0, 0)), "three", null)); when(underlyingStore.get(eq(3L))).thenReturn(mockValueHolder3); when(journal.isInDoubt(eq(new TransactionId(new TestXid(0, 0))))).thenReturn(true); @@ -364,7 +364,7 @@ public void testCommitInOnePhase() throws Exception { xaTransactionContext.addCommand(3L, new StoreEvictCommand<>("three")); Store.ValueHolder> mockValueHolder = mock(Store.ValueHolder.class); - when(mockValueHolder.value()).thenReturn(new SoftLock<>(null, "two", null)); + when(mockValueHolder.get()).thenReturn(new SoftLock<>(null, "two", null)); when(underlyingStore.get(eq(2L))).thenReturn(mockValueHolder); final AtomicReference> savedInDoubtCollectionRef = new AtomicReference<>(); @@ -377,7 +377,7 @@ public void testCommitInOnePhase() throws Exception { final AtomicReference softLock1Ref = new AtomicReference<>(); when(underlyingStore.get(eq(1L))).then(invocation -> softLock1Ref.get() == null ? null : new AbstractValueHolder(-1, -1) { @Override - public Object value() { + public Object get() { return softLock1Ref.get(); } @Override @@ -398,7 +398,7 @@ protected TimeUnit nativeTimeUnit() { final AtomicReference softLock2Ref = new AtomicReference<>(new SoftLock(null, "two", null)); when(underlyingStore.get(eq(2L))).then(invocation -> softLock2Ref.get() == null ? null : new AbstractValueHolder(-1, -1) { @Override - public Object value() { + public Object get() { return softLock2Ref.get(); } @Override @@ -470,7 +470,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } @Override - public SoftLock value() { + public SoftLock get() { return new SoftLock<>(new TransactionId(new TestXid(0, 0)), "one", new XAValueHolder<>("un", timeSource.getTimeMillis())); } }); @@ -480,7 +480,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } @Override - public SoftLock value() { + public SoftLock get() { return new SoftLock<>(new TransactionId(new TestXid(0, 0)), "two", null); } }); @@ -551,7 +551,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } @Override - public SoftLock value() { + public SoftLock get() { return new SoftLock<>(new TransactionId(new TestXid(0, 0)), "old1", new XAValueHolder<>("new1", timeSource .getTimeMillis())); } @@ -562,7 +562,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } @Override - public SoftLock value() { + public SoftLock get() { return new SoftLock<>(new TransactionId(new TestXid(0, 0)), "old2", null); } }); @@ -617,7 +617,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } @Override - public SoftLock value() { + public SoftLock get() { return new SoftLock<>(new TransactionId(new TestXid(0, 0)), "old1", new XAValueHolder<>("new1", timeSource .getTimeMillis())); } @@ -628,7 +628,7 @@ protected TimeUnit nativeTimeUnit() { return TimeUnit.MILLISECONDS; } @Override - public SoftLock value() { + public SoftLock get() { return new SoftLock<>(new TransactionId(new TestXid(0, 0)), "old2", null); } }); diff --git a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java index 37da508b91..7445eabe83 100644 --- a/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java +++ b/transactions/src/test/java/org/ehcache/transactions/xa/internal/XAValueHolderTest.java @@ -52,7 +52,7 @@ public void testSerialization() throws Exception { assertThat(result.creationTime(TimeUnit.MILLISECONDS), is(valueHolder.creationTime(TimeUnit.MILLISECONDS))); assertThat(result.lastAccessTime(TimeUnit.MILLISECONDS), is(valueHolder.lastAccessTime(TimeUnit.MILLISECONDS))); assertThat(result.expirationTime(TimeUnit.MILLISECONDS), is(valueHolder.expirationTime(TimeUnit.MILLISECONDS))); - assertThat(result.value(), is(valueHolder.value())); + assertThat(result.get(), is(valueHolder.get())); assertThat(result.hits(), is(valueHolder.hits())); } } diff --git a/xml/src/test/java/com/pany/ehcache/MyExpiry.java b/xml/src/test/java/com/pany/ehcache/MyExpiry.java index 99e793fd1d..f99e8d2617 100644 --- a/xml/src/test/java/com/pany/ehcache/MyExpiry.java +++ b/xml/src/test/java/com/pany/ehcache/MyExpiry.java @@ -16,27 +16,27 @@ package com.pany.ehcache; -import org.ehcache.ValueSupplier; import org.ehcache.expiry.ExpiryPolicy; import java.time.Duration; +import java.util.function.Supplier; /** * @author Alex Snaps */ public class MyExpiry implements ExpiryPolicy { @Override - public Duration getExpiryForCreation(final Object key, final Object value) { + public Duration getExpiryForCreation(Object key, Object value) { return Duration.ofSeconds(42); } @Override - public Duration getExpiryForAccess(final Object key, final ValueSupplier value) { + public Duration getExpiryForAccess(Object key, Supplier value) { return Duration.ofSeconds(42); } @Override - public Duration getExpiryForUpdate(Object key, ValueSupplier oldValue, Object newValue) { + public Duration getExpiryForUpdate(Object key, Supplier oldValue, Object newValue) { return Duration.ofSeconds(42); } } From f566fde3d933f6bdf4e71d4361633caf5ee4d17d Mon Sep 17 00:00:00 2001 From: Saurabh Agarwal Date: Thu, 4 Jan 2018 18:24:47 +0530 Subject: [PATCH 085/779] Issue #2219: Provide a way to pass connection properties in DefaultClusteringService --- .../ClusteringServiceConfiguration.java | 30 ++++++++++++++++++- .../service/DefaultClusteringService.java | 4 +-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java index 692a9c0f57..481f2c9e4f 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java @@ -26,8 +26,8 @@ import java.net.URI; import java.time.Duration; -import java.util.Map; import java.util.Objects; +import java.util.Properties; import org.ehcache.clustered.common.ServerSideConfiguration; @@ -44,6 +44,7 @@ public class ClusteringServiceConfiguration private final boolean autoCreate; private final ServerSideConfiguration serverConfiguration; private final Timeouts timeouts; + private final Properties properties; /** * Creates a {@code ClusteringServiceConfiguration} from the properties provided. @@ -123,10 +124,27 @@ public ClusteringServiceConfiguration(URI clusterUri, boolean autoCreate, Server * @throws IllegalArgumentException if {@code clusterUri} is not URI valid for cluster operations */ public ClusteringServiceConfiguration(URI clusterUri, Timeouts timeouts, boolean autoCreate, ServerSideConfiguration serverConfig) { + this(clusterUri, timeouts, autoCreate, serverConfig, new Properties()); + } + + /** + * Creates a {@code ClusteringServiceConfiguration} from the properties provided. + * + * @param clusterUri the non-{@code null} URI identifying the cluster server + * @param timeouts the {@link Timeouts} specifying the time limit for clustered cache operations + * @param autoCreate {@code true} if server components should be auto created + * @param serverConfig the server side entity configuration required + * @param properties the non-{@code null} connection Properties + * + * @throws NullPointerException if {@code clusterUri} is {@code null} + * @throws IllegalArgumentException if {@code clusterUri} is not URI valid for cluster operations + */ + public ClusteringServiceConfiguration(URI clusterUri, Timeouts timeouts, boolean autoCreate, ServerSideConfiguration serverConfig, Properties properties) { this.clusterUri = Objects.requireNonNull(clusterUri, "Cluster URI cannot be null"); this.autoCreate = autoCreate; this.serverConfiguration = serverConfig; this.timeouts = Objects.requireNonNull(timeouts, "Operation timeouts cannot be null"); + this.properties = Objects.requireNonNull(properties, "Properties cannot be null"); } protected ClusteringServiceConfiguration(ClusteringServiceConfiguration baseConfig) { @@ -135,6 +153,7 @@ protected ClusteringServiceConfiguration(ClusteringServiceConfiguration baseConf this.timeouts = baseConfig.getTimeouts(); this.autoCreate = baseConfig.isAutoCreate(); this.serverConfiguration = baseConfig.getServerConfiguration(); + this.properties = baseConfig.getProperties(); } /** @@ -173,6 +192,15 @@ public Timeouts getTimeouts() { return timeouts; } + /** + * The {@code Properties} for the connection. + * + * @return the connection {@code Properties} + */ + public Properties getProperties() { + return properties; + } + /** * The timeout for cache read operations. * diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java index b2070c6994..0e4b734a14 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java @@ -57,7 +57,6 @@ import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; -import java.util.Arrays; import java.util.Properties; import java.util.Random; import java.util.concurrent.ConcurrentHashMap; @@ -79,6 +78,7 @@ class DefaultClusteringService implements ClusteringService, EntityService { private final String entityIdentifier; private final ConcurrentMap knownPersistenceSpaces = new ConcurrentHashMap<>(); private final Timeouts timeouts; + private final Properties properties; private volatile Connection clusterConnection; private ClusterTierManagerClientEntityFactory entityFactory; @@ -93,6 +93,7 @@ class DefaultClusteringService implements ClusteringService, EntityService { this.clusterUri = extractClusterUri(ehcacheUri); this.entityIdentifier = clusterUri.relativize(ehcacheUri).getPath(); this.timeouts = configuration.getTimeouts(); + this.properties = configuration.getProperties(); } private static URI extractClusterUri(URI uri) { @@ -171,7 +172,6 @@ private void createEntityFactory() { private void initClusterConnection() { try { - Properties properties = new Properties(); properties.put(ConnectionPropertyNames.CONNECTION_NAME, CONNECTION_PREFIX + entityIdentifier); properties.put(ConnectionPropertyNames.CONNECTION_TIMEOUT, Long.toString(timeouts.getConnectionTimeout().toMillis())); clusterConnection = ConnectionFactory.connect(clusterUri, properties); From 1d04202ac3b53c259c37cb3929c6dc87cccc3657 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 13 Dec 2017 14:22:34 +0100 Subject: [PATCH 086/779] Support JCache 1.1.0 --- 107/build.gradle | 4 ++-- .../java/org/ehcache/jsr107/Eh107CacheManager.java | 14 ++------------ .../org/ehcache/jsr107/EventListenerAdaptors.java | 2 +- 107/src/tck/resources/ExcludeList | 7 ------- .../org/ehcache/jsr107/Eh107CacheTypeTest.java | 5 +---- gradle.properties | 3 ++- 6 files changed, 8 insertions(+), 27 deletions(-) diff --git a/107/build.gradle b/107/build.gradle index 469acad59e..732ee857b3 100644 --- a/107/build.gradle +++ b/107/build.gradle @@ -32,8 +32,8 @@ sourceSets { dependencies { compile project(':impl'), project(':xml') provided "javax.cache:cache-api:$parent.jcacheVersion" - tckTestRuntime 'javax.cache:cache-tests:1.0.1' - tckTestClasses('javax.cache:cache-tests:1.0.1:tests') { + tckTestRuntime "javax.cache:cache-tests:$jcacheTckVersion" + tckTestClasses("javax.cache:cache-tests:$jcacheTckVersion:tests") { transitive = false } } diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java b/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java index 5041aa7cad..d2de6953fe 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107CacheManager.java @@ -287,18 +287,7 @@ public Cache getCache(String cacheName) { throw new NullPointerException(); } - Eh107Cache cache = safeCacheRetrieval(cacheName); - - if (cache == null) { - return null; - } - - if (cache.getConfiguration(Configuration.class).getKeyType() != Object.class - || cache.getConfiguration(Configuration.class).getValueType() != Object.class) { - throw new IllegalArgumentException("Cache [" + cacheName - + "] specifies key/value types. Use getCache(String, Class, Class)"); - } - return cache; + return safeCacheRetrieval(cacheName); } @SuppressWarnings("unchecked") @@ -312,6 +301,7 @@ private Eh107Cache safeCacheRetrieval(final String cacheName) { @Override public Iterable getCacheNames() { + checkClosed(); refreshAllCaches(); return Collections.unmodifiableList(new ArrayList<>(caches.keySet())); } diff --git a/107/src/main/java/org/ehcache/jsr107/EventListenerAdaptors.java b/107/src/main/java/org/ehcache/jsr107/EventListenerAdaptors.java index a47040ab6a..b03d1080db 100644 --- a/107/src/main/java/org/ehcache/jsr107/EventListenerAdaptors.java +++ b/107/src/main/java/org/ehcache/jsr107/EventListenerAdaptors.java @@ -174,7 +174,7 @@ org.ehcache.event.EventType getEhcacheEventType() { @SuppressWarnings("unchecked") @Override public void onEvent(org.ehcache.event.CacheEvent ehEvent) { - Eh107CacheEntryEvent event = new Eh107CacheEntryEvent.NormalEvent<>(source, EventType.CREATED, ehEvent, requestsOld); + Eh107CacheEntryEvent event = new Eh107CacheEntryEvent.NormalEvent<>(source, EventType.CREATED, ehEvent, false); if (filter.evaluate(event)) { Set events = Collections.singleton(event); listener.onCreated((Iterable>) events); diff --git a/107/src/tck/resources/ExcludeList b/107/src/tck/resources/ExcludeList index 0cc2da0b52..e84e6c9418 100644 --- a/107/src/tck/resources/ExcludeList +++ b/107/src/tck/resources/ExcludeList @@ -4,10 +4,3 @@ # This is a dummy test that fails if not in the exclude list. org.jsr107.tck.CachingTest#dummyTest - -# see https://github.com/jsr107/jsr107tck/issues/63 -org.jsr107.tck.management.CacheMBStatisticsBeanTest#testPutIfAbsent - -# see https://github.com/jsr107/jsr107tck/issues/61 -org.jsr107.tck.spi.CachingProviderClassLoaderTest#getCacheManagerSingleton - diff --git a/107/src/test/java/org/ehcache/jsr107/Eh107CacheTypeTest.java b/107/src/test/java/org/ehcache/jsr107/Eh107CacheTypeTest.java index c633988975..a7acd10b30 100644 --- a/107/src/test/java/org/ehcache/jsr107/Eh107CacheTypeTest.java +++ b/107/src/test/java/org/ehcache/jsr107/Eh107CacheTypeTest.java @@ -63,7 +63,7 @@ public void testCompileTimeTypeSafety() throws Exception { @Test - public void testRunTimeTypeSafety() throws Exception { + public void testRunTimeTypeLaxity() throws Exception { CachingProvider provider = Caching.getCachingProvider(); javax.cache.CacheManager cacheManager = provider.getCacheManager(this.getClass().getResource("/ehcache-107-types.xml").toURI(), getClass().getClassLoader()); @@ -79,9 +79,6 @@ public void testRunTimeTypeSafety() throws Exception { try { cacheManager.getCache("cache1"); - fail("Caches with runtime types should throw illegal argument exception when different types are used in getcache"); - } catch (IllegalArgumentException e) { - //Empty block as nothing is required to be tested } finally { cacheManager.destroyCache("cache1"); cacheManager.close(); diff --git a/gradle.properties b/gradle.properties index f512918e87..51b310a403 100644 --- a/gradle.properties +++ b/gradle.properties @@ -2,7 +2,7 @@ # Terracotta third parties offheapVersion = 2.4.0 statisticVersion = 1.5.0 -jcacheVersion = 1.0.0 +jcacheVersion = 1.1.0 slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 @@ -18,6 +18,7 @@ assertjVersion = 3.8.0 hamcrestVersion = 1.3 mockitoVersion = 2.12.0 jacksonVersion = 2.7.5 +jcacheTckVersion = 1.1.0 # Tools findbugsVersion = 3.0.1 From 1bffe4ae3bec6839739cabe3669d9815de71eb53 Mon Sep 17 00:00:00 2001 From: Saurabh Agarwal Date: Thu, 4 Jan 2018 22:54:46 +0530 Subject: [PATCH 087/779] Made ClusteringServiceConfiguration return a copy of Properties --- .../client/config/ClusteringServiceConfiguration.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java index 481f2c9e4f..94c98851eb 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java @@ -144,7 +144,7 @@ public ClusteringServiceConfiguration(URI clusterUri, Timeouts timeouts, boolean this.autoCreate = autoCreate; this.serverConfiguration = serverConfig; this.timeouts = Objects.requireNonNull(timeouts, "Operation timeouts cannot be null"); - this.properties = Objects.requireNonNull(properties, "Properties cannot be null"); + this.properties = (Properties) Objects.requireNonNull(properties, "Properties cannot be null").clone(); } protected ClusteringServiceConfiguration(ClusteringServiceConfiguration baseConfig) { @@ -198,7 +198,7 @@ public Timeouts getTimeouts() { * @return the connection {@code Properties} */ public Properties getProperties() { - return properties; + return (Properties) properties.clone(); } /** From 4ffd7c48f90591fa8e0eb77dd510a74465f1e60c Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Fri, 17 Nov 2017 15:19:23 -0500 Subject: [PATCH 088/779] :heavy_plus_sign: Close #2221: Management layer refactoring to support more statistic types (tables and samples) --- .../client/internal/store/ClusteredStore.java | 24 +-- .../AbstractClusteringManagementTest.java | 62 ++++--- .../ClusteredStatisticsCountTest.java | 8 +- .../ClusteringManagementServiceTest.java | 39 ++--- .../server/EhcacheStateServiceImpl.java | 48 +++--- .../PoolStatisticsManagementProvider.java | 6 +- ...rverStoreStatisticsManagementProvider.java | 24 +-- .../core/statistics/CacheStatistics.java | 4 +- .../core/statistics/TierStatistics.java | 13 +- .../core/statistics/TypedValueStatistic.java | 40 ----- gradle.properties | 6 +- .../statistics/DefaultCacheStatistics.java | 69 +++----- .../statistics/DefaultTierStatistics.java | 161 ++++++------------ .../impl/internal/statistics/StatsUtils.java | 13 +- .../statistics/ZeroOperationStatistic.java | 92 ---------- .../impl/internal/store/heap/OnHeapStore.java | 15 +- .../store/offheap/AbstractOffHeapStore.java | 73 +++----- .../DefaultCacheStatisticsTest.java | 6 +- .../statistics/DefaultTierStatisticsTest.java | 12 +- .../internal/statistics/StatsUtilsTest.java | 41 ++--- .../statistics/TierCalculationTest.java | 9 - .../statistics/EhcacheStatisticsProvider.java | 60 +++---- .../statistics/StandardEhcacheStatistics.java | 34 ++-- .../DefaultManagementRegistryService.java | 6 +- .../java/org/ehcache/docs/ManagementTest.java | 2 +- .../EhcacheStatisticsProviderTest.java | 9 +- .../StandardEhCacheStatisticsQueryTest.java | 3 +- .../StandardEhcacheStatisticsTest.java | 2 +- .../providers/statistics/StatsUtil.java | 2 +- .../DefaultManagementRegistryServiceTest.java | 23 ++- .../DefaultSharedManagementServiceTest.java | 12 +- 31 files changed, 325 insertions(+), 593 deletions(-) delete mode 100644 core/src/main/java/org/ehcache/core/statistics/TypedValueStatistic.java delete mode 100644 impl/src/main/java/org/ehcache/impl/internal/statistics/ZeroOperationStatistic.java diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java index ab9f1c7526..5cdcbf62ab 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java @@ -22,9 +22,9 @@ import org.ehcache.clustered.client.config.ClusteredStoreConfiguration; import org.ehcache.clustered.client.internal.store.ServerStoreProxy.ServerCallback; import org.ehcache.clustered.client.internal.store.operations.ChainResolver; -import org.ehcache.clustered.client.internal.store.operations.EternalChainResolver; import org.ehcache.clustered.client.internal.store.operations.ConditionalRemoveOperation; import org.ehcache.clustered.client.internal.store.operations.ConditionalReplaceOperation; +import org.ehcache.clustered.client.internal.store.operations.EternalChainResolver; import org.ehcache.clustered.client.internal.store.operations.ExpiryChainResolver; import org.ehcache.clustered.client.internal.store.operations.PutIfAbsentOperation; import org.ehcache.clustered.client.internal.store.operations.PutOperation; @@ -40,30 +40,30 @@ import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.CacheConfigurationChangeListener; import org.ehcache.core.Ehcache; -import org.ehcache.core.events.CacheEventListenerConfiguration; import org.ehcache.core.collections.ConcurrentWeakIdentityHashMap; +import org.ehcache.core.events.CacheEventListenerConfiguration; +import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.core.spi.store.Store; +import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.StoreAccessTimeoutException; import org.ehcache.core.spi.store.events.StoreEventSource; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; -import org.ehcache.core.statistics.AuthoritativeTierOperationOutcomes; -import org.ehcache.core.statistics.StoreOperationOutcomes; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.time.TimeSourceService; +import org.ehcache.core.statistics.AuthoritativeTierOperationOutcomes; +import org.ehcache.core.statistics.StoreOperationOutcomes; import org.ehcache.core.statistics.StoreOperationOutcomes.EvictionOutcome; import org.ehcache.core.statistics.TierOperationOutcomes; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.loaderwriter.DefaultCacheLoaderWriterConfiguration; -import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.store.HashUtils; import org.ehcache.spi.persistence.StateRepository; import org.ehcache.spi.serialization.Serializer; import org.ehcache.spi.serialization.StatefulSerializer; -import org.ehcache.spi.service.ServiceDependencies; -import org.ehcache.spi.service.ServiceProvider; import org.ehcache.spi.service.Service; import org.ehcache.spi.service.ServiceConfiguration; +import org.ehcache.spi.service.ServiceDependencies; +import org.ehcache.spi.service.ServiceProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terracotta.statistics.MappedOperationStatistic; @@ -72,7 +72,6 @@ import java.nio.ByteBuffer; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -135,13 +134,6 @@ private ClusteredStore(final OperationsCodec codec, final ChainResolver tags = new HashSet<>(Arrays.asList(STATISTICS_TAG, "tier")); - StatisticsManager.createPassThroughStatistic(this, "mappings", tags, () -> -1L); - StatisticsManager.createPassThroughStatistic(this, "maxMappings", tags, () -> -1L); - StatisticsManager.createPassThroughStatistic(this, "allocatedMemory", tags, () -> -1L); - StatisticsManager.createPassThroughStatistic(this, "occupiedMemory", tags, () -> -1L); - } /** diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java index 634bb4e0b6..1366c4e75c 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java @@ -33,8 +33,10 @@ import org.terracotta.management.entity.nms.client.NmsEntity; import org.terracotta.management.entity.nms.client.NmsEntityFactory; import org.terracotta.management.entity.nms.client.NmsService; +import org.terracotta.management.model.cluster.AbstractManageableNode; import org.terracotta.management.model.cluster.Client; import org.terracotta.management.model.cluster.ClientIdentifier; +import org.terracotta.management.model.cluster.ServerEntity; import org.terracotta.management.model.cluster.ServerEntityIdentifier; import org.terracotta.management.model.context.Context; import org.terracotta.management.model.message.Message; @@ -102,13 +104,6 @@ public static void beforeClass() throws Exception { nmsService = new DefaultNmsService(tmsAgentEntity); nmsService.setOperationTimeout(5, TimeUnit.SECONDS); - tmsServerEntityIdentifier = readTopology() - .activeServerEntityStream() - .filter(serverEntity -> serverEntity.getType().equals(NmsConfig.ENTITY_TYPE)) - .findFirst() - .get() // throws if not found - .getServerEntityIdentifier(); - cacheManager = newCacheManagerBuilder() // cluster config .with(cluster(CLUSTER.getConnectionURI().resolve("/my-server-entity-1")) @@ -146,19 +141,6 @@ public static void beforeClass() throws Exception { // ensure the CM is running and get its client id assertThat(cacheManager.getStatus(), equalTo(Status.AVAILABLE)); - ehcacheClientIdentifier = readTopology().getClients().values() - .stream() - .filter(client -> client.getName().equals("Ehcache:my-server-entity-1")) - .findFirst() - .map(Client::getClientIdentifier) - .get(); - - clusterTierManagerEntityIdentifier = readTopology() - .activeServerEntityStream() - .filter(serverEntity -> serverEntity.getName().equals("my-server-entity-1")) - .findFirst() - .get() // throws if not found - .getServerEntityIdentifier(); // test_notifs_sent_at_CM_init waitForAllNotifications( @@ -174,6 +156,36 @@ public static void beforeClass() throws Exception { "SERVER_ENTITY_UNFETCHED" ); + do { + tmsServerEntityIdentifier = readTopology() + .activeServerEntityStream() + .filter(serverEntity -> serverEntity.getType().equals(NmsConfig.ENTITY_TYPE)) + .filter(AbstractManageableNode::isManageable) + .map(ServerEntity::getServerEntityIdentifier) + .findFirst() + .orElse(null); + } while (tmsServerEntityIdentifier == null && !Thread.currentThread().isInterrupted()); + + do { + ehcacheClientIdentifier = readTopology().getClients().values() + .stream() + .filter(client -> client.getName().equals("Ehcache:my-server-entity-1")) + .filter(AbstractManageableNode::isManageable) + .findFirst() + .map(Client::getClientIdentifier) + .orElse(null); + } while (ehcacheClientIdentifier == null && !Thread.currentThread().isInterrupted()); + + do { + clusterTierManagerEntityIdentifier = readTopology() + .activeServerEntityStream() + .filter(serverEntity -> serverEntity.getName().equals("my-server-entity-1")) + .filter(AbstractManageableNode::isManageable) + .map(ServerEntity::getServerEntityIdentifier) + .findFirst() + .orElse(null); + } while (clusterTierManagerEntityIdentifier == null && !Thread.currentThread().isInterrupted()); + sendManagementCallOnEntityToCollectStats(); } @@ -213,9 +225,11 @@ protected static org.terracotta.management.model.cluster.Cluster readTopology() } protected static void sendManagementCallOnClientToCollectStats() throws Exception { - Context ehcacheClient = readTopology().getClient(ehcacheClientIdentifier).get().getContext() + org.terracotta.management.model.cluster.Cluster topology = readTopology(); + Client manageableClient = topology.getClient(ehcacheClientIdentifier).filter(AbstractManageableNode::isManageable).get(); + Context cmContext = manageableClient.getContext() .with("cacheManagerName", "my-super-cache-manager"); - nmsService.startStatisticCollector(ehcacheClient, 1, TimeUnit.SECONDS).waitForReturn(); + nmsService.startStatisticCollector(cmContext, 1, TimeUnit.SECONDS).waitForReturn(); } protected static List waitForNextStats() throws Exception { @@ -247,7 +261,9 @@ protected static String normalizeForLineEndings(String stringToNormalize) { } private static void sendManagementCallOnEntityToCollectStats() throws Exception { - Context context = readTopology().getSingleStripe().getActiveServerEntity(tmsServerEntityIdentifier).get().getContext(); + org.terracotta.management.model.cluster.Cluster topology = readTopology(); + ServerEntity manageableEntity = topology.getSingleStripe().getActiveServerEntity(tmsServerEntityIdentifier).filter(AbstractManageableNode::isManageable).get(); + Context context = manageableEntity.getContext(); nmsService.startStatisticCollector(context, 1, TimeUnit.SECONDS).waitForReturn(); } diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java index 560fed6df2..8679f95a3c 100755 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java @@ -66,10 +66,10 @@ public void countTest() throws Exception { System.out.println(" - " + entry.getKey() + " : " + entry.getValue()); }*/ - cacheHitCount = stat.getStatistic("Cache:HitCount").longValue(); - clusteredHitCount = stat.getStatistic("Clustered:HitCount").longValue(); - clusteredMissCount = stat.getStatistic("Clustered:MissCount").longValue(); - cacheMissCount = stat.getStatistic("Cache:MissCount").longValue(); + cacheHitCount = stat.getLatestSample("Cache:HitCount").get(); + clusteredHitCount = stat.getLatestSample("Clustered:HitCount").get(); + clusteredMissCount = stat.getLatestSample("Clustered:MissCount").get(); + cacheMissCount = stat.getLatestSample("Cache:MissCount").get(); } } } while(!Thread.currentThread().isInterrupted() && diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java index 521eaefcc1..1526f8db05 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java @@ -256,7 +256,7 @@ public void test_G_stats_collection() throws Exception { .collect(Collectors.toList()); for (ContextualStatistics stat : stats) { - val = stat.getStatistic("Cache:HitCount").longValue(); + val = stat.getLatestSample("Cache:HitCount").get(); } } while(!Thread.currentThread().isInterrupted() && val != 2); @@ -274,7 +274,7 @@ public void test_G_stats_collection() throws Exception { .collect(Collectors.toList()); for (ContextualStatistics stat : stats) { - val = stat.getStatistic("Cache:HitCount").longValue(); + val = stat.getLatestSample("Cache:HitCount").get(); } } while(!Thread.currentThread().isInterrupted() && val != 4); @@ -339,25 +339,22 @@ public static void initDescriptors() throws ClassNotFoundException { ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:ExpirationCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:MissCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:MappingCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:OccupiedByteSize", "SIZE")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:HitCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:PutCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:RemovalCount" , "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MissCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:OccupiedByteSize", "SIZE")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:AllocatedByteSize", "SIZE")); + OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:OccupiedByteSize", "GAUGE")); + OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:AllocatedByteSize", "GAUGE")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MappingCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:EvictionCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:ExpirationCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MaxMappingCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:HitCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:PutCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:RemovalCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:MaxMappingCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:OccupiedByteSize", "SIZE")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:AllocatedByteSize", "SIZE")); + DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:OccupiedByteSize", "GAUGE")); + DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:AllocatedByteSize", "GAUGE")); DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:HitCount", "COUNTER")); DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:EvictionCount", "COUNTER")); DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:ExpirationCount", "COUNTER")); @@ -370,12 +367,8 @@ public static void initDescriptors() throws ClassNotFoundException { CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:HitCount", "COUNTER")); CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:PutCount", "COUNTER")); CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:RemovalCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:MaxMappingCount", "COUNTER")); CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:EvictionCount", "COUNTER")); CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:ExpirationCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:OccupiedByteSize", "SIZE")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:AllocatedByteSize", "SIZE")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:MappingCount", "COUNTER")); CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:HitCount", "COUNTER")); CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:MissCount", "COUNTER")); @@ -384,21 +377,21 @@ public static void initDescriptors() throws ClassNotFoundException { CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:EvictionCount", "COUNTER")); CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:ExpirationCount", "COUNTER")); - POOL_DESCRIPTORS.add(new StatisticDescriptor("Pool:AllocatedSize", "SIZE")); + POOL_DESCRIPTORS.add(new StatisticDescriptor("Pool:AllocatedSize", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:AllocatedMemory", "SIZE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataAllocatedMemory", "SIZE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:OccupiedMemory", "SIZE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataOccupiedMemory", "SIZE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:AllocatedMemory", "GAUGE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataAllocatedMemory", "GAUGE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:OccupiedMemory", "GAUGE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataOccupiedMemory", "GAUGE")); SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:Entries", "COUNTER")); SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:UsedSlotCount", "COUNTER")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataVitalMemory", "SIZE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:VitalMemory", "SIZE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataVitalMemory", "GAUGE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:VitalMemory", "GAUGE")); SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:RemovedSlotCount", "COUNTER")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataSize", "SIZE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:TableCapacity", "SIZE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataSize", "GAUGE")); + SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:TableCapacity", "GAUGE")); - OFFHEAP_RES_DESCRIPTORS.add(new StatisticDescriptor("OffHeapResource:AllocatedMemory", "SIZE")); + OFFHEAP_RES_DESCRIPTORS.add(new StatisticDescriptor("OffHeapResource:AllocatedMemory", "GAUGE")); } } diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java b/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java index eb99c05079..37970e8a50 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java @@ -39,21 +39,23 @@ import org.terracotta.offheapresource.OffHeapResources; import org.terracotta.offheapstore.paging.PageSource; import org.terracotta.statistics.StatisticsManager; +import org.terracotta.statistics.ValueStatistic; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; -import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.Function; import static java.util.stream.Collectors.toMap; import static org.terracotta.offheapresource.OffHeapResourceIdentifier.identifier; +import static org.terracotta.statistics.StatisticsManager.tags; +import static org.terracotta.statistics.SuppliedValueStatistic.supply; +import static org.terracotta.statistics.StatisticType.COUNTER; +import static org.terracotta.statistics.StatisticType.GAUGE; public class EhcacheStateServiceImpl implements EhcacheStateService { @@ -65,23 +67,23 @@ public class EhcacheStateServiceImpl implements EhcacheStateService { private static final String PROPERTY_STORE_KEY = "storeName"; private static final String PROPERTY_POOL_KEY = "poolName"; - private static final Map> STAT_STORE_METHOD_REFERENCES = new HashMap<>(); - private static final Map> STAT_POOL_METHOD_REFERENCES = new HashMap<>(); + private static final Map>> STAT_STORE_METHOD_REFERENCES = new HashMap<>(11); + private static final Map>> STAT_POOL_METHOD_REFERENCES = new HashMap<>(1); static { - STAT_STORE_METHOD_REFERENCES.put("allocatedMemory", ServerStoreImpl::getAllocatedMemory); - STAT_STORE_METHOD_REFERENCES.put("dataAllocatedMemory", ServerStoreImpl::getDataAllocatedMemory); - STAT_STORE_METHOD_REFERENCES.put("occupiedMemory", ServerStoreImpl::getOccupiedMemory); - STAT_STORE_METHOD_REFERENCES.put("dataOccupiedMemory", ServerStoreImpl::getDataOccupiedMemory); - STAT_STORE_METHOD_REFERENCES.put("entries", ServerStoreImpl::getSize); - STAT_STORE_METHOD_REFERENCES.put("usedSlotCount", ServerStoreImpl::getUsedSlotCount); - STAT_STORE_METHOD_REFERENCES.put("dataVitalMemory", ServerStoreImpl::getDataVitalMemory); - STAT_STORE_METHOD_REFERENCES.put("vitalMemory", ServerStoreImpl::getVitalMemory); - STAT_STORE_METHOD_REFERENCES.put("removedSlotCount", ServerStoreImpl::getRemovedSlotCount); - STAT_STORE_METHOD_REFERENCES.put("dataSize", ServerStoreImpl::getDataSize); - STAT_STORE_METHOD_REFERENCES.put("tableCapacity", ServerStoreImpl::getTableCapacity); + STAT_STORE_METHOD_REFERENCES.put("allocatedMemory", store -> supply(GAUGE, store::getAllocatedMemory)); + STAT_STORE_METHOD_REFERENCES.put("dataAllocatedMemory", store -> supply(GAUGE, store::getDataAllocatedMemory)); + STAT_STORE_METHOD_REFERENCES.put("occupiedMemory", store -> supply(GAUGE, store::getOccupiedMemory)); + STAT_STORE_METHOD_REFERENCES.put("dataOccupiedMemory", store -> supply(GAUGE, store::getDataOccupiedMemory)); + STAT_STORE_METHOD_REFERENCES.put("entries", store -> supply(COUNTER, store::getSize)); + STAT_STORE_METHOD_REFERENCES.put("usedSlotCount", store -> supply(COUNTER, store::getUsedSlotCount)); + STAT_STORE_METHOD_REFERENCES.put("dataVitalMemory", store -> supply(GAUGE, store::getDataVitalMemory)); + STAT_STORE_METHOD_REFERENCES.put("vitalMemory", store -> supply(GAUGE, store::getVitalMemory)); + STAT_STORE_METHOD_REFERENCES.put("removedSlotCount", store -> supply(COUNTER, store::getRemovedSlotCount)); + STAT_STORE_METHOD_REFERENCES.put("dataSize", store -> supply(GAUGE, store::getDataSize)); + STAT_STORE_METHOD_REFERENCES.put("tableCapacity", store -> supply(GAUGE, store::getTableCapacity)); - STAT_POOL_METHOD_REFERENCES.put("allocatedSize", ResourcePageSource::getAllocatedSize); + STAT_POOL_METHOD_REFERENCES.put("allocatedSize", pool -> supply(GAUGE, pool::getAllocatedSize)); } private final OffHeapResources offHeapResources; @@ -304,13 +306,12 @@ private ResourcePageSource createPageSource(String poolName, ServerSideConfigura private void registerStoreStatistics(ServerStoreImpl store, String storeName) { STAT_STORE_METHOD_REFERENCES.forEach((key, value) -> - registerStatistic(store, storeName, key, STATISTICS_STORE_TAG, PROPERTY_STORE_KEY, () -> value.apply(store) )); + registerStatistic(store, storeName, key, STATISTICS_STORE_TAG, PROPERTY_STORE_KEY, value.apply(store))); } private void registerPoolStatistics(String poolName, ResourcePageSource pageSource) { - STAT_POOL_METHOD_REFERENCES.forEach((key, value)-> - registerStatistic(pageSource, poolName, key, STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, () -> value.apply(pageSource)) - ); + STAT_POOL_METHOD_REFERENCES.forEach((key, value) -> + registerStatistic(pageSource, poolName, key, STATISTICS_POOL_TAG, PROPERTY_POOL_KEY, value.apply(pageSource))); } private void unRegisterStoreStatistics(ServerStoreImpl store) { @@ -329,13 +330,12 @@ private void unRegisterPoolStatistics(ResourcePageSource pageSource) { } } - private void registerStatistic(Object context, String name, String observerName, String tag, String propertyKey, Callable callable) { - Set tags = new HashSet<>(Arrays.asList(tag, "tier")); + private void registerStatistic(Object context, String name, String observerName, String tag, String propertyKey, ValueStatistic source) { Map properties = new HashMap<>(); properties.put("discriminator", tag); properties.put(propertyKey, name); - StatisticsManager.createPassThroughStatistic(context, observerName, tags, properties, callable); + StatisticsManager.createPassThroughStatistic(context, observerName, tags(tag, "tier"), properties, source); } private void releaseDedicatedPool(String name, PageSource pageSource) { diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java b/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java index bcbc015abf..84013c85c1 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java @@ -31,7 +31,7 @@ import java.util.stream.Collectors; import static java.util.Arrays.asList; -import static org.terracotta.context.extended.ValueStatisticDescriptor.descriptor; +import static org.terracotta.statistics.registry.ValueStatisticDescriptor.descriptor; @Named("PoolStatistics") @RequiredContext({@Named("consumerId"), @Named("type"), @Named("alias")}) @@ -53,7 +53,7 @@ public Collection> getExposedObjects() { @Override protected StatisticRegistry getStatisticRegistry(PoolBinding managedObject) { if (managedObject == PoolBinding.ALL_SHARED) { - return StatisticRegistry.noop(); + return new StatisticRegistry(null, () -> getTimeSource().getTimestamp()); } String poolName = managedObject.getAlias(); @@ -76,7 +76,7 @@ private static class PoolExposedStatistics extends AbstractExposedStatistics getKnownStatistics(); + Map> getKnownStatistics(); /** * Map of tier statistics on this cache. Per tier name diff --git a/core/src/main/java/org/ehcache/core/statistics/TierStatistics.java b/core/src/main/java/org/ehcache/core/statistics/TierStatistics.java index d259a1f220..a86946cb55 100644 --- a/core/src/main/java/org/ehcache/core/statistics/TierStatistics.java +++ b/core/src/main/java/org/ehcache/core/statistics/TierStatistics.java @@ -16,6 +16,8 @@ package org.ehcache.core.statistics; +import org.terracotta.statistics.ValueStatistic; + import java.util.Map; /** @@ -28,10 +30,10 @@ public interface TierStatistics { * * @return a map of statistics per name */ - Map getKnownStatistics(); + Map> getKnownStatistics(); /** - * Reset the values for this tier. However, note that {@code mapping, maxMappings, allocatedMemory, occupiedMemory} + * Reset the values for this tier. However, note that {@code mapping, allocatedMemory, occupiedMemory} * won't be reset since it doesn't make sense. *

* Implementation note: Calling clear doesn't really clear the data. It freezes the actual values and compensate @@ -88,13 +90,6 @@ public interface TierStatistics { */ long getMappings(); - /** - * Maximum number of entries that was contained in this tier - * - * @return number of entries - */ - long getMaxMappings(); - /** * How many bytes are currently allocated (occupied or not) for this tier * diff --git a/core/src/main/java/org/ehcache/core/statistics/TypedValueStatistic.java b/core/src/main/java/org/ehcache/core/statistics/TypedValueStatistic.java deleted file mode 100644 index bcad2eb6d0..0000000000 --- a/core/src/main/java/org/ehcache/core/statistics/TypedValueStatistic.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright Terracotta, Inc. - * - * 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 org.ehcache.core.statistics; - -import org.terracotta.statistics.ValueStatistic; -import org.terracotta.statistics.extended.StatisticType; - -/** - * Represent a {@code ValueStatistic} that knows its {@code StatisticType}. - */ -public abstract class TypedValueStatistic implements ValueStatistic { - private final StatisticType type; - - /** - * Type of this value statistic. Can be COUNTER or SIZE. - * - * @param type {@code StatisticType} - */ - public TypedValueStatistic(StatisticType type) { - this.type = type; - } - - public StatisticType getType() { - return type; - } -} diff --git a/gradle.properties b/gradle.properties index 51b310a403..c149306ebf 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,15 +1,15 @@ # Terracotta third parties offheapVersion = 2.4.0 -statisticVersion = 1.5.0 +statisticVersion = 2.0.0 jcacheVersion = 1.1.0 slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre9 +terracottaPlatformVersion = 5.4.0-pre10 terracottaApisVersion = 1.4.0-pre8 -terracottaCoreVersion = 5.4.0-pre15 +terracottaCoreVersion = 5.4.0-pre16 terracottaPassthroughTestingVersion = 1.4.0-pre9 # Test lib versions diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java index f5d205148b..dac28dc393 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java @@ -28,17 +28,17 @@ import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.core.statistics.CacheStatistics; import org.ehcache.core.statistics.TierStatistics; -import org.ehcache.core.statistics.TypedValueStatistic; import org.terracotta.statistics.OperationStatistic; +import org.terracotta.statistics.ValueStatistic; import org.terracotta.statistics.derived.LatencySampling; import org.terracotta.statistics.derived.MinMaxAverage; -import org.terracotta.statistics.extended.StatisticType; import org.terracotta.statistics.observer.ChainedOperationObserver; import static java.util.EnumSet.allOf; import static org.ehcache.impl.internal.statistics.StatsUtils.findLowestTier; import static org.ehcache.impl.internal.statistics.StatsUtils.findOperationStatisticOnChildren; import static org.ehcache.impl.internal.statistics.StatsUtils.findTiers; +import static org.terracotta.statistics.SuppliedValueStatistic.counter; /** * Contains usage statistics relative to a given cache. @@ -63,7 +63,7 @@ class DefaultCacheStatistics implements CacheStatistics { private final Map tierStatistics; private final TierStatistics lowestTier; - private final Map knownStatistics; + private final Map> knownStatistics; public DefaultCacheStatistics(InternalCache cache) { bulkMethodEntries = cache.getBulkMethodEntries(); @@ -100,44 +100,14 @@ public DefaultCacheStatistics(InternalCache cache) { knownStatistics = createKnownStatistics(); } - private Map createKnownStatistics() { - Map knownStatistics = new HashMap<>(30); - knownStatistics.put("Cache:HitCount", new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getCacheHits(); - } - }); - knownStatistics.put("Cache:MissCount", new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getCacheMisses(); - } - }); - knownStatistics.put("Cache:PutCount", new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getCachePuts(); - } - }); - knownStatistics.put("Cache:RemovalCount", new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getCacheRemovals(); - } - }); - knownStatistics.put("Cache:EvictionCount", new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getCacheEvictions(); - } - }); - knownStatistics.put("Cache:ExpirationCount", new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getCacheExpirations(); - } - }); + private Map> createKnownStatistics() { + Map> knownStatistics = new HashMap<>(30); + knownStatistics.put("Cache:HitCount", counter(this::getCacheHits)); + knownStatistics.put("Cache:MissCount", counter(this::getCacheMisses)); + knownStatistics.put("Cache:PutCount", counter(this::getCachePuts)); + knownStatistics.put("Cache:RemovalCount", counter(this::getCacheRemovals)); + knownStatistics.put("Cache:EvictionCount", counter(this::getCacheEvictions)); + knownStatistics.put("Cache:ExpirationCount", counter(this::getCacheExpirations)); for (TierStatistics tier : tierStatistics.values()) { knownStatistics.putAll(tier.getKnownStatistics()); @@ -146,14 +116,17 @@ public Number value() { return Collections.unmodifiableMap(knownStatistics); } - public Map getKnownStatistics() { + @Override + public Map> getKnownStatistics() { return knownStatistics; } + @Override public Map getTierStatistics() { return Collections.unmodifiableMap(tierStatistics); } + @Override public void clear() { compensatingCounters = compensatingCounters.snapshot(this); averageGetTime.clear(); @@ -164,29 +137,35 @@ public void clear() { } } + @Override public long getCacheHits() { return normalize(getHits() - compensatingCounters.cacheHits); } + @Override public float getCacheHitPercentage() { long cacheHits = getCacheHits(); return normalize((float) cacheHits / (cacheHits + getCacheMisses())) * 100.0f; } + @Override public long getCacheMisses() { return normalize(getMisses() - compensatingCounters.cacheMisses); } + @Override public float getCacheMissPercentage() { long cacheMisses = getCacheMisses(); return normalize((float) cacheMisses / (getCacheHits() + cacheMisses)) * 100.0f; } + @Override public long getCacheGets() { return normalize(getHits() + getMisses() - compensatingCounters.cacheGets); } + @Override public long getCachePuts() { return normalize(getBulkCount(BulkOps.PUT_ALL) + put.sum(EnumSet.of(CacheOperationOutcomes.PutOutcome.PUT)) + @@ -195,6 +174,7 @@ public long getCachePuts() { compensatingCounters.cachePuts); } + @Override public long getCacheRemovals() { return normalize(getBulkCount(BulkOps.REMOVE_ALL) + remove.sum(EnumSet.of(CacheOperationOutcomes.RemoveOutcome.SUCCESS)) + @@ -202,22 +182,27 @@ public long getCacheRemovals() { compensatingCounters.cacheRemovals); } + @Override public long getCacheEvictions() { return normalize(lowestTier.getEvictions()); } + @Override public long getCacheExpirations() { return normalize(lowestTier.getExpirations()); } + @Override public float getCacheAverageGetTime() { return (float) averageGetTime.value(); } + @Override public float getCacheAveragePutTime() { return (float) averagePutTime.value(); } + @Override public float getCacheAverageRemoveTime() { return (float) averageRemoveTime.value(); } diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java index 10a328d5c1..7379387ee1 100755 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java @@ -16,35 +16,32 @@ package org.ehcache.impl.internal.statistics; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; - import org.ehcache.Cache; import org.ehcache.core.statistics.StoreOperationOutcomes; import org.ehcache.core.statistics.TierOperationOutcomes; import org.ehcache.core.statistics.TierStatistics; -import org.ehcache.core.statistics.TypedValueStatistic; -import org.terracotta.statistics.ConstantValueStatistic; import org.terracotta.statistics.OperationStatistic; import org.terracotta.statistics.ValueStatistic; -import org.terracotta.statistics.extended.StatisticType; +import org.terracotta.statistics.ZeroOperationStatistic; + +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; import static org.ehcache.impl.internal.statistics.StatsUtils.findStatisticOnDescendants; +import static org.terracotta.statistics.SuppliedValueStatistic.counter; +import static org.terracotta.statistics.SuppliedValueStatistic.gauge; /** * Contains usage statistics relative to a given tier. */ class DefaultTierStatistics implements TierStatistics { - private static final ValueStatistic NOT_AVAILABLE = ConstantValueStatistic.instance(-1L); - private volatile CompensatingCounters compensatingCounters = CompensatingCounters.empty(); - private final String tierName; - - private final Map knownStatistics; + private final Map> knownStatistics; private final OperationStatistic get; private final OperationStatistic put; @@ -57,13 +54,14 @@ class DefaultTierStatistics implements TierStatistics { private final OperationStatistic expiration; private final OperationStatistic compute; private final OperationStatistic computeIfAbsent; - private final ValueStatistic mapping; - private final ValueStatistic maxMapping; - private final ValueStatistic allocatedMemory; - private final ValueStatistic occupiedMemory; + + //Ehcache default to -1 if unavailable, but the management layer needs optional or null + // (since -1 can be a normal value for a stat). + private final Optional> mapping; + private final Optional> allocatedMemory; + private final Optional> occupiedMemory; public DefaultTierStatistics(Cache cache, String tierName) { - this.tierName = tierName; get = findOperationStatistic(cache, tierName, "tier", "get"); put = findOperationStatistic(cache, tierName, "put"); @@ -78,121 +76,54 @@ public DefaultTierStatistics(Cache cache, String tierName) { computeIfAbsent = findOperationStatistic(cache, tierName, "computeIfAbsent"); mapping = findValueStatistics(cache, tierName, "mappings"); - maxMapping = findValueStatistics(cache, tierName, "maxMappings"); allocatedMemory = findValueStatistics(cache, tierName, "allocatedMemory"); occupiedMemory = findValueStatistics(cache, tierName, "occupiedMemory"); - Map knownStatistics = createKnownStatistics(tierName); + Map> knownStatistics = createKnownStatistics(tierName); this.knownStatistics = Collections.unmodifiableMap(knownStatistics); } - private Map createKnownStatistics(String tierName) { - Map knownStatistics = new HashMap<>(7); - addKnownStatistic(knownStatistics, tierName, "HitCount", get, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getHits(); - } - }); - addKnownStatistic(knownStatistics, tierName, "MissCount", get, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getMisses(); - } - }); - addKnownStatistic(knownStatistics, tierName, "PutCount", get, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getPuts(); - } - }); - addKnownStatistic(knownStatistics, tierName, "RemovalCount", get, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getRemovals(); - } - }); - addKnownStatistic(knownStatistics, tierName, "EvictionCount", get, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getEvictions(); - } - }); - addKnownStatistic(knownStatistics, tierName, "ExpirationCount", get, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getExpirations(); - } - }); - addKnownStatistic(knownStatistics, tierName, "MappingCount", mapping, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getMappings(); - } - }); - addKnownStatistic(knownStatistics, tierName, "MaxMappingCount", maxMapping, new TypedValueStatistic(StatisticType.COUNTER) { - @Override - public Number value() { - return getMaxMappings(); - } - }); - addKnownStatistic(knownStatistics, tierName, "AllocatedByteSize", allocatedMemory, new TypedValueStatistic(StatisticType.SIZE) { - @Override - public Number value() { - return getAllocatedByteSize(); - } - }); - addKnownStatistic(knownStatistics, tierName, "OccupiedByteSize", occupiedMemory, new TypedValueStatistic(StatisticType.SIZE) { - @Override - public Number value() { - return getOccupiedByteSize(); - } - }); + private Map> createKnownStatistics(String tierName) { + Map> knownStatistics = new HashMap<>(7); + knownStatistics.put(tierName + ":HitCount", counter(this::getHits)); + knownStatistics.put(tierName + ":MissCount", counter(this::getMisses)); + knownStatistics.put(tierName + ":PutCount", counter(this::getPuts)); + knownStatistics.put(tierName + ":RemovalCount", counter(this::getRemovals)); + knownStatistics.put(tierName + ":EvictionCount", counter(this::getEvictions)); + knownStatistics.put(tierName + ":ExpirationCount", counter(this::getExpirations)); + mapping.ifPresent(longValueStatistic -> knownStatistics.put(tierName + ":MappingCount", counter(this::getMappings))); + allocatedMemory.ifPresent(longValueStatistic -> knownStatistics.put(tierName + ":AllocatedByteSize", gauge(this::getAllocatedByteSize))); + occupiedMemory.ifPresent(longValueStatistic -> knownStatistics.put(tierName + ":OccupiedByteSize", gauge(this::getOccupiedByteSize))); return knownStatistics; } - public Map getKnownStatistics() { + @Override + public Map> getKnownStatistics() { return knownStatistics; } - private static void addKnownStatistic(Map knownStatistics, String tierName, String name, Object stat, TypedValueStatistic statistic) { - if (stat != NOT_AVAILABLE) { - knownStatistics.put(tierName + ":" + name, statistic); - } - } - private > OperationStatistic findOperationStatistic(Cache cache, String tierName, String tag, String stat) { - OperationStatistic s = findStatisticOnDescendants(cache, tierName, tag, stat); - if(s == null) { - return ZeroOperationStatistic.get(); - } - return s; + return StatsUtils.>findStatisticOnDescendants(cache, tierName, tag, stat).orElse(ZeroOperationStatistic.get()); } private > OperationStatistic findOperationStatistic(Cache cache, String tierName, String stat) { - OperationStatistic s = findStatisticOnDescendants(cache, tierName, stat); - if(s == null) { - return ZeroOperationStatistic.get(); - } - return s; + return StatsUtils.>findStatisticOnDescendants(cache, tierName, stat).orElse(ZeroOperationStatistic.get()); } - private ValueStatistic findValueStatistics(Cache cache, String tierName, String statName) { - ValueStatistic stat = findStatisticOnDescendants(cache, tierName, statName); - if (stat == null) { - return NOT_AVAILABLE; - } - return stat; + private Optional> findValueStatistics(Cache cache, String tierName, String statName) { + return findStatisticOnDescendants(cache, tierName, statName); } /** - * Reset the values for this tier. However, note that {@code mapping, maxMappings, allocatedMemory, occupiedMemory} + * Reset the values for this tier. However, note that {@code mapping, allocatedMemory, occupiedMemory} * but be reset since it doesn't make sense. */ + @Override public void clear() { compensatingCounters = compensatingCounters.snapshot(this); } + @Override public long getHits() { return get.sum(EnumSet.of(TierOperationOutcomes.GetOutcome.HIT)) + putIfAbsent.sum(EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.HIT)) + @@ -204,6 +135,7 @@ public long getHits() { compensatingCounters.hits; } + @Override public long getMisses() { return get.sum(EnumSet.of(TierOperationOutcomes.GetOutcome.MISS)) + putIfAbsent.sum(EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT)) + @@ -214,6 +146,7 @@ public long getMisses() { compensatingCounters.misses; } + @Override public long getPuts() { return put.sum(EnumSet.of(StoreOperationOutcomes.PutOutcome.PUT)) + putIfAbsent.sum(EnumSet.of(StoreOperationOutcomes.PutIfAbsentOutcome.PUT)) + @@ -224,6 +157,7 @@ public long getPuts() { compensatingCounters.puts; } + @Override public long getRemovals() { return remove.sum(EnumSet.of(StoreOperationOutcomes.RemoveOutcome.REMOVED)) + compute.sum(EnumSet.of(StoreOperationOutcomes.ComputeOutcome.REMOVED)) + @@ -231,29 +165,30 @@ public long getRemovals() { compensatingCounters.removals; } + @Override public long getEvictions() { return eviction.sum(EnumSet.of(TierOperationOutcomes.EvictionOutcome.SUCCESS)) - compensatingCounters.evictions; } + @Override public long getExpirations() { return expiration.sum() - compensatingCounters.expirations; } + @Override public long getMappings() { - return mapping.value(); - } - - public long getMaxMappings() { - return maxMapping.value(); + return mapping.map(ValueStatistic::value).orElse(-1L); } + @Override public long getAllocatedByteSize() { - return allocatedMemory.value(); + return allocatedMemory.map(ValueStatistic::value).orElse(-1L); } + @Override public long getOccupiedByteSize() { - return occupiedMemory.value(); + return occupiedMemory.map(ValueStatistic::value).orElse(-1L); } private static class CompensatingCounters { diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java index d78bb723fb..bd5bc41864 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/StatsUtils.java @@ -18,6 +18,7 @@ import java.util.Collections; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.ehcache.Cache; @@ -71,7 +72,7 @@ protected boolean matchesSafely(Map properties) { * @return the wanted statistic or null if no such statistic is found * @throws RuntimeException when more than one matching statistic is found */ - static T findStatisticOnDescendants(Object context, String discriminator, String tag, String statName) { + static Optional findStatisticOnDescendants(Object context, String discriminator, String tag, String statName) { @SuppressWarnings("unchecked") Set statResult = queryBuilder() @@ -89,11 +90,11 @@ static T findStatisticOnDescendants(Object context, String discriminator, St if (statResult.size() == 1) { @SuppressWarnings("unchecked") T result = (T) statResult.iterator().next().getContext().attributes().get("this"); - return result; + return Optional.ofNullable(result); } // No such stat in this context - return null; + return Optional.empty(); } /** @@ -106,7 +107,7 @@ static T findStatisticOnDescendants(Object context, String discriminator, St * @return the wanted statistic or null if no such statistic is found * @throws RuntimeException when more than one matching statistic is found */ - static T findStatisticOnDescendants(Object context, String tag, String statName) { + static Optional findStatisticOnDescendants(Object context, String tag, String statName) { @SuppressWarnings("unchecked") Set statResult = queryBuilder() @@ -123,11 +124,11 @@ static T findStatisticOnDescendants(Object context, String tag, String statN if (statResult.size() == 1) { @SuppressWarnings("unchecked") T result = (T) statResult.iterator().next().getContext().attributes().get("this"); - return result; + return Optional.ofNullable(result); } // No such stat in this context - return null; + return Optional.empty(); } /** diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/ZeroOperationStatistic.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/ZeroOperationStatistic.java deleted file mode 100644 index 7067025f9b..0000000000 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/ZeroOperationStatistic.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Copyright Terracotta, Inc. - * - * 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 org.ehcache.impl.internal.statistics; - -import java.util.Set; - -import org.terracotta.statistics.OperationStatistic; -import org.terracotta.statistics.ValueStatistic; -import org.terracotta.statistics.observer.ChainedOperationObserver; - -/** - * An operation statistic that always return 0 for everything. Used as a null object. - */ -class ZeroOperationStatistic> implements OperationStatistic { - - @SuppressWarnings("rawtypes") - private static final OperationStatistic INSTANCE = new ZeroOperationStatistic(); - - @SuppressWarnings("unchecked") - public static > OperationStatistic get() { - return (OperationStatistic) INSTANCE; - } - - @Override - public Class type() { - return null; - } - - @Override - public ValueStatistic statistic(T result) { - return null; - } - - @Override - public ValueStatistic statistic(Set results) { - return null; - } - - @Override - public long count(T type) { - return 0; - } - - @Override - public long sum(Set types) { - return 0; - } - - @Override - public long sum() { - return 0; - } - - @Override - public void addDerivedStatistic(ChainedOperationObserver derived) { - - } - - @Override - public void removeDerivedStatistic(ChainedOperationObserver derived) { - - } - - @Override - public void begin() { - - } - - @Override - public void end(T result) { - - } - - @Override - public void end(T result, long... parameters) { - - } -} diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index 2479fe0919..a01d7c187d 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -96,6 +96,8 @@ import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; import static org.ehcache.core.exceptions.StorePassThroughException.handleRuntimeException; import static org.terracotta.statistics.StatisticBuilder.operation; +import static org.terracotta.statistics.StatisticType.COUNTER; +import static org.terracotta.statistics.StatisticType.GAUGE; /** * {@link Store} and {@link HigherCachingTier} implementation for on heap. @@ -259,14 +261,11 @@ public OnHeapStore(final Configuration config, final TimeSource timeSource silentInvalidateAllWithHashObserver = operation(HigherCachingTierOperationOutcomes.SilentInvalidateAllWithHashOutcome.class).named("silentInvalidateAllWithHash").of(this).tag(STATISTICS_TAG).build(); Set tags = new HashSet<>(Arrays.asList(STATISTICS_TAG, "tier")); - StatisticsManager.createPassThroughStatistic(this, "mappings", tags, () -> map.mappingCount()); - StatisticsManager.createPassThroughStatistic(this, "occupiedMemory", tags, () -> { - if (byteSized) { - return map.byteSize(); - } else { - return -1L; - } - }); + StatisticsManager.createPassThroughStatistic(this, "mappings", tags, COUNTER, () -> map.mappingCount()); + + if(byteSized) { + StatisticsManager.createPassThroughStatistic(this, "occupiedMemory", tags, GAUGE, () -> map.byteSize()); + } } @Override diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index 137d78481d..fc41da724a 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -16,11 +16,10 @@ package org.ehcache.impl.internal.store.offheap; +import java.io.Serializable; import java.time.Duration; -import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -53,11 +52,14 @@ import org.slf4j.LoggerFactory; import org.terracotta.offheapstore.exceptions.OversizeMappingException; import org.terracotta.statistics.StatisticsManager; +import org.terracotta.statistics.StatisticType; import org.terracotta.statistics.observer.OperationObserver; import static org.ehcache.core.config.ExpiryUtils.isExpiryDurationInfinite; import static org.ehcache.core.exceptions.StorePassThroughException.handleRuntimeException; import static org.terracotta.statistics.StatisticBuilder.operation; +import static org.terracotta.statistics.StatisticsManager.tags; +import static org.terracotta.statistics.StatisticType.GAUGE; public abstract class AbstractOffHeapStore implements AuthoritativeTier, LowerCachingTier { @@ -132,56 +134,31 @@ public AbstractOffHeapStore(String statisticsTag, Configuration config, Ti this.getAndRemoveObserver= operation(LowerCachingTierOperationsOutcome.GetAndRemoveOutcome.class).of(this).named("getAndRemove").tag(statisticsTag).build(); this.installMappingObserver= operation(LowerCachingTierOperationsOutcome.InstallMappingOutcome.class).of(this).named("installMapping").tag(statisticsTag).build(); - Set tags = new HashSet<>(Arrays.asList(statisticsTag, "tier")); - StatisticsManager.createPassThroughStatistic(this, "allocatedMemory", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.allocatedMemory(); - }); - StatisticsManager.createPassThroughStatistic(this, "occupiedMemory", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.occupiedMemory(); - }); - StatisticsManager.createPassThroughStatistic(this, "dataAllocatedMemory", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.dataAllocatedMemory(); - }); - StatisticsManager.createPassThroughStatistic(this, "dataOccupiedMemory", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.dataOccupiedMemory(); - }); - StatisticsManager.createPassThroughStatistic(this, "dataSize", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.dataSize(); - }); - StatisticsManager.createPassThroughStatistic(this, "dataVitalMemory", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.dataVitalMemory(); - }); - StatisticsManager.createPassThroughStatistic(this, "mappings", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.longSize(); - }); - StatisticsManager.createPassThroughStatistic(this, "maxMappings", tags, () -> -1L); - StatisticsManager.createPassThroughStatistic(this, "vitalMemory", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.vitalMemory(); - }); - StatisticsManager.createPassThroughStatistic(this, "removedSlotCount", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.removedSlotCount(); - }); - StatisticsManager.createPassThroughStatistic(this, "usedSlotCount", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.usedSlotCount(); - }); - StatisticsManager.createPassThroughStatistic(this, "tableCapacity", tags, () -> { - EhcacheOffHeapBackingMap> map = backingMap(); - return map == null ? -1L : map.tableCapacity(); - }); + registerStatistic("allocatedMemory", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::allocatedMemory); + registerStatistic("occupiedMemory", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::occupiedMemory); + registerStatistic("dataAllocatedMemory", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::dataAllocatedMemory); + registerStatistic("dataOccupiedMemory", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::dataOccupiedMemory); + registerStatistic("dataSize", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::dataSize); + registerStatistic("dataVitalMemory", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::dataVitalMemory); + registerStatistic("mappings", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::longSize); + registerStatistic("vitalMemory", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::vitalMemory); + registerStatistic("removedSlotCount", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::removedSlotCount); + registerStatistic("usedSlotCount", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::usedSlotCount); + registerStatistic("tableCapacity", GAUGE, statisticsTag, EhcacheOffHeapBackingMap::tableCapacity); this.mapEvictionListener = new BackingMapEvictionListener<>(eventDispatcher, evictionObserver); } + private void registerStatistic(String name, StatisticType type, String tag, Function>, T> fn) { + StatisticsManager.createPassThroughStatistic(this, name, tags(tag, "tier"), type, () -> { + EhcacheOffHeapBackingMap> map = backingMap(); + // Returning null means not available. + // Do not return -1 because a stat can be negative and it's hard to tell the difference + // between -1 meaning unavailable for a stat and for the other one -1 being a right value; + return map == null ? null : fn.apply(map); + }); + } + @Override public Store.ValueHolder get(K key) throws StoreAccessException { checkKey(key); diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java index 1e375edcbd..8fbdcef5b8 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java @@ -63,7 +63,7 @@ public void before() { @After public void after() { - if(cacheManager != null) { + if (cacheManager != null) { cacheManager.close(); } } @@ -74,7 +74,7 @@ public void getKnownStatistics() { "Cache:RemovalCount", "Cache:EvictionCount", "Cache:PutCount", "OnHeap:ExpirationCount", "Cache:ExpirationCount", "OnHeap:HitCount", "OnHeap:MissCount", "OnHeap:PutCount", "OnHeap:RemovalCount", "OnHeap:EvictionCount", - "OnHeap:MappingCount", "OnHeap:OccupiedByteSize"); + "OnHeap:MappingCount"); } @Test @@ -163,6 +163,6 @@ public void getCacheAverageRemoveTime() throws Exception { } private AbstractObjectAssert assertStat(String key) { - return assertThat(cacheStatistics.getKnownStatistics().get(key).value()); + return assertThat((Number) cacheStatistics.getKnownStatistics().get(key).value()); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java index 27113b5fa0..f1ea506022 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultTierStatisticsTest.java @@ -70,9 +70,7 @@ public void after() { @Test public void getKnownStatistics() { - assertThat(onHeap.getKnownStatistics()).containsOnlyKeys("OnHeap:HitCount", "OnHeap:MissCount", - "OnHeap:PutCount", "OnHeap:RemovalCount", "OnHeap:EvictionCount", "OnHeap:ExpirationCount", "OnHeap:MappingCount", - "OnHeap:OccupiedByteSize"); + assertThat(onHeap.getKnownStatistics()).containsOnlyKeys("OnHeap:HitCount", "OnHeap:MissCount", "OnHeap:PutCount", "OnHeap:RemovalCount", "OnHeap:EvictionCount", "OnHeap:ExpirationCount", "OnHeap:MappingCount"); } @Test @@ -138,12 +136,6 @@ public void getMappings() throws Exception { assertStat("OnHeap:MappingCount").isEqualTo(1L); } - @Test - public void getMaxMappings() throws Exception { - cache.put(1L, "a"); - assertThat(onHeap.getAllocatedByteSize()).isEqualTo(-1L); - } - @Test public void getAllocatedByteSize() throws Exception { cache.put(1L, "a"); @@ -157,6 +149,6 @@ public void getOccupiedByteSize() throws Exception { } private AbstractObjectAssert assertStat(String key) { - return assertThat(onHeap.getKnownStatistics().get(key).value()); + return assertThat((Number) onHeap.getKnownStatistics().get(key).value()); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/StatsUtilsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/StatsUtilsTest.java index b36a648c6c..1bc78f9fef 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/StatsUtilsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/StatsUtilsTest.java @@ -16,11 +16,6 @@ package org.ehcache.impl.internal.statistics; -import java.util.Collections; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.Callable; - import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; @@ -39,6 +34,12 @@ import org.terracotta.context.query.Query; import org.terracotta.statistics.OperationStatistic; import org.terracotta.statistics.StatisticsManager; +import org.terracotta.statistics.StatisticType; + +import java.util.Collections; +import java.util.Map; +import java.util.Optional; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; @@ -52,6 +53,8 @@ import static org.terracotta.context.query.Matchers.context; import static org.terracotta.context.query.Matchers.hasAttribute; import static org.terracotta.context.query.QueryBuilder.queryBuilder; +import static org.terracotta.statistics.StatisticsManager.properties; +import static org.terracotta.statistics.StatisticsManager.tags; public class StatsUtilsTest { @@ -72,14 +75,14 @@ public void before() { cache = cacheManager.getCache("aCache", Long.class, String.class); - StatisticsManager.createPassThroughStatistic(cache, "test", Collections.emptySet(), Collections.singletonMap("myproperty", "myvalue"), (Callable) () -> 0); + StatisticsManager.createPassThroughStatistic(cache, "test", tags(), properties("myproperty=myvalue"), StatisticType.COUNTER, () -> 0); cache.get(1L); } @After public void after() { - if(cacheManager != null) { + if (cacheManager != null) { cacheManager.close(); } } @@ -134,7 +137,7 @@ private Set queryProperty(String key, String value) { .filter(context(attributes(Matchers.>allOf( hasAttribute("name", "test"), hasProperty(key, value) - )))) + )))) .build(); return statQuery.execute(Collections.singleton(ContextManager.nodeFor(cache))); @@ -143,27 +146,27 @@ private Set queryProperty(String key, String value) { @SuppressWarnings("unchecked") @Test public void testFindStatisticOnDescendantsWithDiscriminator() throws Exception { - OperationStatistic stat = findStatisticOnDescendants(cache, "OnHeap", "tier", "get"); - assertThat(stat.sum()).isEqualTo(1L); + Optional> stat = findStatisticOnDescendants(cache, "OnHeap", "tier", "get"); + assertThat(stat.get().sum()).isEqualTo(1L); stat = findStatisticOnDescendants(cache, "OnHeap", "tier", "xxx"); - assertThat(stat).isNull(); + assertThat(stat.isPresent()).isFalse(); stat = findStatisticOnDescendants(cache, "xxx", "tier", "xxx"); - assertThat(stat).isNull(); + assertThat(stat.isPresent()).isFalse(); } @SuppressWarnings("unchecked") @Test public void testFindStatisticOnDescendants() throws Exception { - OperationStatistic stat = findStatisticOnDescendants(cache, "OnHeap", "get"); - assertThat(stat.sum()).isEqualTo(1L); + Optional> stat = findStatisticOnDescendants(cache, "OnHeap", "get"); + assertThat(stat.get().sum()).isEqualTo(1L); stat = findStatisticOnDescendants(cache, "OnHeap", "xxx"); - assertThat(stat).isNull(); + assertThat(stat.isPresent()).isFalse(); stat = findStatisticOnDescendants(cache, "xxx", "xxx"); - assertThat(stat).isNull(); + assertThat(stat.isPresent()).isFalse(); } @Test @@ -186,19 +189,19 @@ public void testFindTiers() { @Test public void testFindLowerTier_one() { - String tier = findLowestTier(new String[] { "OnHeap" }); + String tier = findLowestTier(new String[]{"OnHeap"}); assertThat(tier).isEqualTo("OnHeap"); } @Test public void testFindLowerTier_two() { - String tier = findLowestTier(new String[] { "OnHeap", "Offheap" }); + String tier = findLowestTier(new String[]{"OnHeap", "Offheap"}); assertThat(tier).isEqualTo("Offheap"); } @Test public void testFindLowerTier_three() { - String tier = findLowestTier(new String[] { "OnHeap", "Offheap", "Disk" }); + String tier = findLowestTier(new String[]{"OnHeap", "Offheap", "Disk"}); assertThat(tier).isEqualTo("Disk"); } diff --git a/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java b/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java index a6997c6c8d..212dff7a5a 100644 --- a/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/statistics/TierCalculationTest.java @@ -290,15 +290,6 @@ public void testMappingCount() { assertThat(tierStatistics.getMappings()).isEqualTo(1); } - @Test - public void testMaxMappingCount() { - assertThat(tierStatistics.getMaxMappings()).isEqualTo(-1); // FIXME Shouldn't it be 0? - cache.put(1, "a"); - cache.put(2, "b"); - cache.remove(1); - assertThat(tierStatistics.getMappings()).isEqualTo(1); // FIXME: I was expecting 2 - } - @Test public void testAllocatedByteSize() { assumeFalse(tierName.equals("OnHeap")); // FIXME: Not calculated for OnHeap when a size is allocated diff --git a/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java b/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java index 5ec1af5aca..7a54f1af0d 100644 --- a/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java +++ b/management/src/main/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProvider.java @@ -16,6 +16,7 @@ package org.ehcache.management.providers.statistics; import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.time.TimeSource; import org.ehcache.management.ManagementRegistryServiceConfiguration; import org.ehcache.management.providers.CacheBinding; import org.ehcache.management.providers.CacheBindingManagementProvider; @@ -23,67 +24,56 @@ import org.terracotta.management.model.capabilities.descriptors.Descriptor; import org.terracotta.management.model.capabilities.descriptors.StatisticDescriptor; import org.terracotta.management.model.context.Context; +import org.terracotta.management.registry.DefaultStatisticsManagementProvider; import org.terracotta.management.registry.Named; -import org.terracotta.management.registry.ExposedObject; import org.terracotta.management.registry.collect.StatisticProvider; +import org.terracotta.statistics.registry.Statistic; -import java.util.ArrayList; +import java.io.Serializable; import java.util.Collection; import java.util.Collections; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; import java.util.Map; -import java.util.TreeMap; +import java.util.Objects; + +import static java.util.stream.Collectors.toList; @Named("StatisticsCapability") @StatisticProvider public class EhcacheStatisticsProvider extends CacheBindingManagementProvider { - private static final Comparator STATISTIC_DESCRIPTOR_COMPARATOR = Comparator.comparing(StatisticDescriptor::getName); - private final StatisticsService statisticsService; + private final TimeSource timeSource; - public EhcacheStatisticsProvider(ManagementRegistryServiceConfiguration configuration, StatisticsService statisticsService) { + public EhcacheStatisticsProvider(ManagementRegistryServiceConfiguration configuration, StatisticsService statisticsService, TimeSource timeSource) { super(configuration); - this.statisticsService = statisticsService; + this.statisticsService = Objects.requireNonNull(statisticsService); + this.timeSource = Objects.requireNonNull(timeSource); } @Override protected ExposedCacheBinding wrap(CacheBinding cacheBinding) { - return new StandardEhcacheStatistics(registryConfiguration, cacheBinding, statisticsService); + return new StandardEhcacheStatistics(registryConfiguration, cacheBinding, statisticsService, timeSource); } @Override public final Collection getDescriptors() { - Collection capabilities = new HashSet<>(); - for (ExposedObject o : getExposedObjects()) { - capabilities.addAll(((StandardEhcacheStatistics) o).getDescriptors()); - } - List list = new ArrayList<>(capabilities); - list.sort(STATISTIC_DESCRIPTOR_COMPARATOR); - return list; + // To keep ordering because these objects end up in an immutable + // topology so this is easier for testing to compare with json payloads + return super.getDescriptors() + .stream() + .map(d -> (StatisticDescriptor) d) + .sorted(STATISTIC_DESCRIPTOR_COMPARATOR) + .collect(toList()); } @Override - public Map collectStatistics(Context context, Collection statisticNames) { - StandardEhcacheStatistics ehcacheStatistics = (StandardEhcacheStatistics) findExposedObject(context); - if (ehcacheStatistics != null) { - if (statisticNames == null || statisticNames.isEmpty()) { - return ehcacheStatistics.queryStatistics(); - } else { - Map statistics = new TreeMap<>(); - for (String statisticName : statisticNames) { - try { - statistics.put(statisticName, ehcacheStatistics.queryStatistic(statisticName)); - } catch (IllegalArgumentException ignored) { - // ignore when statisticName does not exist and throws an exception - } - } - return statistics; - } + public Map> collectStatistics(Context context, Collection statisticNames) { + StandardEhcacheStatistics exposedObject = (StandardEhcacheStatistics) findExposedObject(context); + if (exposedObject == null) { + return Collections.emptyMap(); } - return Collections.emptyMap(); + return DefaultStatisticsManagementProvider.collect(exposedObject.getStatisticRegistry(), statisticNames); + } } diff --git a/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java b/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java index 36f8d997e3..70c43c83bd 100644 --- a/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java +++ b/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java @@ -16,50 +16,38 @@ package org.ehcache.management.providers.statistics; import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.statistics.CacheStatistics; -import org.ehcache.core.statistics.TypedValueStatistic; import org.ehcache.management.ManagementRegistryServiceConfiguration; import org.ehcache.management.providers.CacheBinding; import org.ehcache.management.providers.ExposedCacheBinding; import org.terracotta.management.model.capabilities.descriptors.StatisticDescriptor; import org.terracotta.management.registry.collect.StatisticRegistry; +import org.terracotta.statistics.registry.Statistic; +import java.io.Serializable; import java.util.Collection; import java.util.Map; +import java.util.Optional; public class StandardEhcacheStatistics extends ExposedCacheBinding { private final StatisticRegistry statisticRegistry; - StandardEhcacheStatistics(ManagementRegistryServiceConfiguration registryConfiguration, CacheBinding cacheBinding, StatisticsService statisticsService) { + StandardEhcacheStatistics(ManagementRegistryServiceConfiguration registryConfiguration, CacheBinding cacheBinding, StatisticsService statisticsService, TimeSource timeSource) { super(registryConfiguration, cacheBinding); - this.statisticRegistry = new StatisticRegistry(cacheBinding.getCache()); + this.statisticRegistry = new StatisticRegistry(cacheBinding.getCache(), timeSource::getTimeMillis); String cacheName = cacheBinding.getAlias(); CacheStatistics cacheStatistics = statisticsService.getCacheStatistics(cacheName); - Map knownStatistics = cacheStatistics.getKnownStatistics(); - - for(Map.Entry stat : knownStatistics.entrySet()) { - String name = stat.getKey(); - TypedValueStatistic valueStatistic = stat.getValue(); - switch (valueStatistic.getType()) { - case COUNTER: - statisticRegistry.registerCounter(name, valueStatistic); - break; - case SIZE: - statisticRegistry.registerSize(name, valueStatistic); - break; - default: - throw new IllegalArgumentException("Unsupported statistic type: " + valueStatistic.getType()); - } - } + cacheStatistics.getKnownStatistics().forEach(statisticRegistry::registerStatistic); } - public Number queryStatistic(String fullStatisticName) { + public Optional> queryStatistic(String fullStatisticName) { return statisticRegistry.queryStatistic(fullStatisticName); } - public Map queryStatistics() { + public Map> queryStatistics() { return statisticRegistry.queryStatistics(); } @@ -68,4 +56,8 @@ public Collection getDescriptors() { return statisticRegistry.getDescriptors(); } + StatisticRegistry getStatisticRegistry() { + return statisticRegistry; + } + } diff --git a/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java b/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java index 2c468806d0..78db45dabb 100644 --- a/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java +++ b/management/src/main/java/org/ehcache/management/registry/DefaultManagementRegistryService.java @@ -22,6 +22,7 @@ import org.ehcache.core.spi.service.CacheManagerProviderService; import org.ehcache.core.spi.service.StatisticsService; import org.ehcache.core.spi.store.InternalCacheManager; +import org.ehcache.core.spi.time.TimeSourceService; import org.ehcache.management.ManagementRegistryService; import org.ehcache.management.ManagementRegistryServiceConfiguration; import org.ehcache.management.cluster.Clustering; @@ -43,7 +44,7 @@ import java.util.Collection; import java.util.Map; -@ServiceDependencies({CacheManagerProviderService.class, StatisticsService.class}) +@ServiceDependencies({CacheManagerProviderService.class, StatisticsService.class, TimeSourceService.class}) public class DefaultManagementRegistryService extends DefaultManagementRegistry implements ManagementRegistryService, CacheManagerListener { private final ManagementRegistryServiceConfiguration configuration; @@ -64,10 +65,11 @@ public void start(final ServiceProvider serviceProvider) { this.cacheManager = serviceProvider.getService(CacheManagerProviderService.class).getCacheManager(); StatisticsService statisticsService = serviceProvider.getService(StatisticsService.class); + TimeSourceService timeSourceService = serviceProvider.getService(TimeSourceService.class); // initialize management capabilities (stats, action calls, etc) addManagementProvider(new EhcacheActionProvider(getConfiguration())); - addManagementProvider(new EhcacheStatisticsProvider(getConfiguration(), statisticsService)); + addManagementProvider(new EhcacheStatisticsProvider(getConfiguration(), statisticsService, timeSourceService.getTimeSource())); addManagementProvider(new EhcacheStatisticCollectorProvider(getConfiguration())); addManagementProvider(new EhcacheSettingsProvider(getConfiguration(), cacheManager)); diff --git a/management/src/test/java/org/ehcache/docs/ManagementTest.java b/management/src/test/java/org/ehcache/docs/ManagementTest.java index 60840f9bac..2a35b1be8e 100644 --- a/management/src/test/java/org/ehcache/docs/ManagementTest.java +++ b/management/src/test/java/org/ehcache/docs/ManagementTest.java @@ -231,7 +231,7 @@ public void managingMultipleCacheManagers() throws Exception { ContextualStatistics statisticsContext1 = counters.getResult(context1); - Number counterContext1 = statisticsContext1.getStatistic("Cache:MissCount"); + Long counterContext1 = statisticsContext1.getLatestSample("Cache:MissCount").get(); // miss count is a sampled stat, for example its values could be [0,1,2]. // In the present case, only the last value is important to us , the cache was eventually missed 2 times diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProviderTest.java b/management/src/test/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProviderTest.java index 239c97cc95..deaceb6e43 100644 --- a/management/src/test/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProviderTest.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/EhcacheStatisticsProviderTest.java @@ -17,6 +17,8 @@ import org.ehcache.core.EhcacheWithLoaderWriter; import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.time.SystemTimeSource; +import org.ehcache.core.spi.time.TimeSource; import org.ehcache.impl.internal.statistics.DefaultStatisticsService; import org.ehcache.management.ManagementRegistryServiceConfiguration; import org.ehcache.management.providers.CacheBinding; @@ -51,6 +53,7 @@ public class EhcacheStatisticsProviderTest { Context cmContext_0 = Context.create("cacheManagerName", "cache-manager-0"); ManagementRegistryServiceConfiguration cmConfig_0 = new DefaultManagementRegistryConfiguration() .setContext(cmContext_0); + TimeSource timeSource = SystemTimeSource.INSTANCE; @After public void tearDown() throws Exception { @@ -60,7 +63,7 @@ public void tearDown() throws Exception { @Test @SuppressWarnings("unchecked") public void testDescriptions() throws Exception { - EhcacheStatisticsProvider ehcacheStatisticsProvider = new EhcacheStatisticsProvider(cmConfig_0, statisticsService) { + EhcacheStatisticsProvider ehcacheStatisticsProvider = new EhcacheStatisticsProvider(cmConfig_0, statisticsService, timeSource) { @Override protected ExposedCacheBinding wrap(CacheBinding cacheBinding) { StandardEhcacheStatistics mock = mock(StandardEhcacheStatistics.class); @@ -86,7 +89,7 @@ protected ExposedCacheBinding wrap(CacheBinding cacheBinding) { @Test public void testCapabilityContext() throws Exception { - EhcacheStatisticsProvider ehcacheStatisticsProvider = new EhcacheStatisticsProvider(cmConfig_0, statisticsService) { + EhcacheStatisticsProvider ehcacheStatisticsProvider = new EhcacheStatisticsProvider(cmConfig_0, statisticsService, timeSource) { @Override protected ExposedCacheBinding wrap(CacheBinding cacheBinding) { return mock(StandardEhcacheStatistics.class); @@ -111,7 +114,7 @@ protected ExposedCacheBinding wrap(CacheBinding cacheBinding) { @Test public void testCallAction() throws Exception { - EhcacheStatisticsProvider ehcacheStatisticsProvider = new EhcacheStatisticsProvider(cmConfig_0, statisticsService); + EhcacheStatisticsProvider ehcacheStatisticsProvider = new EhcacheStatisticsProvider(cmConfig_0, statisticsService, timeSource); try { ehcacheStatisticsProvider.callAction(null, null); diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java index 3b626f822e..c15041b618 100755 --- a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java @@ -24,7 +24,6 @@ import org.ehcache.CacheManager; import org.ehcache.config.Builder; import org.ehcache.config.CacheConfiguration; -import org.ehcache.config.EvictionAdvisor; import org.ehcache.config.ResourcePools; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; @@ -163,7 +162,7 @@ public static long getAndAssertExpectedValueFromCounter(String statName, Context assertThat(counters.size(), Matchers.is(1)); - Long counter = (Long) statisticsContext.getStatistic(statName); + Long counter = statisticsContext.getLatestSample(statName).get(); assertThat(counter, Matchers.is(expectedResult)); diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java index 2f1ffc8fd1..859c2b00b3 100755 --- a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java @@ -73,7 +73,7 @@ public void statsClearCacheTest() throws InterruptedException { .getSingleResult(); assertThat(counter.size(), Matchers.is(1)); - Number count = counter.getStatistic("Cache:HitCount"); + Long count = counter. getLatestSample("Cache:HitCount").get(); assertThat(count.longValue(), Matchers.equalTo(1L)); } diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java b/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java index 23700d5641..607943581a 100755 --- a/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java @@ -54,7 +54,7 @@ public static long getAndAssertExpectedValueFromCounter(String statName, Context assertThat(counters.size(), Matchers.is(1)); - Number counter = statisticsContext.getStatistic(statName); + Number counter = statisticsContext.getLatestSample(statName).get(); long value = counter.longValue(); assertThat(value, Matchers.is(expectedResult)); diff --git a/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java b/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java index 065b2f75aa..8c8cde9b8c 100644 --- a/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java +++ b/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java @@ -17,7 +17,6 @@ import java.io.File; import java.io.IOException; -import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import java.util.NoSuchElementException; @@ -160,6 +159,7 @@ public void descriptorOffHeapTest() { allDescriptors.addAll(ONHEAP_DESCRIPTORS); allDescriptors.addAll(OFFHEAP_DESCRIPTORS); allDescriptors.addAll(CACHE_DESCRIPTORS); + allDescriptors.add(new StatisticDescriptor("OnHeap:OccupiedByteSize" , "GAUGE")); assertThat(descriptors).containsOnlyElementsOf(allDescriptors); } @@ -277,7 +277,7 @@ public void testCanGetStats() { .on(context1); ContextualStatistics counters = getResultSet(builder1, context1, null, queryStatisticName).getResult(context1); - Number counterHistory1 = counters.getStatistic(queryStatisticName); + Number counterHistory1 = counters.getLatestSample(queryStatisticName).get(); assertThat(counters.size()).isEqualTo(1); assertThat(counterHistory1.longValue()).isEqualTo(1L); @@ -292,8 +292,8 @@ public void testCanGetStats() { assertThat(allCounters.getResult(context1).size()).isEqualTo(1); assertThat(allCounters.getResult(context2).size()).isEqualTo(1); - assertThat(allCounters.getResult(context1).getStatistic(queryStatisticName).longValue()).isEqualTo(1L); - assertThat(allCounters.getResult(context2).getStatistic(queryStatisticName).longValue()).isEqualTo(1L); + assertThat(allCounters.getResult(context1).getLatestSample(queryStatisticName).get()).isEqualTo(1L); + assertThat(allCounters.getResult(context2).getLatestSample(queryStatisticName).get()).isEqualTo(1L); cacheManager1.close(); } @@ -306,12 +306,12 @@ private static ResultSet getResultSet(Builder builder, Con counters = builder.build().execute(); ContextualStatistics statisticsContext1 = counters.getResult(context1); - Number counterContext1 = statisticsContext1.getStatistic(statisticsName); + Number counterContext1 = statisticsContext1.getLatestSample(statisticsName).get(); if(context2 != null) { ContextualStatistics statisticsContext2 = counters.getResult(context2); - Number counterHistoryContext2 = statisticsContext2.getStatistic(statisticsName); + Number counterHistoryContext2 = statisticsContext2.getLatestSample(statisticsName).get(); if(counterHistoryContext2.longValue() > 0 && counterContext1.longValue() > 0) @@ -415,25 +415,22 @@ public static void loadStatsUtil() throws ClassNotFoundException { ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:ExpirationCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:MissCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:MappingCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:OccupiedByteSize" , "SIZE")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:HitCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:PutCount" , "COUNTER")); ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:RemovalCount" , "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MissCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:OccupiedByteSize", "SIZE")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:AllocatedByteSize", "SIZE")); + OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:OccupiedByteSize", "GAUGE")); + OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:AllocatedByteSize", "GAUGE")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MappingCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:EvictionCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:ExpirationCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MaxMappingCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:HitCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:PutCount", "COUNTER")); OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:RemovalCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:MaxMappingCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:OccupiedByteSize", "SIZE")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:AllocatedByteSize", "SIZE")); + DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:OccupiedByteSize", "GAUGE")); + DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:AllocatedByteSize", "GAUGE")); DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:HitCount", "COUNTER")); DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:EvictionCount", "COUNTER")); DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:ExpirationCount", "COUNTER")); diff --git a/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java b/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java index ce8f83e953..0b3287474d 100644 --- a/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java +++ b/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java @@ -184,9 +184,9 @@ public void testStats() { assertThat(allCounters.getResult(contextList.get(2)).size(), equalTo(1)); - assertThat(allCounters.getResult(contextList.get(0)).getStatistic(statisticName).longValue(), equalTo(1L)); - assertThat(allCounters.getResult(contextList.get(1)).getStatistic(statisticName).longValue(), equalTo(1L)); - assertThat(allCounters.getResult(contextList.get(2)).getStatistic(statisticName).longValue(), equalTo(1L)); + assertThat(allCounters.getResult(contextList.get(0)).getLatestSample(statisticName).get(), equalTo(1L)); + assertThat(allCounters.getResult(contextList.get(1)).getLatestSample(statisticName).get(), equalTo(1L)); + assertThat(allCounters.getResult(contextList.get(2)).getLatestSample(statisticName).get(), equalTo(1L)); } @@ -197,9 +197,9 @@ private static ResultSet getResultSet(StatisticQuery.Build while(!Thread.currentThread().isInterrupted()) { counters = builder.build().execute(); - if(counters.getResult(contextList.get(0)).getStatistic(statisticsName).longValue()> 0 && - counters.getResult(contextList.get(1)).getStatistic(statisticsName).longValue() > 0 && - counters.getResult(contextList.get(2)).getStatistic(statisticsName).longValue() > 0) { + if(counters.getResult(contextList.get(0)).getLatestSample(statisticsName).get()> 0 && + counters.getResult(contextList.get(1)).getLatestSample(statisticsName).get() > 0 && + counters.getResult(contextList.get(2)).getLatestSample(statisticsName).get() > 0) { break; } } From 5ead10e917fbdfe6bc58ac20fc99dd3e21846eae Mon Sep 17 00:00:00 2001 From: Saurabh Agarwal Date: Mon, 8 Jan 2018 16:19:54 +0530 Subject: [PATCH 089/779] Introduced a constant to define the default value for autoCreate --- .../client/config/ClusteringServiceConfiguration.java | 3 ++- .../builders/ClusteringServiceConfigurationBuilder.java | 4 +++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java index 94c98851eb..9c920d086c 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/ClusteringServiceConfiguration.java @@ -40,6 +40,7 @@ public class ClusteringServiceConfiguration CacheManagerConfiguration, HumanReadable { + public static final boolean DEFAULT_AUTOCREATE = false; private final URI clusterUri; private final boolean autoCreate; private final ServerSideConfiguration serverConfiguration; @@ -95,7 +96,7 @@ public ClusteringServiceConfiguration(URI clusterUri, ServerSideConfiguration se * @throws IllegalArgumentException if {@code clusterUri} is not URI valid for cluster operations */ public ClusteringServiceConfiguration(URI clusterUri, Timeouts timeouts, ServerSideConfiguration serverConfig) { - this(clusterUri, timeouts, false, serverConfig); + this(clusterUri, timeouts, DEFAULT_AUTOCREATE, serverConfig); } /** diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java index 0374f5943b..1d5e3f8790 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/builders/ClusteringServiceConfigurationBuilder.java @@ -27,6 +27,8 @@ import org.ehcache.clustered.common.ServerSideConfiguration; import org.ehcache.config.Builder; +import static org.ehcache.clustered.client.config.ClusteringServiceConfiguration.DEFAULT_AUTOCREATE; + /** * A builder of ClusteringService configurations. */ @@ -44,7 +46,7 @@ public final class ClusteringServiceConfigurationBuilder implements Builder Date: Tue, 9 Jan 2018 11:43:29 -0500 Subject: [PATCH 090/779] Make sure we do not received unexpected notifications --- .../management/AbstractClusteringManagementTest.java | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java index 1366c4e75c..5aa96b71ac 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java @@ -269,6 +269,8 @@ private static void sendManagementCallOnEntityToCollectStats() throws Exception protected static void waitForAllNotifications(String... notificationTypes) throws InterruptedException, TimeoutException { List waitingFor = new ArrayList<>(Arrays.asList(notificationTypes)); + List missingOnes = new ArrayList<>(); + // please keep these sout because it is really hard to troubleshoot blocking tests in the beforeClass method in the case we do not receive all notifs. // System.out.println("waitForAllNotifications: " + waitingFor); @@ -280,6 +282,8 @@ protected static void waitForAllNotifications(String... notificationTypes) throw if (waitingFor.remove(notification.getType())) { // System.out.println("Remove " + notification.getType()); // System.out.println("Still waiting for: " + waitingFor); + } else { + missingOnes.add(notification); } } } @@ -294,5 +298,6 @@ protected static void waitForAllNotifications(String... notificationTypes) throw t.interrupt(); // we interrupt the thread that is waiting on the message queue assertTrue("Still waiting for: " + waitingFor, waitingFor.isEmpty()); + assertTrue("Unexpected notification: " + missingOnes, missingOnes.isEmpty()); } } From 4f517b8e9cecc7455f2d513594220098a4908986 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 2 Jan 2018 16:31:49 -0500 Subject: [PATCH 091/779] Add default methods to CacheLoaderWriter --- .../jsr107/Eh107CacheLoaderWriter.java | 18 ++++---- .../integration/ProductCacheLoaderWriter.java | 12 ++--- .../spi/loaderwriter/CacheLoaderWriter.java | 21 +++++++-- ...tedCombinationsWIthClusteredCacheTest.java | 12 ++--- .../EhcacheManagerToStringTest.java | 12 ++--- .../core/EhcacheWithLoaderWriterTest.java | 12 ++--- .../writebehind/AbstractWriteBehind.java | 46 ------------------- .../writebehind/StripedWriteBehind.java | 27 ----------- .../CacheConfigurationBuilderTest.java | 12 ++--- .../docs/plugs/SampleLoaderWriter.java | 12 ++--- .../WriteBehindProviderFactoryTest.java | 12 ++--- .../WriteBehindTestLoaderWriter.java | 12 ++--- .../DefaultCacheLoaderWriterProviderTest.java | 16 +++---- .../store/disk/OffHeapDiskStoreTest.java | 12 ++--- .../transactions/xa/SampleLoaderWriter.java | 12 ++--- .../transactions/xa/XAGettingStarted.java | 12 ++--- .../integration/TestCacheLoaderWriter.java | 12 ++--- .../ThreadRememberingLoaderWriter.java | 13 +++--- 18 files changed, 113 insertions(+), 172 deletions(-) diff --git a/107/src/main/java/org/ehcache/jsr107/Eh107CacheLoaderWriter.java b/107/src/main/java/org/ehcache/jsr107/Eh107CacheLoaderWriter.java index 815b9315a3..5e9df94dab 100644 --- a/107/src/main/java/org/ehcache/jsr107/Eh107CacheLoaderWriter.java +++ b/107/src/main/java/org/ehcache/jsr107/Eh107CacheLoaderWriter.java @@ -19,7 +19,6 @@ import java.io.IOException; import java.util.ArrayList; import java.util.Collection; -import static java.util.Collections.emptyMap; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -30,9 +29,10 @@ import javax.cache.integration.CacheWriter; import org.ehcache.jsr107.internal.Jsr107CacheLoaderWriter; -import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; +import static java.util.Collections.emptyMap; + /** * @author teck */ @@ -53,7 +53,7 @@ class Eh107CacheLoaderWriter implements Jsr107CacheLoaderWriter, Clo } @Override - public V load(K key) throws Exception { + public V load(K key) { if (readThrough) { return cacheLoader.load(key); } else { @@ -62,7 +62,7 @@ public V load(K key) throws Exception { } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { if (readThrough) { return loadAllAlways(keys); } else { @@ -71,7 +71,7 @@ public Map loadAll(Iterable keys) throws Exception { } @Override - public Map loadAllAlways(Iterable keys) throws BulkCacheLoadingException, Exception { + public Map loadAllAlways(Iterable keys) { if (cacheLoader == null) { return emptyMap(); } else { @@ -80,21 +80,21 @@ public Map loadAllAlways(Iterable keys) throws BulkCacheLoadi } @Override - public void write(K key, V value) throws Exception { + public void write(K key, V value) { if (cacheWriter != null) { cacheWriter.write(cacheEntryFor(key, value)); } } @Override - public void delete(K key) throws Exception { + public void delete(K key) { if (cacheWriter != null) { cacheWriter.delete(key); } } @Override - public void deleteAll(Iterable keys) throws Exception { + public void deleteAll(Iterable keys) throws BulkCacheWritingException { if (cacheWriter != null) { Set allKeys = new HashSet<>(); for (K key : keys) { @@ -131,7 +131,7 @@ private Map failures(Set keys, Exception e) { } @Override - public void writeAll(Iterable> entries) throws Exception { + public void writeAll(Iterable> entries) { if (cacheWriter != null) { Collection> toWrite = new ArrayList<>(); for (Map.Entry entry : entries) { diff --git a/107/src/test/java/com/pany/ehcache/integration/ProductCacheLoaderWriter.java b/107/src/test/java/com/pany/ehcache/integration/ProductCacheLoaderWriter.java index 30770b375e..efd2315a88 100644 --- a/107/src/test/java/com/pany/ehcache/integration/ProductCacheLoaderWriter.java +++ b/107/src/test/java/com/pany/ehcache/integration/ProductCacheLoaderWriter.java @@ -38,13 +38,13 @@ public class ProductCacheLoaderWriter implements CacheLoaderWriter seen = new HashSet<>(); @Override - public Product load(final Long key) throws Exception { + public Product load(final Long key) { seen.add(key); return new Product(key); } @Override - public Map loadAll(final Iterable keys) throws Exception { + public Map loadAll(final Iterable keys) { for (Long key : keys) { seen.add(key); } @@ -52,7 +52,7 @@ public Map loadAll(final Iterable keys) throws Ex } @Override - public void write(final Long key, final Product value) throws Exception { + public void write(final Long key, final Product value) { List products = written.get(key); if(products == null) { products = new ArrayList<>(); @@ -65,17 +65,17 @@ public void write(final Long key, final Product value) throws Exception { } @Override - public void writeAll(final Iterable> entries) throws Exception { + public void writeAll(final Iterable> entries) { // no-op } @Override - public void delete(final Long key) throws Exception { + public void delete(final Long key) { // no-op } @Override - public void deleteAll(final Iterable keys) throws Exception { + public void deleteAll(final Iterable keys) { // no-op } } diff --git a/api/src/main/java/org/ehcache/spi/loaderwriter/CacheLoaderWriter.java b/api/src/main/java/org/ehcache/spi/loaderwriter/CacheLoaderWriter.java index 599facaa75..d7c40c29e2 100644 --- a/api/src/main/java/org/ehcache/spi/loaderwriter/CacheLoaderWriter.java +++ b/api/src/main/java/org/ehcache/spi/loaderwriter/CacheLoaderWriter.java @@ -16,6 +16,7 @@ package org.ehcache.spi.loaderwriter; +import java.util.HashMap; import java.util.Map; /** @@ -75,7 +76,13 @@ public interface CacheLoaderWriter { * @throws BulkCacheLoadingException in case of partial success * @throws Exception in case no values could be loaded */ - Map loadAll(Iterable keys) throws BulkCacheLoadingException, Exception; + default Map loadAll(Iterable keys) throws BulkCacheLoadingException, Exception { + Map entries = new HashMap<>(); + for (K k : keys) { + entries.put(k, load(k)) ; + } + return entries; + } /** * Writes a single mapping. @@ -105,7 +112,11 @@ public interface CacheLoaderWriter { * @throws BulkCacheWritingException in case of partial success * @throws Exception in case no values could be written */ - void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception; + default void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + for (Map.Entry entry : entries) { + write(entry.getKey(), entry.getValue()); + } + } /** * Deletes a single mapping. @@ -127,6 +138,10 @@ public interface CacheLoaderWriter { * @throws BulkCacheWritingException in case of partial success * @throws Exception in case no values can be loaded */ - void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception; + default void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + for (K k : keys) { + delete(k); + } + } } diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/UnSupportedCombinationsWIthClusteredCacheTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/UnSupportedCombinationsWIthClusteredCacheTest.java index 0a0dc345e5..1c64ea6663 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/UnSupportedCombinationsWIthClusteredCacheTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/UnSupportedCombinationsWIthClusteredCacheTest.java @@ -151,32 +151,32 @@ public void testClusteredCacheWithXA() throws Exception { private static class TestLoaderWriter implements CacheLoaderWriter { @Override - public String load(Long key) throws Exception { + public String load(Long key) { return null; } @Override - public Map loadAll(Iterable keys) throws BulkCacheLoadingException, Exception { + public Map loadAll(Iterable keys) { return null; } @Override - public void write(Long key, String value) throws Exception { + public void write(Long key, String value) { } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { } @Override - public void delete(Long key) throws Exception { + public void delete(Long key) { } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { } } diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/EhcacheManagerToStringTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/EhcacheManagerToStringTest.java index 270ca16f23..6d348a8094 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/EhcacheManagerToStringTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/EhcacheManagerToStringTest.java @@ -133,32 +133,32 @@ public void clusteredToString() throws Exception { public static class SampleLoaderWriter implements CacheLoaderWriter { @Override - public V load(K key) throws Exception { + public V load(K key) { throw new UnsupportedOperationException("Implement Me"); } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void write(K key, V value) throws Exception { + public void write(K key, V value) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void writeAll(Iterable> entries) throws Exception { + public void writeAll(Iterable> entries) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void delete(K key) throws Exception { + public void delete(K key) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void deleteAll(Iterable keys) throws Exception { + public void deleteAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } } diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java index cb4273c67d..6902c2dd56 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java @@ -194,7 +194,7 @@ public Map> bulkCompute(Set keys, private static class KeyFumblingCacheLoaderWriter implements CacheLoaderWriter { @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { HashMap result = new HashMap<>(); for (String key : keys) { result.put(new String(key), "valueFor" + key); @@ -203,27 +203,27 @@ public Map loadAll(Iterable keys) throws Excep } @Override - public void write(String key, String value) throws Exception { + public void write(String key, String value) { throw new UnsupportedOperationException("TODO Implement me!"); } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { throw new UnsupportedOperationException("TODO Implement me!"); } @Override - public void delete(String key) throws Exception { + public void delete(String key) { throw new UnsupportedOperationException("TODO Implement me!"); } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { throw new UnsupportedOperationException("TODO Implement me!"); } @Override - public String load(String key) throws Exception { + public String load(String key) { throw new UnsupportedOperationException("TODO Implement me!"); } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/AbstractWriteBehind.java b/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/AbstractWriteBehind.java index c936a49600..38650185b7 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/AbstractWriteBehind.java +++ b/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/AbstractWriteBehind.java @@ -15,11 +15,6 @@ */ package org.ehcache.impl.internal.loaderwriter.writebehind; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.BlockingQueue; -import org.ehcache.spi.loaderwriter.BulkCacheWritingException; - import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.impl.internal.loaderwriter.writebehind.operations.DeleteOperation; import org.ehcache.impl.internal.loaderwriter.writebehind.operations.SingleOperation; @@ -40,58 +35,17 @@ public V load(K key) throws Exception { return operation == null ? cacheLoaderWriter.load(key) : (operation.getClass() == WriteOperation.class ? ((WriteOperation) operation).getValue() : null); } - @Override - public Map loadAll(Iterable keys) throws Exception { - Map entries = new HashMap<>(); - for (K k : keys) { - entries.put(k, load(k)) ; - } - return entries; - } - @Override public void write(K key, V value) throws CacheWritingException { addOperation(new WriteOperation<>(key, value)); } - @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { - for (Map.Entry entry : entries) { - write(entry.getKey(), entry.getValue()); - } - } - @Override public void delete(K key) throws CacheWritingException { addOperation(new DeleteOperation<>(key)); } - @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { - for (K k : keys) { - delete(k); - } - } - protected abstract SingleOperation getOperation(K key); protected abstract void addOperation(final SingleOperation operation); - - protected static void putUninterruptibly(BlockingQueue queue, T r) { - boolean interrupted = false; - try { - while (true) { - try { - queue.put(r); - return; - } catch (InterruptedException e) { - interrupted = true; - } - } - } finally { - if (interrupted) { - Thread.currentThread().interrupt(); - } - } - } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java b/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java index 434f45900f..5f599c172e 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java +++ b/impl/src/main/java/org/ehcache/impl/internal/loaderwriter/writebehind/StripedWriteBehind.java @@ -16,12 +16,8 @@ package org.ehcache.impl.internal.loaderwriter.writebehind; import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.concurrent.locks.ReentrantReadWriteLock; -import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.spi.loaderwriter.WriteBehindConfiguration; @@ -78,15 +74,6 @@ public V load(K key) throws Exception { return v; } - @Override - public Map loadAll(Iterable keys) throws Exception { - Map entries = new HashMap<>(); - for (K k : keys) { - entries.put(k, load(k)) ; - } - return entries; - } - @Override public void write(K key, V value) throws Exception { readLock.lock(); @@ -97,13 +84,6 @@ public void write(K key, V value) throws Exception { } } - @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { - for (Entry entry : entries) { - write(entry.getKey(), entry.getValue()); - } - } - @Override public void delete(K key) throws Exception { readLock.lock(); @@ -114,13 +94,6 @@ public void delete(K key) throws Exception { } } - @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { - for (K k : keys) { - delete(k); - } - } - @Override public void stop() { writeLock.lock(); diff --git a/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java b/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java index 8b32862a58..8b2863fc94 100644 --- a/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java +++ b/impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java @@ -66,32 +66,32 @@ public void testEvictionAdvisor() throws Exception { public void testLoaderWriter() throws Exception { CacheLoaderWriter loaderWriter = new CacheLoaderWriter() { @Override - public Object load(Object key) throws Exception { + public Object load(Object key) { return null; } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { return null; } @Override - public void write(Object key, Object value) throws Exception { + public void write(Object key, Object value) { } @Override - public void writeAll(Iterable iterable) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable iterable) { } @Override - public void delete(Object key) throws Exception { + public void delete(Object key) { } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { } }; diff --git a/impl/src/test/java/org/ehcache/docs/plugs/SampleLoaderWriter.java b/impl/src/test/java/org/ehcache/docs/plugs/SampleLoaderWriter.java index e99d9e3a4c..bf69f64002 100644 --- a/impl/src/test/java/org/ehcache/docs/plugs/SampleLoaderWriter.java +++ b/impl/src/test/java/org/ehcache/docs/plugs/SampleLoaderWriter.java @@ -44,7 +44,7 @@ public SampleLoaderWriter(Map initialData) { } @Override - public V load(K key) throws Exception { + public V load(K key) { lock.readLock().lock(); try { V value = data.get(key); @@ -56,12 +56,12 @@ public V load(K key) throws Exception { } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void write(K key, V value) throws Exception { + public void write(K key, V value) { lock.writeLock().lock(); try { data.put(key, value); @@ -72,7 +72,7 @@ public void write(K key, V value) throws Exception { } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { lock.writeLock().lock(); try { for (Map.Entry entry : entries) { @@ -85,7 +85,7 @@ public void writeAll(Iterable> ent } @Override - public void delete(K key) throws Exception { + public void delete(K key) { lock.writeLock().lock(); try { data.remove(key); @@ -96,7 +96,7 @@ public void delete(K key) throws Exception { } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { lock.writeLock().lock(); try { for (K key : keys) { diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindProviderFactoryTest.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindProviderFactoryTest.java index 91c6d3a5f5..c5db714bbb 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindProviderFactoryTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindProviderFactoryTest.java @@ -79,32 +79,32 @@ public void testWriteBehindWithoutCacheLoaderWriter() { public static class SampleLoaderWriter implements CacheLoaderWriter { @Override - public V load(K key) throws Exception { + public V load(K key) { throw new UnsupportedOperationException("Implement Me"); } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void write(K key, V value) throws Exception { + public void write(K key, V value) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void writeAll(Iterable> entries) throws Exception { + public void writeAll(Iterable> entries) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void delete(K key) throws Exception { + public void delete(K key) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void deleteAll(Iterable keys) throws Exception { + public void deleteAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } } diff --git a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTestLoaderWriter.java b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTestLoaderWriter.java index a613def24c..0c26fc2f40 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTestLoaderWriter.java +++ b/impl/src/test/java/org/ehcache/impl/internal/loaderwriter/writebehind/WriteBehindTestLoaderWriter.java @@ -39,7 +39,7 @@ public synchronized void setLatch(CountDownLatch latch) { } @Override - public synchronized V load(K key) throws Exception { + public synchronized V load(K key) { List values = getValueList(key); if (values.isEmpty()) { return null; @@ -49,7 +49,7 @@ public synchronized V load(K key) throws Exception { } @Override - public synchronized Map loadAll(Iterable keys) throws Exception { + public synchronized Map loadAll(Iterable keys) { Map loaded = new HashMap<>(); for (K k : keys) { loaded.put(k, load(k)); @@ -58,26 +58,26 @@ public synchronized Map loadAll(Iterable keys) throws Excepti } @Override - public synchronized void write(K key, V value) throws Exception { + public synchronized void write(K key, V value) { getValueList(key).add(value); if(latch != null) latch.countDown(); } @Override - public synchronized void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public synchronized void writeAll(Iterable> entries) { for (Entry entry : entries) { write(entry.getKey(), entry.getValue()); } } @Override - public synchronized void delete(K key) throws Exception { + public synchronized void delete(K key) { getValueList(key).add(null); if(latch != null) latch.countDown(); } @Override - public synchronized void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public synchronized void deleteAll(Iterable keys) { for (K k : keys) { delete(k); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/spi/loaderwriter/DefaultCacheLoaderWriterProviderTest.java b/impl/src/test/java/org/ehcache/impl/internal/spi/loaderwriter/DefaultCacheLoaderWriterProviderTest.java index da346e210f..c788884bf7 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/spi/loaderwriter/DefaultCacheLoaderWriterProviderTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/spi/loaderwriter/DefaultCacheLoaderWriterProviderTest.java @@ -132,34 +132,34 @@ public String toString() { }; @Override - public Object load(final Object key) throws Exception { + public Object load(final Object key) { return object; } @Override - public Map loadAll(final Iterable keys) throws Exception { + public Map loadAll(final Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } private static Object lastWritten; @Override - public void write(final Object key, final Object value) throws Exception { + public void write(final Object key, final Object value) { lastWritten = value; } @Override - public void writeAll(final Iterable> entries) throws Exception { + public void writeAll(final Iterable> entries) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void delete(final Object key) throws Exception { + public void delete(final Object key) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void deleteAll(final Iterable keys) throws Exception { + public void deleteAll(final Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } } @@ -176,12 +176,12 @@ public String toString() { private static Object lastWritten; @Override - public Object load(final Object key) throws Exception { + public Object load(final Object key) { return object; } @Override - public void write(final Object key, final Object value) throws Exception { + public void write(final Object key, final Object value) { lastWritten = value; } diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java index f25432f728..953c2485fc 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java @@ -360,29 +360,29 @@ public void diskStoreShrinkingTest() throws Exception { heap(1000).offheap(20, MB).disk(30, MB)) .withLoaderWriter(new CacheLoaderWriter() { @Override - public CacheValue load(Long key) throws Exception { + public CacheValue load(Long key) { return null; } @Override - public Map loadAll(Iterable keys) throws BulkCacheLoadingException, Exception { + public Map loadAll(Iterable keys) { return Collections.emptyMap(); } @Override - public void write(Long key, CacheValue value) throws Exception { + public void write(Long key, CacheValue value) { } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { } @Override - public void delete(Long key) throws Exception { + public void delete(Long key) { } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { } })); diff --git a/integration-test/src/test/java/org/ehcache/integration/transactions/xa/SampleLoaderWriter.java b/integration-test/src/test/java/org/ehcache/integration/transactions/xa/SampleLoaderWriter.java index 9c01913d09..d5aaf5e370 100644 --- a/integration-test/src/test/java/org/ehcache/integration/transactions/xa/SampleLoaderWriter.java +++ b/integration-test/src/test/java/org/ehcache/integration/transactions/xa/SampleLoaderWriter.java @@ -48,7 +48,7 @@ public void clear() { } @Override - public V load(K key) throws Exception { + public V load(K key) { lock.readLock().lock(); try { V value = data.get(key); @@ -60,12 +60,12 @@ public V load(K key) throws Exception { } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void write(K key, V value) throws Exception { + public void write(K key, V value) { lock.writeLock().lock(); try { data.put(key, value); @@ -76,7 +76,7 @@ public void write(K key, V value) throws Exception { } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { lock.writeLock().lock(); try { for (Map.Entry entry : entries) { @@ -89,7 +89,7 @@ public void writeAll(Iterable> ent } @Override - public void delete(K key) throws Exception { + public void delete(K key) { lock.writeLock().lock(); try { data.remove(key); @@ -100,7 +100,7 @@ public void delete(K key) throws Exception { } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { lock.writeLock().lock(); try { for (K key : keys) { diff --git a/transactions/src/test/java/org/ehcache/docs/transactions/xa/XAGettingStarted.java b/transactions/src/test/java/org/ehcache/docs/transactions/xa/XAGettingStarted.java index 6293b0a4b6..c0fd23febb 100644 --- a/transactions/src/test/java/org/ehcache/docs/transactions/xa/XAGettingStarted.java +++ b/transactions/src/test/java/org/ehcache/docs/transactions/xa/XAGettingStarted.java @@ -231,7 +231,7 @@ public SampleLoaderWriter(Map initialData) { } @Override - public V load(K key) throws Exception { + public V load(K key) { lock.readLock().lock(); try { V v = data.get(key); @@ -243,12 +243,12 @@ public V load(K key) throws Exception { } @Override - public Map loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } @Override - public void write(K key, V value) throws Exception { + public void write(K key, V value) { lock.writeLock().lock(); try { data.put(key, value); @@ -259,7 +259,7 @@ public void write(K key, V value) throws Exception { } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { lock.writeLock().lock(); try { for (Map.Entry entry : entries) { @@ -272,7 +272,7 @@ public void writeAll(Iterable> ent } @Override - public void delete(K key) throws Exception { + public void delete(K key) { lock.writeLock().lock(); try { data.remove(key); @@ -283,7 +283,7 @@ public void delete(K key) throws Exception { } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { lock.writeLock().lock(); try { for (K key : keys) { diff --git a/xml/src/test/java/com/pany/ehcache/integration/TestCacheLoaderWriter.java b/xml/src/test/java/com/pany/ehcache/integration/TestCacheLoaderWriter.java index 060c4a8fd4..07a28440eb 100644 --- a/xml/src/test/java/com/pany/ehcache/integration/TestCacheLoaderWriter.java +++ b/xml/src/test/java/com/pany/ehcache/integration/TestCacheLoaderWriter.java @@ -33,12 +33,12 @@ public class TestCacheLoaderWriter implements CacheLoaderWriter public static CountDownLatch latch; @Override - public String load(final Number key) throws Exception { + public String load(final Number key) { return key.toString(); } @Override - public Map loadAll(final Iterable keys) throws Exception { + public Map loadAll(final Iterable keys) { final Map loaded = new HashMap<>(); for (Number key : keys) { loaded.put(key, load(key)); @@ -47,7 +47,7 @@ public Map loadAll(final Iterable keys) throws } @Override - public void write(final Number key, final String value) throws Exception { + public void write(final Number key, final String value) { lastWrittenKey = key; if(latch != null) { latch.countDown(); @@ -55,7 +55,7 @@ public void write(final Number key, final String value) throws Exception { } @Override - public void writeAll(final Iterable> entries) throws Exception { + public void writeAll(final Iterable> entries) { for (Entry entry : entries) { lastWrittenKey = entry.getKey(); if(latch != null) { @@ -65,12 +65,12 @@ public void writeAll(final Iterable keys) throws Exception { + public void deleteAll(final Iterable keys) { throw new UnsupportedOperationException("Implement me!"); } } diff --git a/xml/src/test/java/com/pany/ehcache/integration/ThreadRememberingLoaderWriter.java b/xml/src/test/java/com/pany/ehcache/integration/ThreadRememberingLoaderWriter.java index 727b03fd30..4c5dd124a7 100644 --- a/xml/src/test/java/com/pany/ehcache/integration/ThreadRememberingLoaderWriter.java +++ b/xml/src/test/java/com/pany/ehcache/integration/ThreadRememberingLoaderWriter.java @@ -18,7 +18,6 @@ import java.util.Collections; import java.util.Map; import java.util.concurrent.Semaphore; -import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; public class ThreadRememberingLoaderWriter implements CacheLoaderWriter { @@ -26,35 +25,35 @@ public class ThreadRememberingLoaderWriter implements CacheLoaderWriter loadAll(Iterable keys) throws Exception { + public Map loadAll(Iterable keys) { return Collections.emptyMap(); } @Override - public void write(String key, String value) throws Exception { + public void write(String key, String value) { LAST_SEEN_THREAD = Thread.currentThread(); USED.release(); } @Override - public void writeAll(Iterable> entries) throws BulkCacheWritingException, Exception { + public void writeAll(Iterable> entries) { LAST_SEEN_THREAD = Thread.currentThread(); USED.release(); } @Override - public void delete(String key) throws Exception { + public void delete(String key) { LAST_SEEN_THREAD = Thread.currentThread(); USED.release(); } @Override - public void deleteAll(Iterable keys) throws BulkCacheWritingException, Exception { + public void deleteAll(Iterable keys) { LAST_SEEN_THREAD = Thread.currentThread(); USED.release(); } From cac14cb2d020f357dac23c49b908da6f5e9c44ae Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 9 Jan 2018 15:22:09 -0500 Subject: [PATCH 092/779] Typos --- .../management/AbstractClusteringManagementTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java index 5aa96b71ac..1826dde539 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java @@ -215,7 +215,7 @@ public static void afterClass() throws Exception { @Before public void init() throws Exception { if (nmsService != null) { - // this call clear the CURRRENT arrived messages, but be aware that some other messages can arrive just after the drain + // this call clear the CURRENT arrived messages, but be aware that some other messages can arrive just after the drain nmsService.readMessages(); } } @@ -233,7 +233,7 @@ protected static void sendManagementCallOnClientToCollectStats() throws Exceptio } protected static List waitForNextStats() throws Exception { - // uses the monitoring consumre entity to get the content of the stat buffer when some stats are collected + // uses the monitoring to get the content of the stat buffer when some stats are collected return nmsService.waitForMessage(message -> message.getType().equals("STATISTICS")) .stream() .filter(message -> message.getType().equals("STATISTICS")) @@ -250,7 +250,7 @@ protected static List notificationTypes(List messages) { .collect(Collectors.toList()); } - protected static String read(String path) throws FileNotFoundException { + protected static String read(String path) { try (Scanner scanner = new Scanner(AbstractClusteringManagementTest.class.getResourceAsStream(path), "UTF-8")) { return scanner.useDelimiter("\\A").next(); } From 5951f33c52c9a92c4d4e2240a5889071ad103b98 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 4 Jan 2018 16:14:12 -0500 Subject: [PATCH 093/779] Test that StorePassThroughExceptions are handled correctly --- .../store/StoreBulkComputeIfAbsentTest.java | 29 ++++++++ .../internal/store/StoreBulkComputeTest.java | 29 ++++++++ .../store/StoreComputeIfAbsentTest.java | 30 ++++++-- .../internal/store/StoreComputeTest.java | 69 +++++++++++++++++++ .../internal/store/tiering/TieredStore.java | 40 ++++------- 5 files changed, 163 insertions(+), 34 deletions(-) diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java index 4b1b6f1607..87b975a530 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java @@ -16,6 +16,7 @@ package org.ehcache.internal.store; +import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; @@ -24,6 +25,7 @@ import org.ehcache.spi.test.SPITest; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -266,4 +268,31 @@ public void testMappingFunctionProducesWrongValueType() throws Exception { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } } + + @SPITest + public void exception() throws Exception { + Set inputKeys = Collections.singleton(factory.createKey(0)); + + RuntimeException exception = new RuntimeException("error"); + + try { + kvStore.bulkComputeIfAbsent(inputKeys, entries -> { throw exception; }); + } catch (StoreAccessException e) { + assertThat(e.getCause(), is(exception)); + } + } + + @SPITest + public void passThroughException() throws Exception { + Set inputKeys = Collections.singleton(factory.createKey(0)); + + RuntimeException exception = new RuntimeException("error"); + StorePassThroughException ste = new StorePassThroughException(exception); + + try { + kvStore.bulkComputeIfAbsent(inputKeys, entries -> { throw ste; }); + } catch (RuntimeException e) { + assertThat(e, is(exception)); + } + } } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java index 16959921f2..ad2a6c7814 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java @@ -16,6 +16,7 @@ package org.ehcache.internal.store; +import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; @@ -24,6 +25,7 @@ import org.ehcache.spi.test.SPITest; +import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -278,4 +280,31 @@ public void remappingFunctionProducesWrongValueType() throws Exception { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } } + + @SPITest + public void exception() throws Exception { + Set inputKeys = Collections.singleton(factory.createKey(0)); + + RuntimeException exception = new RuntimeException("error"); + + try { + kvStore.bulkCompute(inputKeys, entries -> { throw exception; }); + } catch (StoreAccessException e) { + assertThat(e.getCause(), is(exception)); + } + } + + @SPITest + public void passThroughException() throws Exception { + Set inputKeys = Collections.singleton(factory.createKey(0)); + + RuntimeException exception = new RuntimeException("error"); + StorePassThroughException ste = new StorePassThroughException(exception); + + try { + kvStore.bulkCompute(inputKeys, entries -> { throw ste; }); + } catch (RuntimeException e) { + assertThat(e, is(exception)); + } + } } diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java index f005eb5343..180b8f2f78 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java @@ -15,11 +15,13 @@ */ package org.ehcache.internal.store; +import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; +import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; @@ -179,24 +181,38 @@ public void testFunctionReturnsNull() throws Exception { public void testException() throws Exception { kvStore = factory.newStore(); - final K key = factory.createKey(1L); - - assertThat(kvStore.get(key), nullValue()); + K key = factory.createKey(1L); - final RuntimeException re = new RuntimeException(); + RuntimeException re = new RuntimeException(); try { kvStore.computeIfAbsent(key, keyParam -> { throw re; }); - } catch (RuntimeException e) { - assertThat(e, is(re)); } catch (StoreAccessException e) { - throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); + assertThat(e.getCause(), is(re)); } assertThat(kvStore.get(key), nullValue()); } + @SPITest + public void testStorePassThroughException() throws Exception { + kvStore = factory.newStore(); + + K key = factory.createKey(1L); + + RuntimeException exception = new RuntimeException("error"); + StorePassThroughException re = new StorePassThroughException(exception); + + try { + kvStore.computeIfAbsent(key, keyParam -> { + throw re; + }); + } catch (RuntimeException e) { + assertThat(e, is(exception)); + } + } + @SPITest public void testComputeIfAbsentValuePresentExpiresOnAccess() throws LegalSPITesterException { TestTimeSource timeSource = new TestTimeSource(10043L); diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java index 5a35c180f2..a706ea8ccb 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java @@ -15,11 +15,13 @@ */ package org.ehcache.internal.store; +import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; +import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; @@ -191,6 +193,73 @@ public void testException() throws Exception { assertThat(kvStore.get(key).get(), is(value)); } + @SPITest + public void testStorePassThroughException() throws Exception { + kvStore = factory.newStore(); + + K key = factory.createKey(520928098); + V value = factory.createValue(15098209865L); + + RuntimeException exception = new RuntimeException("error"); + StorePassThroughException re = new StorePassThroughException(exception); + + try { + kvStore.put(key, value); + assertThat(kvStore.get(key).get(), is(value)); + + kvStore.compute(key, (keyParam, oldValue) -> { + throw re; + }); + } catch (RuntimeException e) { + assertThat(e, is(exception)); + } + + assertThat(kvStore.get(key).get(), is(value)); + } + + @SPITest + public void testExceptionOnSupplier() throws Exception { + kvStore = factory.newStore(); + + K key = factory.createKey(520928098); + V value = factory.createValue(15098209865L); + + RuntimeException re = new RuntimeException(); + + try { + kvStore.put(key, value); + assertThat(kvStore.get(key).get(), is(value)); + + kvStore.compute(key, (keyParam, oldValue) -> oldValue, () -> { throw re; }); + } catch (StoreAccessException e) { + assertThat(e.getCause(), is(re)); + } + + assertThat(kvStore.get(key).get(), is(value)); + } + + @SPITest + public void testPassThroughExceptionOnSupplier() throws Exception { + kvStore = factory.newStore(); + + K key = factory.createKey(520928098); + V value = factory.createValue(15098209865L); + + RuntimeException exception = new RuntimeException("error"); + StorePassThroughException re = new StorePassThroughException(exception); + + try { + kvStore.put(key, value); + assertThat(kvStore.get(key).get(), is(value)); + + kvStore.compute(key, (keyParam, oldValue) -> oldValue, () -> { throw re; }); + } catch (RuntimeException e) { + assertThat(e, is(exception)); + } + + assertThat(kvStore.get(key).get(), is(value)); + } + @SPITest public void testComputeExpiresOnAccess() throws Exception { TestTimeSource timeSource = new TestTimeSource(10042L); diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java index fe0ea103f4..ef593d33bc 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java @@ -20,6 +20,7 @@ import org.ehcache.config.ResourceType; import org.ehcache.core.CacheConfigurationChangeListener; import org.ehcache.core.collections.ConcurrentWeakIdentityHashMap; +import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.spi.store.events.StoreEventSource; @@ -29,8 +30,6 @@ import org.ehcache.spi.service.ServiceConfiguration; import org.ehcache.spi.service.ServiceDependencies; import org.ehcache.spi.service.ServiceProvider; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.terracotta.statistics.StatisticsManager; import java.util.AbstractMap; @@ -52,8 +51,6 @@ */ public class TieredStore implements Store { - private static final Logger LOG = LoggerFactory.getLogger(TieredStore.class); - private final AtomicReference> cachingTierRef; private final CachingTier noopCachingTier; private final CachingTier realCachingTier; @@ -84,7 +81,6 @@ public void invalidateAllWithHash(long hash) throws StoreAccessException { StatisticsManager.associate(authoritativeTier).withParent(this); } - @Override public ValueHolder get(final K key) throws StoreAccessException { try { @@ -92,27 +88,14 @@ public ValueHolder get(final K key) throws StoreAccessException { try { return authoritativeTier.getAndFault(keyParam); } catch (StoreAccessException cae) { - throw new ComputationException(cae); + throw new StorePassThroughException(cae); } }); - } catch (ComputationException ce) { - throw ce.getStoreAccessException(); - } - } - - static class ComputationException extends RuntimeException { - - public ComputationException(StoreAccessException cause) { - super(cause); - } - - public StoreAccessException getStoreAccessException() { - return (StoreAccessException) getCause(); - } - - @Override - public synchronized Throwable fillInStackTrace() { - return this; + } catch (StoreAccessException ce) { + if(ce.getCause() instanceof StorePassThroughException) { + throw (StoreAccessException) ce.getCause().getCause(); + } + throw (RuntimeException) ce.getCause(); } } @@ -259,11 +242,14 @@ public ValueHolder computeIfAbsent(final K key, final Function Date: Fri, 5 Jan 2018 13:00:00 -0500 Subject: [PATCH 094/779] No need to keep stack trace of the StorePassThroughException --- .../exceptions/StorePassThroughException.java | 7 +++ .../StorePassThroughExceptionTest.java | 52 +++++++++++++++++++ 2 files changed, 59 insertions(+) create mode 100644 core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java diff --git a/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java b/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java index 219ca9787b..362d6ea606 100644 --- a/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java +++ b/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java @@ -48,6 +48,13 @@ public StorePassThroughException(final Throwable cause) { super(cause); } + @Override + public synchronized Throwable fillInStackTrace() { + // skip the stack trace filling because this exception is just a placeholder and won't ever be caught outside of + // a store + return this; + } + /** * Helper method for handling runtime exceptions. *

diff --git a/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java b/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java new file mode 100644 index 0000000000..74400335b3 --- /dev/null +++ b/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java @@ -0,0 +1,52 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.exceptions; + +import org.ehcache.core.spi.store.StoreAccessException; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.*; + +public class StorePassThroughExceptionTest { + + @Test + public void fillInStackTrace() { + StorePassThroughException e = new StorePassThroughException(new Exception()); + assertThat(e.getStackTrace()).isEmpty(); + } + + @Test + public void handleRuntimeException_runtimeWrappedInStoreAccessException() { + RuntimeException re = new RuntimeException(); + StoreAccessException sae = StorePassThroughException.handleRuntimeException(re); + assertThat(sae.getCause()).isSameAs(re); + } + + @Test + public void handleRuntimeException_storePassThroughExceptionUnwrappedIfRuntime() { + RuntimeException re = new RuntimeException(); + assertThatExceptionOfType(RuntimeException.class) + .isThrownBy(() -> StorePassThroughException.handleRuntimeException(new StorePassThroughException(re))) + .isSameAs(re); + } + + @Test + public void handleRuntimeException_storePassThroughExceptionCauseWrapped() { + Exception e = new Exception(); + StoreAccessException sae = StorePassThroughException.handleRuntimeException(new StorePassThroughException(e)); + assertThat(sae.getCause()).isSameAs(e); + } +} From c26834f9add51c8729e89466244a183f6c6da2a1 Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Tue, 9 Jan 2018 18:45:39 -0500 Subject: [PATCH 095/779] :arrow_up: Upgrade of core + statistics + platform --- .../client/internal/store/AbstractServerStoreProxyTest.java | 6 +++++- .../BasicClusteredCacheOpsReplicationMultiThreadedTest.java | 2 +- gradle.properties | 6 +++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/AbstractServerStoreProxyTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/AbstractServerStoreProxyTest.java index fb6ba014ad..519ab7b140 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/AbstractServerStoreProxyTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/AbstractServerStoreProxyTest.java @@ -15,6 +15,7 @@ */ package org.ehcache.clustered.client.internal.store; +import org.ehcache.clustered.client.config.builders.TimeoutsBuilder; import org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityFactory; import org.ehcache.clustered.client.internal.ClusterTierManagerClientEntityService; import org.ehcache.clustered.client.internal.UnitTestConnectionService; @@ -31,6 +32,7 @@ import org.terracotta.connection.Connection; import java.net.URI; +import java.time.Duration; import java.util.Collections; import java.util.Properties; @@ -65,7 +67,9 @@ protected static SimpleClusterTierClientEntity createClientEntity(String name, Connection connection = CONNECTION_SERVICE.connect(CLUSTER_URI, new Properties()); // Create ClusterTierManagerClientEntity if needed - ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory(connection); + ClusterTierManagerClientEntityFactory entityFactory = new ClusterTierManagerClientEntityFactory( + connection, + TimeoutsBuilder.timeouts().write(Duration.ofSeconds(30)).build()); if (create) { entityFactory.create(name, new ServerSideConfiguration("defaultResource", Collections.emptyMap())); } diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/BasicClusteredCacheOpsReplicationMultiThreadedTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/BasicClusteredCacheOpsReplicationMultiThreadedTest.java index 04faa8a683..76317b6619 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/BasicClusteredCacheOpsReplicationMultiThreadedTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/BasicClusteredCacheOpsReplicationMultiThreadedTest.java @@ -278,7 +278,7 @@ public void testClear() throws Exception { private void drainTasks(List futures) throws InterruptedException, java.util.concurrent.ExecutionException { for (int i = 0; i < futures.size(); i++) { try { - futures.get(i).get(10, TimeUnit.SECONDS); + futures.get(i).get(60, TimeUnit.SECONDS); } catch (TimeoutException e) { fail("Stuck on number " + i); } diff --git a/gradle.properties b/gradle.properties index c149306ebf..640ab085ca 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,15 +1,15 @@ # Terracotta third parties offheapVersion = 2.4.0 -statisticVersion = 2.0.0 +statisticVersion = 2.0.1 jcacheVersion = 1.1.0 slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre10 +terracottaPlatformVersion = 5.4.0-pre12 terracottaApisVersion = 1.4.0-pre8 -terracottaCoreVersion = 5.4.0-pre16 +terracottaCoreVersion = 5.4.0-pre17 terracottaPassthroughTestingVersion = 1.4.0-pre9 # Test lib versions From e055a53a920c3558deaa02a5dca09a531e976cc1 Mon Sep 17 00:00:00 2001 From: Louis Jacomet Date: Wed, 10 Jan 2018 17:18:37 +0100 Subject: [PATCH 096/779] Switch plugin for XJC generation --- xml/build.gradle | 31 +++++--------------------- xml/config/checkstyle-suppressions.xml | 4 ++-- 2 files changed, 7 insertions(+), 28 deletions(-) diff --git a/xml/build.gradle b/xml/build.gradle index 28e4c2d809..e4fa448292 100644 --- a/xml/build.gradle +++ b/xml/build.gradle @@ -15,24 +15,13 @@ */ plugins { - id 'com.github.jacobono.jaxb' version '1.3.5' + id 'org.unbroken-dome.xjc' version '1.1.3' } apply plugin: EhDeploy dependencies { compile project(':api'), project(':core'), project(':impl') - - // Constrained to JAXB 2.1 due to JDK 1.6 compatibility requirements - jaxb 'com.sun.xml.bind:jaxb-xjc:2.1.17' - jaxb 'com.sun.xml.bind:jaxb-impl:2.1.17' - jaxb 'javax.xml:jaxb-api:2.1' -} - -def generatedSources = "src/generated/java" - -sourceSets.main.java { - srcDir generatedSources } test { @@ -41,18 +30,8 @@ test { } } -jaxb { - xsdDir = "$name/src/main/resources" - episodesDir = "$name/build/xsd/episodes" - bindingsDir = "$name/build/xsd/bindings" - xjc { - destinationDir = generatedSources - generatePackage = "org.ehcache.xml.model" - } - - compileJava.dependsOn "xjc" -} - -clean { - delete generatedSources +xjcGenerate { + source = fileTree('src/main/resources') { include '*.xsd' } + targetPackage = 'org.ehcache.xml.model' + extension = true } diff --git a/xml/config/checkstyle-suppressions.xml b/xml/config/checkstyle-suppressions.xml index b156d0e18d..a287bf4e21 100644 --- a/xml/config/checkstyle-suppressions.xml +++ b/xml/config/checkstyle-suppressions.xml @@ -5,6 +5,6 @@ "http://www.puppycrawl.com/dtds/suppressions_1_1.dtd"> - + - \ No newline at end of file + From a27aad5633000c80fa4cbde8841fec033edfe722 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Fri, 22 Dec 2017 11:23:37 -0500 Subject: [PATCH 097/779] Fix javadoc issues on expiration API --- api/src/main/java/org/ehcache/expiry/Expirations.java | 8 ++++---- api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/api/src/main/java/org/ehcache/expiry/Expirations.java b/api/src/main/java/org/ehcache/expiry/Expirations.java index ef6c711d12..cb6e99b82d 100644 --- a/api/src/main/java/org/ehcache/expiry/Expirations.java +++ b/api/src/main/java/org/ehcache/expiry/Expirations.java @@ -30,7 +30,7 @@ public final class Expirations { * * @return the no expiry instance * - * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#noExpiration()} instead + * @deprecated Use {@code org.ehcache.config.builders.ExpiryPolicyBuilder#noExpiration()} instead */ @Deprecated public static Expiry noExpiration() { @@ -43,7 +43,7 @@ public static Expiry noExpiration() { * @param timeToLive the TTL duration * @return a TTL expiry * - * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#timeToLiveExpiration(java.time.Duration)} instead + * @deprecated Use {@code org.ehcache.config.builders.ExpiryPolicyBuilder#timeToLiveExpiration(java.time.Duration)} instead */ @Deprecated public static Expiry timeToLiveExpiration(Duration timeToLive) { @@ -59,7 +59,7 @@ public static Expiry timeToLiveExpiration(Duration timeToLive) { * @param timeToIdle the TTI duration * @return a TTI expiry * - * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#timeToIdleExpiration(java.time.Duration)} instead + * @deprecated Use {@code org.ehcache.config.builders.ExpiryPolicyBuilder#timeToIdleExpiration(java.time.Duration)} instead */ @Deprecated public static Expiry timeToIdleExpiration(Duration timeToIdle) { @@ -78,7 +78,7 @@ public static Expiry timeToIdleExpiration(Duration timeToIdle) { * @param the value type for the cache * @return an {@link Expiry} builder * - * @deprecated Use {@link org.ehcache.config.builders.ExpiryPolicyBuilder#expiry()} instead + * @deprecated Use {@code org.ehcache.config.builders.ExpiryPolicyBuilder#expiry()} instead */ @Deprecated public static ExpiryBuilder builder() { diff --git a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java index 907dd70afd..c50c95abaa 100644 --- a/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java +++ b/api/src/main/java/org/ehcache/expiry/ExpiryPolicy.java @@ -25,8 +25,8 @@ * Previous values are not accessible directly but are rather available through a value {@code Supplier} * to indicate that access can require computation (such as deserialization). *

- * {@link Duration#isNegative() Negative duration} are not supported, expiry policy implementation returning such a - * duration will result in immediate expiry, as if the duration was {@link Duration#ZERO zero}. + * {@link java.time.Duration#isNegative() Negative durations} are not supported, expiry policy implementation returning such a + * duration will result in immediate expiry, as if the duration was {@link java.time.Duration#ZERO zero}. *

* NOTE: Some cache configurations (eg. caches with eventual consistency) may use local (ie. non-consistent) state * to decide whether to call {@link #getExpiryForUpdate(Object, Supplier, Object)} vs. From 643a73720094c5a3cbca08f907d044a80949888b Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 10 Jan 2018 13:33:24 -0500 Subject: [PATCH 098/779] Refactoring of statistics descriptor constants --- .../ClusteringManagementServiceTest.java | 141 +++++++++--------- 1 file changed, 70 insertions(+), 71 deletions(-) diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java index 1526f8db05..6480ea13e4 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java @@ -48,14 +48,72 @@ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ClusteringManagementServiceTest extends AbstractClusteringManagementTest { - private static final Collection ONHEAP_DESCRIPTORS = new ArrayList<>(); - private static final Collection OFFHEAP_DESCRIPTORS = new ArrayList<>(); - private static final Collection DISK_DESCRIPTORS = new ArrayList<>(); - private static final Collection CLUSTERED_DESCRIPTORS = new ArrayList<>(); - private static final Collection CACHE_DESCRIPTORS = new ArrayList<>(); - private static final Collection POOL_DESCRIPTORS = new ArrayList<>(); - private static final Collection SERVER_STORE_DESCRIPTORS = new ArrayList<>(); - private static final Collection OFFHEAP_RES_DESCRIPTORS = new ArrayList<>(); + private static final Collection ONHEAP_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("OnHeap:EvictionCount" , "COUNTER"), + new StatisticDescriptor("OnHeap:ExpirationCount" , "COUNTER"), + new StatisticDescriptor("OnHeap:MissCount" , "COUNTER"), + new StatisticDescriptor("OnHeap:MappingCount" , "COUNTER"), + new StatisticDescriptor("OnHeap:HitCount" , "COUNTER"), + new StatisticDescriptor("OnHeap:PutCount" , "COUNTER"), + new StatisticDescriptor("OnHeap:RemovalCount" , "COUNTER") + ); + private static final Collection OFFHEAP_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("OffHeap:MissCount", "COUNTER"), + new StatisticDescriptor("OffHeap:OccupiedByteSize", "GAUGE"), + new StatisticDescriptor("OffHeap:AllocatedByteSize", "GAUGE"), + new StatisticDescriptor("OffHeap:MappingCount", "COUNTER"), + new StatisticDescriptor("OffHeap:EvictionCount", "COUNTER"), + new StatisticDescriptor("OffHeap:ExpirationCount", "COUNTER"), + new StatisticDescriptor("OffHeap:HitCount", "COUNTER"), + new StatisticDescriptor("OffHeap:PutCount", "COUNTER"), + new StatisticDescriptor("OffHeap:RemovalCount", "COUNTER") + ); + private static final Collection DISK_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("Disk:OccupiedByteSize", "GAUGE"), + new StatisticDescriptor("Disk:AllocatedByteSize", "GAUGE"), + new StatisticDescriptor("Disk:HitCount", "COUNTER"), + new StatisticDescriptor("Disk:EvictionCount", "COUNTER"), + new StatisticDescriptor("Disk:ExpirationCount", "COUNTER"), + new StatisticDescriptor("Disk:MissCount", "COUNTER"), + new StatisticDescriptor("Disk:MappingCount", "COUNTER"), + new StatisticDescriptor("Disk:PutCount", "COUNTER"), + new StatisticDescriptor("Disk:RemovalCount", "COUNTER") + ); + private static final Collection CLUSTERED_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("Clustered:MissCount", "COUNTER"), + new StatisticDescriptor("Clustered:HitCount", "COUNTER"), + new StatisticDescriptor("Clustered:PutCount", "COUNTER"), + new StatisticDescriptor("Clustered:RemovalCount", "COUNTER"), + new StatisticDescriptor("Clustered:EvictionCount", "COUNTER"), + new StatisticDescriptor("Clustered:ExpirationCount", "COUNTER") + ); + private static final Collection CACHE_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("Cache:HitCount", "COUNTER"), + new StatisticDescriptor("Cache:MissCount", "COUNTER"), + new StatisticDescriptor("Cache:PutCount", "COUNTER"), + new StatisticDescriptor("Cache:RemovalCount", "COUNTER"), + new StatisticDescriptor("Cache:EvictionCount", "COUNTER"), + new StatisticDescriptor("Cache:ExpirationCount", "COUNTER") + ); + private static final Collection POOL_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("Pool:AllocatedSize", "GAUGE") + ); + private static final Collection SERVER_STORE_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("Store:AllocatedMemory", "GAUGE"), + new StatisticDescriptor("Store:DataAllocatedMemory", "GAUGE"), + new StatisticDescriptor("Store:OccupiedMemory", "GAUGE"), + new StatisticDescriptor("Store:DataOccupiedMemory", "GAUGE"), + new StatisticDescriptor("Store:Entries", "COUNTER"), + new StatisticDescriptor("Store:UsedSlotCount", "COUNTER"), + new StatisticDescriptor("Store:DataVitalMemory", "GAUGE"), + new StatisticDescriptor("Store:VitalMemory", "GAUGE"), + new StatisticDescriptor("Store:RemovedSlotCount", "COUNTER"), + new StatisticDescriptor("Store:DataSize", "GAUGE"), + new StatisticDescriptor("Store:TableCapacity", "GAUGE") + ); + private static final Collection OFFHEAP_RES_DESCRIPTORS = Arrays.asList( + new StatisticDescriptor("OffHeapResource:AllocatedMemory", "GAUGE") + ); @Test @Ignore("This is not a test, but something useful to show a json print of a cluster topology with all management metadata inside") @@ -280,10 +338,12 @@ public void test_G_stats_collection() throws Exception { } while(!Thread.currentThread().isInterrupted() && val != 4); // wait until we have some stats coming from the server entity - while (!Thread.currentThread().isInterrupted() && !allStats.stream().filter(statistics -> statistics.getContext().contains("consumerId")).findFirst().isPresent()) { + while (!Thread.currentThread().isInterrupted() && !allStats.stream().anyMatch(statistics -> statistics.getContext().contains("consumerId"))) { allStats.addAll(waitForNextStats()); } - List serverStats = allStats.stream().filter(statistics -> statistics.getContext().contains("consumerId")).collect(Collectors.toList()); + List serverStats = allStats.stream() + .filter(statistics -> statistics.getContext().contains("consumerId")) + .collect(Collectors.toList()); // server-side stats TreeSet capabilities = serverStats.stream() @@ -333,65 +393,4 @@ public void test_G_stats_collection() throws Exception { assertThat(offHeapResourceDescriptors).isEqualTo(OFFHEAP_RES_DESCRIPTORS.stream().map(StatisticDescriptor::getName).collect(Collectors.toSet())); } - @BeforeClass - public static void initDescriptors() throws ClassNotFoundException { - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:EvictionCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:ExpirationCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:MissCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:MappingCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:HitCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:PutCount" , "COUNTER")); - ONHEAP_DESCRIPTORS.add(new StatisticDescriptor("OnHeap:RemovalCount" , "COUNTER")); - - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MissCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:OccupiedByteSize", "GAUGE")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:AllocatedByteSize", "GAUGE")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:MappingCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:EvictionCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:ExpirationCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:HitCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:PutCount", "COUNTER")); - OFFHEAP_DESCRIPTORS.add(new StatisticDescriptor("OffHeap:RemovalCount", "COUNTER")); - - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:OccupiedByteSize", "GAUGE")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:AllocatedByteSize", "GAUGE")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:HitCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:EvictionCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:ExpirationCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:MissCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:MappingCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:PutCount", "COUNTER")); - DISK_DESCRIPTORS.add(new StatisticDescriptor("Disk:RemovalCount", "COUNTER")); - - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:MissCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:HitCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:PutCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:RemovalCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:EvictionCount", "COUNTER")); - CLUSTERED_DESCRIPTORS.add(new StatisticDescriptor("Clustered:ExpirationCount", "COUNTER")); - - CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:HitCount", "COUNTER")); - CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:MissCount", "COUNTER")); - CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:PutCount", "COUNTER")); - CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:RemovalCount", "COUNTER")); - CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:EvictionCount", "COUNTER")); - CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:ExpirationCount", "COUNTER")); - - POOL_DESCRIPTORS.add(new StatisticDescriptor("Pool:AllocatedSize", "GAUGE")); - - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:AllocatedMemory", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataAllocatedMemory", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:OccupiedMemory", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataOccupiedMemory", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:Entries", "COUNTER")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:UsedSlotCount", "COUNTER")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataVitalMemory", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:VitalMemory", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:RemovedSlotCount", "COUNTER")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:DataSize", "GAUGE")); - SERVER_STORE_DESCRIPTORS.add(new StatisticDescriptor("Store:TableCapacity", "GAUGE")); - - OFFHEAP_RES_DESCRIPTORS.add(new StatisticDescriptor("OffHeapResource:AllocatedMemory", "GAUGE")); - } - } From 13429c2cfa048e490571f5bd9be6e1b8041061d4 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Thu, 11 Jan 2018 22:04:26 +0530 Subject: [PATCH 099/779] Change default timeout --- .../java/org/ehcache/clustered/client/config/Timeouts.java | 3 ++- .../client/internal/service/DefaultClusteringService.java | 1 + .../client/config/builders/TimeoutsBuilderTest.java | 6 +++--- .../src/test/resources/clusteredConfiguration.txt | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java b/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java index df979b664c..10d755c5de 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/config/Timeouts.java @@ -29,8 +29,9 @@ public final class Timeouts { public static final Duration DEFAULT_OPERATION_TIMEOUT = Duration.ofSeconds(5); + public static final Duration DEFAULT_CONNECTION_TIMEOUT = Duration.ofSeconds(150); public static final Duration INFINITE_TIMEOUT = Duration.ofNanos(Long.MAX_VALUE); - public static final Timeouts DEFAULT = new Timeouts(DEFAULT_OPERATION_TIMEOUT, DEFAULT_OPERATION_TIMEOUT, INFINITE_TIMEOUT); + public static final Timeouts DEFAULT = new Timeouts(DEFAULT_OPERATION_TIMEOUT, DEFAULT_OPERATION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT); private final Duration readOperationTimeout; private final Duration writeOperationTimeout; diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java index 0e4b734a14..87fe8fb77f 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java @@ -175,6 +175,7 @@ private void initClusterConnection() { properties.put(ConnectionPropertyNames.CONNECTION_NAME, CONNECTION_PREFIX + entityIdentifier); properties.put(ConnectionPropertyNames.CONNECTION_TIMEOUT, Long.toString(timeouts.getConnectionTimeout().toMillis())); clusterConnection = ConnectionFactory.connect(clusterUri, properties); + } catch (ConnectionException ex) { throw new RuntimeException(ex); } diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/config/builders/TimeoutsBuilderTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/config/builders/TimeoutsBuilderTest.java index 2f1d67910b..266799a904 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/config/builders/TimeoutsBuilderTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/config/builders/TimeoutsBuilderTest.java @@ -26,15 +26,15 @@ public class TimeoutsBuilderTest { @Test - public void build_empty() throws Exception { + public void build_empty() { Timeouts t = TimeoutsBuilder.timeouts().build(); assertThat(t.getReadOperationTimeout()).isEqualTo(Timeouts.DEFAULT_OPERATION_TIMEOUT); assertThat(t.getWriteOperationTimeout()).isEqualTo(Timeouts.DEFAULT_OPERATION_TIMEOUT); - assertThat(t.getConnectionTimeout()).isEqualTo(Timeouts.INFINITE_TIMEOUT); + assertThat(t.getConnectionTimeout()).isEqualTo(Timeouts.DEFAULT_CONNECTION_TIMEOUT); } @Test - public void build_filled() throws Exception { + public void build_filled() { Timeouts t = TimeoutsBuilder.timeouts() .read(Duration.ofDays(1)) .write(Duration.ofDays(2)) diff --git a/clustered/integration-test/src/test/resources/clusteredConfiguration.txt b/clustered/integration-test/src/test/resources/clusteredConfiguration.txt index 2d070ab3ff..01de31f03a 100644 --- a/clustered/integration-test/src/test/resources/clusteredConfiguration.txt +++ b/clustered/integration-test/src/test/resources/clusteredConfiguration.txt @@ -33,7 +33,7 @@ caches: services: - org.ehcache.clustered.client.config.ClusteringServiceConfiguration: clusterUri: terracotta://server-1/my-server-entity-2 - timeouts: Timeouts{readOperation=PT5S,writeOperation=PT5S,connection=PT2562047H47M16.854775807S} + timeouts: Timeouts{readOperation=PT5S,writeOperation=PT5S,connection=PT2M30S} autoCreate: true defaultServerResource: primary-server-resource resourcePools: From 89905e15d7a868e5c33319968afeb03761b729c0 Mon Sep 17 00:00:00 2001 From: Saurabh Agarwal Date: Fri, 12 Jan 2018 16:14:37 +0530 Subject: [PATCH 100/779] Updated platform and core versions --- gradle.properties | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gradle.properties b/gradle.properties index 640ab085ca..a3c1dd845b 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,9 +7,9 @@ slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre12 +terracottaPlatformVersion = 5.4.0-pre13 terracottaApisVersion = 1.4.0-pre8 -terracottaCoreVersion = 5.4.0-pre17 +terracottaCoreVersion = 5.4.0-pre18 terracottaPassthroughTestingVersion = 1.4.0-pre9 # Test lib versions From 64bb9b50c941e1920888740b740693cf23467e6d Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Fri, 12 Jan 2018 12:37:28 -0500 Subject: [PATCH 101/779] :arrow_up: Upgrade of statistics + platform --- .../management/ClusteredStatisticsCountTest.java | 8 ++++---- .../management/ClusteringManagementServiceTest.java | 4 ++-- .../clustered/server/EhcacheStateServiceImpl.java | 2 +- gradle.properties | 4 ++-- .../internal/statistics/DefaultCacheStatistics.java | 2 +- .../internal/statistics/DefaultTierStatistics.java | 4 ++-- .../test/java/org/ehcache/docs/ManagementTest.java | 2 +- .../StandardEhCacheStatisticsQueryTest.java | 2 +- .../statistics/StandardEhcacheStatisticsTest.java | 2 +- .../management/providers/statistics/StatsUtil.java | 2 +- .../DefaultManagementRegistryServiceTest.java | 10 +++++----- .../registry/DefaultSharedManagementServiceTest.java | 12 ++++++------ 12 files changed, 27 insertions(+), 27 deletions(-) diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java index 8679f95a3c..f27143201e 100755 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteredStatisticsCountTest.java @@ -66,10 +66,10 @@ public void countTest() throws Exception { System.out.println(" - " + entry.getKey() + " : " + entry.getValue()); }*/ - cacheHitCount = stat.getLatestSample("Cache:HitCount").get(); - clusteredHitCount = stat.getLatestSample("Clustered:HitCount").get(); - clusteredMissCount = stat.getLatestSample("Clustered:MissCount").get(); - cacheMissCount = stat.getLatestSample("Cache:MissCount").get(); + cacheHitCount = stat.getLatestSampleValue("Cache:HitCount").get(); + clusteredHitCount = stat.getLatestSampleValue("Clustered:HitCount").get(); + clusteredMissCount = stat.getLatestSampleValue("Clustered:MissCount").get(); + cacheMissCount = stat.getLatestSampleValue("Cache:MissCount").get(); } } } while(!Thread.currentThread().isInterrupted() && diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java index 6480ea13e4..1cfaebd8cb 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java @@ -314,7 +314,7 @@ public void test_G_stats_collection() throws Exception { .collect(Collectors.toList()); for (ContextualStatistics stat : stats) { - val = stat.getLatestSample("Cache:HitCount").get(); + val = stat.getLatestSampleValue("Cache:HitCount").get(); } } while(!Thread.currentThread().isInterrupted() && val != 2); @@ -332,7 +332,7 @@ public void test_G_stats_collection() throws Exception { .collect(Collectors.toList()); for (ContextualStatistics stat : stats) { - val = stat.getLatestSample("Cache:HitCount").get(); + val = stat.getLatestSampleValue("Cache:HitCount").get(); } } while(!Thread.currentThread().isInterrupted() && val != 4); diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java b/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java index 37970e8a50..d7275395b4 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/EhcacheStateServiceImpl.java @@ -53,7 +53,7 @@ import static java.util.stream.Collectors.toMap; import static org.terracotta.offheapresource.OffHeapResourceIdentifier.identifier; import static org.terracotta.statistics.StatisticsManager.tags; -import static org.terracotta.statistics.SuppliedValueStatistic.supply; +import static org.terracotta.statistics.ValueStatistics.supply; import static org.terracotta.statistics.StatisticType.COUNTER; import static org.terracotta.statistics.StatisticType.GAUGE; diff --git a/gradle.properties b/gradle.properties index a3c1dd845b..b163628b4a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,13 +1,13 @@ # Terracotta third parties offheapVersion = 2.4.0 -statisticVersion = 2.0.1 +statisticVersion = 2.0.2 jcacheVersion = 1.1.0 slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre13 +terracottaPlatformVersion = 5.4.0-pre14 terracottaApisVersion = 1.4.0-pre8 terracottaCoreVersion = 5.4.0-pre18 terracottaPassthroughTestingVersion = 1.4.0-pre9 diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java index dac28dc393..7d51329b02 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java @@ -38,7 +38,7 @@ import static org.ehcache.impl.internal.statistics.StatsUtils.findLowestTier; import static org.ehcache.impl.internal.statistics.StatsUtils.findOperationStatisticOnChildren; import static org.ehcache.impl.internal.statistics.StatsUtils.findTiers; -import static org.terracotta.statistics.SuppliedValueStatistic.counter; +import static org.terracotta.statistics.ValueStatistics.counter; /** * Contains usage statistics relative to a given cache. diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java index 7379387ee1..86a25cec92 100755 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultTierStatistics.java @@ -31,8 +31,8 @@ import java.util.Optional; import static org.ehcache.impl.internal.statistics.StatsUtils.findStatisticOnDescendants; -import static org.terracotta.statistics.SuppliedValueStatistic.counter; -import static org.terracotta.statistics.SuppliedValueStatistic.gauge; +import static org.terracotta.statistics.ValueStatistics.counter; +import static org.terracotta.statistics.ValueStatistics.gauge; /** * Contains usage statistics relative to a given tier. diff --git a/management/src/test/java/org/ehcache/docs/ManagementTest.java b/management/src/test/java/org/ehcache/docs/ManagementTest.java index 2a35b1be8e..236378eb8c 100644 --- a/management/src/test/java/org/ehcache/docs/ManagementTest.java +++ b/management/src/test/java/org/ehcache/docs/ManagementTest.java @@ -231,7 +231,7 @@ public void managingMultipleCacheManagers() throws Exception { ContextualStatistics statisticsContext1 = counters.getResult(context1); - Long counterContext1 = statisticsContext1.getLatestSample("Cache:MissCount").get(); + Long counterContext1 = statisticsContext1.getLatestSampleValue("Cache:MissCount").get(); // miss count is a sampled stat, for example its values could be [0,1,2]. // In the present case, only the last value is important to us , the cache was eventually missed 2 times diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java index c15041b618..6b9e6f2183 100755 --- a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhCacheStatisticsQueryTest.java @@ -162,7 +162,7 @@ public static long getAndAssertExpectedValueFromCounter(String statName, Context assertThat(counters.size(), Matchers.is(1)); - Long counter = statisticsContext.getLatestSample(statName).get(); + Long counter = statisticsContext.getLatestSampleValue(statName).get(); assertThat(counter, Matchers.is(expectedResult)); diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java index 859c2b00b3..c85823ebde 100755 --- a/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/StandardEhcacheStatisticsTest.java @@ -73,7 +73,7 @@ public void statsClearCacheTest() throws InterruptedException { .getSingleResult(); assertThat(counter.size(), Matchers.is(1)); - Long count = counter. getLatestSample("Cache:HitCount").get(); + Long count = counter. getLatestSampleValue("Cache:HitCount").get(); assertThat(count.longValue(), Matchers.equalTo(1L)); } diff --git a/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java b/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java index 607943581a..8a792fc60e 100755 --- a/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java +++ b/management/src/test/java/org/ehcache/management/providers/statistics/StatsUtil.java @@ -54,7 +54,7 @@ public static long getAndAssertExpectedValueFromCounter(String statName, Context assertThat(counters.size(), Matchers.is(1)); - Number counter = statisticsContext.getLatestSample(statName).get(); + Number counter = statisticsContext.getLatestSampleValue(statName).get(); long value = counter.longValue(); assertThat(value, Matchers.is(expectedResult)); diff --git a/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java b/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java index 8c8cde9b8c..3deea5fedd 100644 --- a/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java +++ b/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java @@ -277,7 +277,7 @@ public void testCanGetStats() { .on(context1); ContextualStatistics counters = getResultSet(builder1, context1, null, queryStatisticName).getResult(context1); - Number counterHistory1 = counters.getLatestSample(queryStatisticName).get(); + Number counterHistory1 = counters.getLatestSampleValue(queryStatisticName).get(); assertThat(counters.size()).isEqualTo(1); assertThat(counterHistory1.longValue()).isEqualTo(1L); @@ -292,8 +292,8 @@ public void testCanGetStats() { assertThat(allCounters.getResult(context1).size()).isEqualTo(1); assertThat(allCounters.getResult(context2).size()).isEqualTo(1); - assertThat(allCounters.getResult(context1).getLatestSample(queryStatisticName).get()).isEqualTo(1L); - assertThat(allCounters.getResult(context2).getLatestSample(queryStatisticName).get()).isEqualTo(1L); + assertThat(allCounters.getResult(context1).getLatestSampleValue(queryStatisticName).get()).isEqualTo(1L); + assertThat(allCounters.getResult(context2).getLatestSampleValue(queryStatisticName).get()).isEqualTo(1L); cacheManager1.close(); } @@ -306,12 +306,12 @@ private static ResultSet getResultSet(Builder builder, Con counters = builder.build().execute(); ContextualStatistics statisticsContext1 = counters.getResult(context1); - Number counterContext1 = statisticsContext1.getLatestSample(statisticsName).get(); + Number counterContext1 = statisticsContext1.getLatestSampleValue(statisticsName).get(); if(context2 != null) { ContextualStatistics statisticsContext2 = counters.getResult(context2); - Number counterHistoryContext2 = statisticsContext2.getLatestSample(statisticsName).get(); + Number counterHistoryContext2 = statisticsContext2.getLatestSampleValue(statisticsName).get(); if(counterHistoryContext2.longValue() > 0 && counterContext1.longValue() > 0) diff --git a/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java b/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java index 0b3287474d..a05a4bda98 100644 --- a/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java +++ b/management/src/test/java/org/ehcache/management/registry/DefaultSharedManagementServiceTest.java @@ -184,9 +184,9 @@ public void testStats() { assertThat(allCounters.getResult(contextList.get(2)).size(), equalTo(1)); - assertThat(allCounters.getResult(contextList.get(0)).getLatestSample(statisticName).get(), equalTo(1L)); - assertThat(allCounters.getResult(contextList.get(1)).getLatestSample(statisticName).get(), equalTo(1L)); - assertThat(allCounters.getResult(contextList.get(2)).getLatestSample(statisticName).get(), equalTo(1L)); + assertThat(allCounters.getResult(contextList.get(0)).getLatestSampleValue(statisticName).get(), equalTo(1L)); + assertThat(allCounters.getResult(contextList.get(1)).getLatestSampleValue(statisticName).get(), equalTo(1L)); + assertThat(allCounters.getResult(contextList.get(2)).getLatestSampleValue(statisticName).get(), equalTo(1L)); } @@ -197,9 +197,9 @@ private static ResultSet getResultSet(StatisticQuery.Build while(!Thread.currentThread().isInterrupted()) { counters = builder.build().execute(); - if(counters.getResult(contextList.get(0)).getLatestSample(statisticsName).get()> 0 && - counters.getResult(contextList.get(1)).getLatestSample(statisticsName).get() > 0 && - counters.getResult(contextList.get(2)).getLatestSample(statisticsName).get() > 0) { + if(counters.getResult(contextList.get(0)).getLatestSampleValue(statisticsName).get()> 0 && + counters.getResult(contextList.get(1)).getLatestSampleValue(statisticsName).get() > 0 && + counters.getResult(contextList.get(2)).getLatestSampleValue(statisticsName).get() > 0) { break; } } From 6493ecc232566c250d94f51ecc71607788a83196 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 16 Jan 2018 13:29:27 -0500 Subject: [PATCH 102/779] Test Functions class --- .../ehcache/core/internal/util/Functions.java | 2 +- .../core/internal/util/FunctionsTest.java | 74 +++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 core/src/test/java/org/ehcache/core/internal/util/FunctionsTest.java diff --git a/core/src/main/java/org/ehcache/core/internal/util/Functions.java b/core/src/main/java/org/ehcache/core/internal/util/Functions.java index 472ea3c5ac..be4fd29a18 100644 --- a/core/src/main/java/org/ehcache/core/internal/util/Functions.java +++ b/core/src/main/java/org/ehcache/core/internal/util/Functions.java @@ -89,8 +89,8 @@ public T apply(final A a, final B b) { if (computed) { return value; } - computed = true; value = function.apply(a, b); + computed = true; return value; } } diff --git a/core/src/test/java/org/ehcache/core/internal/util/FunctionsTest.java b/core/src/test/java/org/ehcache/core/internal/util/FunctionsTest.java new file mode 100644 index 0000000000..5e0675d148 --- /dev/null +++ b/core/src/test/java/org/ehcache/core/internal/util/FunctionsTest.java @@ -0,0 +1,74 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.internal.util; + +import org.junit.Test; + +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.BiFunction; +import java.util.function.Function; + +import static org.assertj.core.api.Assertions.*; + +public class FunctionsTest { + + @Test + public void memoizeFunction() { + AtomicInteger i = new AtomicInteger(); + Function function = Functions.memoize(a -> i.incrementAndGet()); + assertThat(function.apply("a").intValue()).isEqualTo(1); + assertThat(function.apply("b").intValue()).isEqualTo(1); // note that the parameter changes, the result should still be the same + } + + @Test + public void memoizeFunction_shouldNotMemoizeOnException() { + AtomicBoolean firstTime = new AtomicBoolean(true); + Function function = Functions.memoize(a -> { + if (firstTime.get()) { + firstTime.set(false); + throw new RuntimeException("Failed"); + } + return 2; + }); + + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> function.apply("a")).withMessage("Failed"); + assertThat(function.apply("a").intValue()).isEqualTo(2); + } + + @Test + public void memoizeBiFunction() { + AtomicInteger i = new AtomicInteger(); + BiFunction function = Functions.memoize((a, b) -> i.incrementAndGet()); + assertThat(function.apply("a", "a").intValue()).isEqualTo(1); + assertThat(function.apply("b", "b").intValue()).isEqualTo(1); // note that the parameter changes, the result should still be the same + } + + @Test + public void memoizeBiFunction_shouldNotMemoizeOnException() { + AtomicBoolean firstTime = new AtomicBoolean(true); + BiFunction function = Functions.memoize((a, b) -> { + if (firstTime.get()) { + firstTime.set(false); + throw new RuntimeException("Failed"); + } + return 2; + }); + + assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> function.apply("a", "b")).withMessage("Failed"); + assertThat(function.apply("a", "b").intValue()).isEqualTo(2); + } +} From 8770ca777a665c9b92730fefe1c0ebea34374ef8 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 16 Jan 2018 13:53:30 -0500 Subject: [PATCH 103/779] Get rid of deprecation warnings about ValueSupplier --- api/src/main/java/org/ehcache/expiry/Expirations.java | 6 ++---- api/src/main/java/org/ehcache/expiry/Expiry.java | 10 ++++------ .../org/ehcache/core/internal/util/ValueSuppliers.java | 2 +- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/api/src/main/java/org/ehcache/expiry/Expirations.java b/api/src/main/java/org/ehcache/expiry/Expirations.java index cb6e99b82d..76aa9b8381 100644 --- a/api/src/main/java/org/ehcache/expiry/Expirations.java +++ b/api/src/main/java/org/ehcache/expiry/Expirations.java @@ -15,8 +15,6 @@ */ package org.ehcache.expiry; -import org.ehcache.ValueSupplier; - import java.util.Objects; /** @@ -111,12 +109,12 @@ public Duration getExpiryForCreation(K key, V value) { } @Override - public Duration getExpiryForAccess(K key, ValueSupplier value) { + public Duration getExpiryForAccess(K key, org.ehcache.ValueSupplier value) { return access; } @Override - public Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue) { + public Duration getExpiryForUpdate(K key, org.ehcache.ValueSupplier oldValue, V newValue) { return update; } diff --git a/api/src/main/java/org/ehcache/expiry/Expiry.java b/api/src/main/java/org/ehcache/expiry/Expiry.java index db8e44fc35..546ee034d0 100644 --- a/api/src/main/java/org/ehcache/expiry/Expiry.java +++ b/api/src/main/java/org/ehcache/expiry/Expiry.java @@ -16,16 +16,14 @@ package org.ehcache.expiry; -import org.ehcache.ValueSupplier; - /** * A policy object that governs expiration for mappings in a {@link org.ehcache.Cache Cache}. *

- * Previous values are not accessible directly but are rather available through a {@link ValueSupplier value supplier} + * Previous values are not accessible directly but are rather available through a {@link org.ehcache.ValueSupplier value supplier} * to indicate that access can require computation (such as deserialization). *

* NOTE: Some cache configurations (eg. caches with eventual consistency) may use local (ie. non-consistent) state - * to decide whether to call {@link #getExpiryForUpdate(Object, ValueSupplier, Object)} vs. + * to decide whether to call {@link #getExpiryForUpdate(Object, org.ehcache.ValueSupplier, Object)} vs. * {@link #getExpiryForCreation(Object, Object)}. For these cache configurations it is advised to return the same * value for both of these methods *

@@ -69,7 +67,7 @@ public interface Expiry { * @param value a value supplier for the accessed entry * @return an expiration {@code Duration}, {@code null} means unchanged */ - Duration getExpiryForAccess(K key, ValueSupplier value); + Duration getExpiryForAccess(K key, org.ehcache.ValueSupplier value); /** @@ -86,6 +84,6 @@ public interface Expiry { * @param newValue the new value of the entry * @return an expiration {@code Duration}, {@code null} means unchanged */ - Duration getExpiryForUpdate(K key, ValueSupplier oldValue, V newValue); + Duration getExpiryForUpdate(K key, org.ehcache.ValueSupplier oldValue, V newValue); } diff --git a/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java b/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java index 0dad3efa24..7d24db1173 100644 --- a/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java +++ b/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java @@ -24,7 +24,7 @@ * @deprecated Now using {@code Supplier} for {@link org.ehcache.expiry.ExpiryPolicy} */ @Deprecated -public class ValueSuppliers { +public final class ValueSuppliers { /** * Returns a basic {@link ValueSupplier} that serves the value passed in From 14cf571ec839d71fab037c5bfc0c89d95667cebe Mon Sep 17 00:00:00 2001 From: Chris Dennis Date: Tue, 16 Jan 2018 16:51:56 -0500 Subject: [PATCH 104/779] Prepare for developer doc integration --- Home.asciidoc => docs/src/docs/asciidoc/developer/Home.asciidoc | 0 .../src/docs/asciidoc/developer/design.basics.asciidoc | 0 .../src/docs/asciidoc/developer/design.bootstrapping.asciidoc | 0 .../src/docs/asciidoc/developer/design.tiering.asciidoc | 0 .../src/docs/asciidoc/developer/dev.git.asciidoc | 0 .../src/docs/asciidoc/developer/dev.guidelines.asciidoc | 0 .../src/docs/asciidoc/developer/dev.meetings.asciidoc | 0 .../src/docs/asciidoc/developer/module.api.asciidoc | 0 .../src/docs/asciidoc/developer/module.clustering.asciidoc | 0 .../src/docs/asciidoc/developer/module.core.asciidoc | 0 .../src/docs/asciidoc/developer/module.impl.asciidoc | 0 .../src/docs/asciidoc/developer/module.xa.asciidoc | 0 12 files changed, 0 insertions(+), 0 deletions(-) rename Home.asciidoc => docs/src/docs/asciidoc/developer/Home.asciidoc (100%) rename design.basics.asciidoc => docs/src/docs/asciidoc/developer/design.basics.asciidoc (100%) rename design.bootstrapping.asciidoc => docs/src/docs/asciidoc/developer/design.bootstrapping.asciidoc (100%) rename design.tiering.asciidoc => docs/src/docs/asciidoc/developer/design.tiering.asciidoc (100%) rename dev.git.asciidoc => docs/src/docs/asciidoc/developer/dev.git.asciidoc (100%) rename dev.guidelines.asciidoc => docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc (100%) rename dev.meetings.asciidoc => docs/src/docs/asciidoc/developer/dev.meetings.asciidoc (100%) rename module.api.asciidoc => docs/src/docs/asciidoc/developer/module.api.asciidoc (100%) rename module.clustering.asciidoc => docs/src/docs/asciidoc/developer/module.clustering.asciidoc (100%) rename module.core.asciidoc => docs/src/docs/asciidoc/developer/module.core.asciidoc (100%) rename module.impl.asciidoc => docs/src/docs/asciidoc/developer/module.impl.asciidoc (100%) rename module.xa.asciidoc => docs/src/docs/asciidoc/developer/module.xa.asciidoc (100%) diff --git a/Home.asciidoc b/docs/src/docs/asciidoc/developer/Home.asciidoc similarity index 100% rename from Home.asciidoc rename to docs/src/docs/asciidoc/developer/Home.asciidoc diff --git a/design.basics.asciidoc b/docs/src/docs/asciidoc/developer/design.basics.asciidoc similarity index 100% rename from design.basics.asciidoc rename to docs/src/docs/asciidoc/developer/design.basics.asciidoc diff --git a/design.bootstrapping.asciidoc b/docs/src/docs/asciidoc/developer/design.bootstrapping.asciidoc similarity index 100% rename from design.bootstrapping.asciidoc rename to docs/src/docs/asciidoc/developer/design.bootstrapping.asciidoc diff --git a/design.tiering.asciidoc b/docs/src/docs/asciidoc/developer/design.tiering.asciidoc similarity index 100% rename from design.tiering.asciidoc rename to docs/src/docs/asciidoc/developer/design.tiering.asciidoc diff --git a/dev.git.asciidoc b/docs/src/docs/asciidoc/developer/dev.git.asciidoc similarity index 100% rename from dev.git.asciidoc rename to docs/src/docs/asciidoc/developer/dev.git.asciidoc diff --git a/dev.guidelines.asciidoc b/docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc similarity index 100% rename from dev.guidelines.asciidoc rename to docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc diff --git a/dev.meetings.asciidoc b/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc similarity index 100% rename from dev.meetings.asciidoc rename to docs/src/docs/asciidoc/developer/dev.meetings.asciidoc diff --git a/module.api.asciidoc b/docs/src/docs/asciidoc/developer/module.api.asciidoc similarity index 100% rename from module.api.asciidoc rename to docs/src/docs/asciidoc/developer/module.api.asciidoc diff --git a/module.clustering.asciidoc b/docs/src/docs/asciidoc/developer/module.clustering.asciidoc similarity index 100% rename from module.clustering.asciidoc rename to docs/src/docs/asciidoc/developer/module.clustering.asciidoc diff --git a/module.core.asciidoc b/docs/src/docs/asciidoc/developer/module.core.asciidoc similarity index 100% rename from module.core.asciidoc rename to docs/src/docs/asciidoc/developer/module.core.asciidoc diff --git a/module.impl.asciidoc b/docs/src/docs/asciidoc/developer/module.impl.asciidoc similarity index 100% rename from module.impl.asciidoc rename to docs/src/docs/asciidoc/developer/module.impl.asciidoc diff --git a/module.xa.asciidoc b/docs/src/docs/asciidoc/developer/module.xa.asciidoc similarity index 100% rename from module.xa.asciidoc rename to docs/src/docs/asciidoc/developer/module.xa.asciidoc From 765f7104ab9a14c094305b43a74c73ccd3f31809 Mon Sep 17 00:00:00 2001 From: Chris Dennis Date: Tue, 16 Jan 2018 16:56:27 -0500 Subject: [PATCH 105/779] Convert to UNIX line endings --- .../asciidoc/developer/dev.meetings.asciidoc | 586 +++++++++--------- 1 file changed, 293 insertions(+), 293 deletions(-) diff --git a/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc b/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc index b5ad7ae8e4..4b681b799d 100644 --- a/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc +++ b/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc @@ -1,294 +1,294 @@ -= Meet up notes - -:toc: - -== Nov 20, 2014 - Hangout on Air - Rogue Edition - -Recording available https://www.youtube.com/watch?v=efCPffwBvaQ[here on YouTube] - -=== Agenda - - * putIfAbsent and CacheWriters - -== Nov 13, 2014 - Hangout on Air - -Next public meeting on https://plus.google.com/u/0/events/cv6v25r855jsn078tebkcbead2s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST - -=== Agenda - - * Stats - * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. - -== Nov 6, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=9CUnb5np5WM&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * Überjar! - * XML Configuration, - ** How should we parse it? - ** Alex's crazy extension idea for 107 idea - -== Oct 30, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * _Expiry_ to be the Store's concern, just as eviction is - ** Store doesn't know about the public event listeners though, uses internal private mechanism - ** An entry, being present but expired, is considered absent (i.e. a `Cache.putIfAbsent` would succeed). - ** `ValueHolder` probably can go now too - * `storeByValue`, see https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=737[here] - (and followed up on https://groups.google.com/forum/#!topic/ehcache-dev/RoY-P6Zm9tc[ML]) - * Some XML stuff as of https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=2001[here] - -== Oct 23, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * Exception hierarchy - ** Conclusion being we postpone deciding what we do, until we tackle the OSS Beta milestone. 107 dictates what we need to do now anways - * https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A#t=2387[Logging (levels, i18n, ...)] - ** `INFO`: Logs lifecycle stuff - ** `WARN`/`ERROR`: We don't log, but throw - ** `DEBUG`/`TRACE`: Regular ops stuff, including delegating to the `ResilienceStrategy` - -== Oct 16, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=HWi7H7glR_o&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * https://github.com/ehcache/ehcache3/pull/109[PR #109] on `ClassLoader` per `Cache` - ** Should it be a `Service` or do we want to keep it as in the PR? - ** Let's revisit this based on user sample code we plan on doing after the _107 Alpha_ - * Update the `README` to explain how to get to this though _sonatype_ - * _107 Alpha_ to be released as `3.0.0-Alpha` to central - -== Oct 9, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=P_P641-hkPs&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * +EhcacheManager+ & +Ehcache+ implicit contract nailed ? - * Lifecycle and state transitions - -== Oct 2, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=YgfsRhQPT7k&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * Project structure and especially the spi-tester sources - * What should a +Cache+ if everything gets veto'ed from being evicted? - * +CacheLoader+ & +CacheWriter+ only for implementing the Cache Through pattern? - ** Some background https://www.youtube.com/watch?v=a8LzwqZNfYE&list=UU43PVCp2j0b2og2DtxNOU1A[here in this previous meeting] - * Mocking time in tests - -== Sep 25, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=KaOagtwTHyw&index=2&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda (sorry, hadn't had time to review it yet) - - * Release https://github.com/ehcache/ehcache3/milestones[milestones]: - ** 107 Alpha - ** OSS Beta - * Recap on SPI Testing - * +CacheLoader+ & +CacheWriter+ lifecycle in +StandaloneCache+ vs. managed ones - * more TBD on the https://groups.google.com/forum/#!forum/ehcache-dev[Ehcache Developer Google Group] - -== Sep 18, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Moved to Cloudbees - -Our build infrastructure is now on Cloudbees here: -https://ehcache.ci.cloudbees.com - -Still need to publish +-SNAPSHOT+ to Sonatype though - -=== Git workflow - -We said we should not +git push --force+ to a branch that's currently under review (because of the PR associated); but rather closing the PR and creating a new one. - -WARNING: This decision has been invalidated since: it's okay to do it, but be vocal about it. One case where you just want to do it, is rebasing your branch should some other PR been merged in between. - -If you do changes based on the feedback from the PR, they probably should be a commit on their own atop of the other - -=== ConcurrentHashMap v8 port - -Is ported from jsr-166 cvs (revision information is recorded in the commit). Still uses +Unsafe+, but lets leave it like that for now (won't work on GAE for instance though). - -Need to have the CHMv8 tests not run everytime (at least not as they stand). - -+JSR166Wrapper+ contains all interfaces to please +javac+ - -Actually make use of CHMv8 in +OnHeapStore+ is still work that's still pending - -Also have a +Unsafe+ wrapper that adds the methods not present in 1.6 - -=== SPI Testing strategy (discussed https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A#t=1503[here]) - -Hung is currently working on a proposal, based on this here: https://gist.github.com/alexsnaps/f42557d008e2ed37f2b1 - -Acceptance criteria: - - * Not runtime dependency on a given testing framework (e.g. junit) - ** but can provide support for testing framework (e.g. to provide nice reporting) - * SPI tester should report a complete run, not stop on first failure it encounters - * A given SPI tester doesn't know about any given implementation, but implementations pull the SPI tester in - * Probably want to make the SPI testers available through maven using some qualifier (e.g. +core:SpiTesters+) - * The https://jcp.org/aboutJava/communityprocess/ec-public/TCK-docs/tsdg.pdf[Java™ Technology Test Suite -Development Guide 1.2] would probably contain some good input on writing actual SPI tests - * SPI tests are probably somewhat easier to write, given that we know where and how (UTSL!) a given SPI is actually used - -== Sep 11, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=PPiS6Y9Fzh4&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== CRUD operations - - - Let's implement the void ones (e.g. +remove(K): void+) for now, we may do more later. It's a cache, no real reason to wanting the old value ever... - -=== Resilience of +Ehcache+ - - - Stick to +ResilienceStrategy+ and have +Ehcache+ be resilient: - * No issues for on-heap +Store+ implementations - * Persistent ones will cope just fine (i.e. recover) - * Distributed ones will force some +.dealWithUnconsistentCache()+ cases - - Have a checked, do it all yourself, interface of some kind - - Postponing the work until all CRUD operations are implemented - -=== Travis CI - - - Lacks archiving, more work for us to do, but that's the work we'd want to be part of the _S_ in CIaaS - - Louis to take ownership and most probably move to cloudbees... - -=== Eclipse & Gradle - - - Hung to check the Gradle plugin - - Eclipse plugin in gradle build is on master now - -== Sep 4, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=iehQ9Wxx204&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ - -We want +CacheBuilder+ to create instances of types: - - . +Unmanaged(ShortLived)Cache+ - . +UnmanagedLongLivedCache+ - -While +CacheManagerBuilder+ create: - - . +(ShortLived)CacheManager+ - . +LongLivedCacheManager+ - -which manages +Cache+, i.e. not +Unmanaged+ ones. +LongLived+ exposes the methods to delete 'persistent' data (i.e. that outlives the life of the JVM). A +Cache+ is closed or destroyed through the +CacheManager+. - -=== Initial API issue break down - -Issues are now ordered on https://waffle.io/ehcache/ehcache3[waffle.io]: - - . 'API' labeled issues for public API require - .. JavaDoc - . 'API' labeled issues that are about SPI, require - .. JavaDoc - .. Tester of some kind, that - . 'Enhancement' labeled issues require - .. JavaDoc, as required - .. Unit tests - .. If ported from the 2.x line, best is to have decent coverage on the responsibilities the class will keep, prior to refactoring it; then refactor and add/tweak tests as required - -=== CIaaS - - . drone.io 'failed' - . codeship.io 'failed' - . travis-ci.org 'testing...' - . cloudbees.com 'todo' - -== Aug 28, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== +CacheManagerBuilder+ and +CacheBuilder+ - -Let's try to introduce a type hierarchy for both +Cache+ and +CacheManager+ that the builder would actually build, narrowing the type down à la Quartz 2.0 builders. - -[source,java] ----- -PersistentCache cache = newCacheBuilder() // <1> - .diskPersistent( - cfg // <3> - ) // <2> - .build(); // <4> ----- - -<1> static method that creates a builder: +Builder+ -<2> narrows to the builder's type down to +Builder+ -<3> +cfg+ actually defines the mode to use for persistence, eg: expect data on disk; expect none; use data if there; wipe data if there; wipe data on +Cache.close()+ -<4> actually builds the +PersistentCache+ - -Alex to make an actual proposal by next week. - -=== +CacheManager+-less +Cache+ instances - - - Keep these, where the user is actually responsible to provide services - - Only these +Cache+'s type would expose +.close()+ - - +CacheManager+ managed +Cache+ instances would be 'closed' through the +CacheManager+ - - To further lifecycle +PersistentCache+ instance, managed by a +CacheManager+, the latter could expose some method to retrieve +DiskPersisted+ (interface with minimal lifecycle methods) instances; e.g. - ----- -Iterable> it = cacheManager.getManaged(DiskPersisted.class); -it.next().value() // <1> - .deleteOnDiskFiles(); // <2> ----- - -<1> +DiskPersisted+ could expose methods around lifecycling the data on disk only. No +Cache+ methods -<2> Implies +Cache.close()+, i.e. clear all 'VM transient' data and delete data from disk. - -== Aug 21, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] - -=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ - -==== +Cache+ backed by a +Store>+ - - . Rename +Element+ - . Try +Store>+ for now - -==== Roles - -How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? - - . +Cache+ Roles - .. Expiry - .. Public EntryListeners - .. Cache lifecycle - .. CacheLoaders - .. CacheWriters - . +Store+ Roles - .. Store by Value vs. Ref. - .. Eviction & (private) EvictionListeners - -=== Other items - -==== Integrate 107 TCK - -Created issue #21 - -==== What's with the sizeof modules ? - - . *Hibernate* to be integrated within the h2lc module there - . *Groovy*, either: - .. @candrews takes ownership, or += Meet up notes + +:toc: + +== Nov 20, 2014 - Hangout on Air - Rogue Edition + +Recording available https://www.youtube.com/watch?v=efCPffwBvaQ[here on YouTube] + +=== Agenda + + * putIfAbsent and CacheWriters + +== Nov 13, 2014 - Hangout on Air + +Next public meeting on https://plus.google.com/u/0/events/cv6v25r855jsn078tebkcbead2s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST + +=== Agenda + + * Stats + * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. + +== Nov 6, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=9CUnb5np5WM&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * Überjar! + * XML Configuration, + ** How should we parse it? + ** Alex's crazy extension idea for 107 idea + +== Oct 30, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * _Expiry_ to be the Store's concern, just as eviction is + ** Store doesn't know about the public event listeners though, uses internal private mechanism + ** An entry, being present but expired, is considered absent (i.e. a `Cache.putIfAbsent` would succeed). + ** `ValueHolder` probably can go now too + * `storeByValue`, see https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=737[here] + (and followed up on https://groups.google.com/forum/#!topic/ehcache-dev/RoY-P6Zm9tc[ML]) + * Some XML stuff as of https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=2001[here] + +== Oct 23, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * Exception hierarchy + ** Conclusion being we postpone deciding what we do, until we tackle the OSS Beta milestone. 107 dictates what we need to do now anways + * https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A#t=2387[Logging (levels, i18n, ...)] + ** `INFO`: Logs lifecycle stuff + ** `WARN`/`ERROR`: We don't log, but throw + ** `DEBUG`/`TRACE`: Regular ops stuff, including delegating to the `ResilienceStrategy` + +== Oct 16, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=HWi7H7glR_o&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * https://github.com/ehcache/ehcache3/pull/109[PR #109] on `ClassLoader` per `Cache` + ** Should it be a `Service` or do we want to keep it as in the PR? + ** Let's revisit this based on user sample code we plan on doing after the _107 Alpha_ + * Update the `README` to explain how to get to this though _sonatype_ + * _107 Alpha_ to be released as `3.0.0-Alpha` to central + +== Oct 9, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=P_P641-hkPs&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * +EhcacheManager+ & +Ehcache+ implicit contract nailed ? + * Lifecycle and state transitions + +== Oct 2, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=YgfsRhQPT7k&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda + + * Project structure and especially the spi-tester sources + * What should a +Cache+ if everything gets veto'ed from being evicted? + * +CacheLoader+ & +CacheWriter+ only for implementing the Cache Through pattern? + ** Some background https://www.youtube.com/watch?v=a8LzwqZNfYE&list=UU43PVCp2j0b2og2DtxNOU1A[here in this previous meeting] + * Mocking time in tests + +== Sep 25, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=KaOagtwTHyw&index=2&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Agenda (sorry, hadn't had time to review it yet) + + * Release https://github.com/ehcache/ehcache3/milestones[milestones]: + ** 107 Alpha + ** OSS Beta + * Recap on SPI Testing + * +CacheLoader+ & +CacheWriter+ lifecycle in +StandaloneCache+ vs. managed ones + * more TBD on the https://groups.google.com/forum/#!forum/ehcache-dev[Ehcache Developer Google Group] + +== Sep 18, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Moved to Cloudbees + +Our build infrastructure is now on Cloudbees here: +https://ehcache.ci.cloudbees.com + +Still need to publish +-SNAPSHOT+ to Sonatype though + +=== Git workflow + +We said we should not +git push --force+ to a branch that's currently under review (because of the PR associated); but rather closing the PR and creating a new one. + +WARNING: This decision has been invalidated since: it's okay to do it, but be vocal about it. One case where you just want to do it, is rebasing your branch should some other PR been merged in between. + +If you do changes based on the feedback from the PR, they probably should be a commit on their own atop of the other + +=== ConcurrentHashMap v8 port + +Is ported from jsr-166 cvs (revision information is recorded in the commit). Still uses +Unsafe+, but lets leave it like that for now (won't work on GAE for instance though). + +Need to have the CHMv8 tests not run everytime (at least not as they stand). + ++JSR166Wrapper+ contains all interfaces to please +javac+ + +Actually make use of CHMv8 in +OnHeapStore+ is still work that's still pending + +Also have a +Unsafe+ wrapper that adds the methods not present in 1.6 + +=== SPI Testing strategy (discussed https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A#t=1503[here]) + +Hung is currently working on a proposal, based on this here: https://gist.github.com/alexsnaps/f42557d008e2ed37f2b1 + +Acceptance criteria: + + * Not runtime dependency on a given testing framework (e.g. junit) + ** but can provide support for testing framework (e.g. to provide nice reporting) + * SPI tester should report a complete run, not stop on first failure it encounters + * A given SPI tester doesn't know about any given implementation, but implementations pull the SPI tester in + * Probably want to make the SPI testers available through maven using some qualifier (e.g. +core:SpiTesters+) + * The https://jcp.org/aboutJava/communityprocess/ec-public/TCK-docs/tsdg.pdf[Java™ Technology Test Suite +Development Guide 1.2] would probably contain some good input on writing actual SPI tests + * SPI tests are probably somewhat easier to write, given that we know where and how (UTSL!) a given SPI is actually used + +== Sep 11, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=PPiS6Y9Fzh4&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== CRUD operations + + - Let's implement the void ones (e.g. +remove(K): void+) for now, we may do more later. It's a cache, no real reason to wanting the old value ever... + +=== Resilience of +Ehcache+ + + - Stick to +ResilienceStrategy+ and have +Ehcache+ be resilient: + * No issues for on-heap +Store+ implementations + * Persistent ones will cope just fine (i.e. recover) + * Distributed ones will force some +.dealWithUnconsistentCache()+ cases + - Have a checked, do it all yourself, interface of some kind + - Postponing the work until all CRUD operations are implemented + +=== Travis CI + + - Lacks archiving, more work for us to do, but that's the work we'd want to be part of the _S_ in CIaaS + - Louis to take ownership and most probably move to cloudbees... + +=== Eclipse & Gradle + + - Hung to check the Gradle plugin + - Eclipse plugin in gradle build is on master now + +== Sep 4, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=iehQ9Wxx204&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ + +We want +CacheBuilder+ to create instances of types: + + . +Unmanaged(ShortLived)Cache+ + . +UnmanagedLongLivedCache+ + +While +CacheManagerBuilder+ create: + + . +(ShortLived)CacheManager+ + . +LongLivedCacheManager+ + +which manages +Cache+, i.e. not +Unmanaged+ ones. +LongLived+ exposes the methods to delete 'persistent' data (i.e. that outlives the life of the JVM). A +Cache+ is closed or destroyed through the +CacheManager+. + +=== Initial API issue break down + +Issues are now ordered on https://waffle.io/ehcache/ehcache3[waffle.io]: + + . 'API' labeled issues for public API require + .. JavaDoc + . 'API' labeled issues that are about SPI, require + .. JavaDoc + .. Tester of some kind, that + . 'Enhancement' labeled issues require + .. JavaDoc, as required + .. Unit tests + .. If ported from the 2.x line, best is to have decent coverage on the responsibilities the class will keep, prior to refactoring it; then refactor and add/tweak tests as required + +=== CIaaS + + . drone.io 'failed' + . codeship.io 'failed' + . travis-ci.org 'testing...' + . cloudbees.com 'todo' + +== Aug 28, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] + +=== +CacheManagerBuilder+ and +CacheBuilder+ + +Let's try to introduce a type hierarchy for both +Cache+ and +CacheManager+ that the builder would actually build, narrowing the type down à la Quartz 2.0 builders. + +[source,java] +---- +PersistentCache cache = newCacheBuilder() // <1> + .diskPersistent( + cfg // <3> + ) // <2> + .build(); // <4> +---- + +<1> static method that creates a builder: +Builder+ +<2> narrows to the builder's type down to +Builder+ +<3> +cfg+ actually defines the mode to use for persistence, eg: expect data on disk; expect none; use data if there; wipe data if there; wipe data on +Cache.close()+ +<4> actually builds the +PersistentCache+ + +Alex to make an actual proposal by next week. + +=== +CacheManager+-less +Cache+ instances + + - Keep these, where the user is actually responsible to provide services + - Only these +Cache+'s type would expose +.close()+ + - +CacheManager+ managed +Cache+ instances would be 'closed' through the +CacheManager+ + - To further lifecycle +PersistentCache+ instance, managed by a +CacheManager+, the latter could expose some method to retrieve +DiskPersisted+ (interface with minimal lifecycle methods) instances; e.g. + +---- +Iterable> it = cacheManager.getManaged(DiskPersisted.class); +it.next().value() // <1> + .deleteOnDiskFiles(); // <2> +---- + +<1> +DiskPersisted+ could expose methods around lifecycling the data on disk only. No +Cache+ methods +<2> Implies +Cache.close()+, i.e. clear all 'VM transient' data and delete data from disk. + +== Aug 21, 2014 - Hangout on Air + +Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] + +=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ + +==== +Cache+ backed by a +Store>+ + + . Rename +Element+ + . Try +Store>+ for now + +==== Roles + +How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? + + . +Cache+ Roles + .. Expiry + .. Public EntryListeners + .. Cache lifecycle + .. CacheLoaders + .. CacheWriters + . +Store+ Roles + .. Store by Value vs. Ref. + .. Eviction & (private) EvictionListeners + +=== Other items + +==== Integrate 107 TCK + +Created issue #21 + +==== What's with the sizeof modules ? + + . *Hibernate* to be integrated within the h2lc module there + . *Groovy*, either: + .. @candrews takes ownership, or .. we find someone within TC/SAG to do so (unidentified yet though) \ No newline at end of file From a8e5ce5669b720dc53952a44e79ba00eeac15d00 Mon Sep 17 00:00:00 2001 From: Chris Dennis Date: Wed, 17 Jan 2018 10:56:11 -0500 Subject: [PATCH 106/779] Remove dev process related documents --- .../src/docs/asciidoc/developer/Home.asciidoc | 60 ---- .../docs/asciidoc/developer/dev.git.asciidoc | 124 -------- .../developer/dev.guidelines.asciidoc | 112 ------- .../asciidoc/developer/dev.meetings.asciidoc | 294 ------------------ 4 files changed, 590 deletions(-) delete mode 100644 docs/src/docs/asciidoc/developer/Home.asciidoc delete mode 100644 docs/src/docs/asciidoc/developer/dev.git.asciidoc delete mode 100644 docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc delete mode 100644 docs/src/docs/asciidoc/developer/dev.meetings.asciidoc diff --git a/docs/src/docs/asciidoc/developer/Home.asciidoc b/docs/src/docs/asciidoc/developer/Home.asciidoc deleted file mode 100644 index 248b298c02..0000000000 --- a/docs/src/docs/asciidoc/developer/Home.asciidoc +++ /dev/null @@ -1,60 +0,0 @@ -= Ehcache 3 developer wiki - -:toc: - -== Developer, be welcome! - -This wiki contains all design documents and other related material to doing development on Ehcache, not _using_ Ehcache! If you are a developer that wants to get involved in developing new features, fixing bugs, extend the existing or implement a new module based on the Ehcache3 SPIs, this is the place you've been looking for. Be welcome! - -== How to contribute? - -=== Process - -On paper (or on this screen), it's pretty straight forward: - - . Join the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] and say hello! Or join us on irc #ehcache on freenode - . Check the https://github.com/ehcache/ehcache3/issues[issues] and verify what you want isn't yet planned or could even already being worked on by someone; We're also using a board on https://waffle.io/ehcache/ehcache3[waffle.io], where work for the current milestone is prioritized; - . If the task exists already and isn't assigned: drop us an email on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list] about it and we'll make sure we help you getting started and we'll assign the task/issue to you; - . If nothing matches in the existing issue list, create a bug as such; or, if we're talking about a larger task or feature, https://groups.google.com/forum/#!forum/ehcache-dev[drop us a message] first, and we'll see how to tackle it; - . https://github.com/ehcache/ehcache3/fork[Fork] the project to your own repository and get started (you probably want to work on a dedicated branch); - . Rebase your fork and do a pull request. We'll use that to code review it (see link:dev.git[git usage page] as well as the link:dev.guidelines[developer guidelines]) - . Be rich and famous! - -Now, the doing the work part might be a little more challenging, and we don't provide any guarantees as to becoming rich... but you'll be famous to us! - -=== Contributor agreement - -In order to accept any contribution, we will need you to fill out and mail https://confluence.terracotta.org/download/attachments/27918462/Terracotta%20Individual%20Contributor%20Agreement%20v3.pdf?version=1&modificationDate=1393442245216&api=v2[the Individual Contributor Agreement] at contributors@terracotta.org. - -=== Code layout - -The code core of Ehcache is split in three core modules: - - . the link:module.api[API module], which contains mainly interfaces. They are the core API to Ehcache (e.g. +Cache+, +CacheManager+) that users depend on. It also contains the entry points in terms of SPI (e.g. +Service+, +Store+, +AuthoritativeTier+ & +CachingTier+), that are used by other modules that in turn provide their implementations; - . the link:module.core[Core module], that is composed of the plumbery that wires the API used by users with the SPI implementations present in packaged modules; and - . the link:module.impl[Implementation module], containing the default implementation of +Cache+ and +CacheManager+, as well as implementations of core SPIs, such as +HeapResource+ that lets you create on-heap +Cache+ and +CachingTier+ instances. - -== Fundamental concepts - -=== Modular approach - -==== Services - -A `CacheManager` manages `Cache` instances, but also `Service` instances that can be used by either `Cache` or other `Service` instances. An example of `Service` being the `org.ehcache.spi.cache.Store.Provider`, it's the `Service` the `CacheManager` will use to create the `Store` instance underlying your `Cache`. - -`Service` are created by using the Java's https://docs.oracle.com/javase/6/docs/api/java/util/ServiceLoader.html[`java.util.ServiceLoader` service-provider loading facility]. It is used to locate all `org.ehcache.spi.service.ServiceFactory` implementations on the classpath. These are in turn used to create `Service` instances. Each `CacheManager` uses its own `org.ehcache.spi.ServiceLocator` facility to locate `Service` instances, which it then in turn life cycles. - -`Service` instances are configured by their own respective `ServiceConfiguration` at `Service.start()` invocation time. `CacheManager` and its `Service` instances can then use these services. In the case of the `org.ehcache.spi.cache.Store.Provider` instance, it is being used by the `CacheManager` to create a `Store` to back a `Cache`. Being a direct dependency of `Ehcache`, that `Service` interface is part of the core SPI. It defines a `createStore()` method that will be invoked by the `CacheManager` at `Cache` creation time. The `Store.Provider` implementation can introspect not only the `Store.Configuration` passed, but also all `ServiceConfiguration` instances associated with the `Cache` being created in order to decide what `Store` should be created (note: currently it only creates `OnHeapStore`, as this is the only topology supported... more to come). - -=== Configuration - -+org.ehcache.config.CacheConfiguration+, +org.ehcache.spi.service.ServiceConfiguration+, +org.ehcache.config.xml.XmlConfigurationParser+ - -NOTE: For more information on how the configuration is parsed, resolved and services are then bootstrapped, please read the link:design.bootstrapping#configuration[Bootstrapping design doc]. - -== How to extend? - -=== SPIs -+org.ehcache.spi.service+, +org.ehcache.spi.cache+ - -=== Extension points diff --git a/docs/src/docs/asciidoc/developer/dev.git.asciidoc b/docs/src/docs/asciidoc/developer/dev.git.asciidoc deleted file mode 100644 index 9c4de849ea..0000000000 --- a/docs/src/docs/asciidoc/developer/dev.git.asciidoc +++ /dev/null @@ -1,124 +0,0 @@ -= Git usage - -:toc: - -== Fork on me GitHub! - - . If you don't have an account on GitHub, create one now and fork your own copy of Ehcache to your account; - . +git clone+ that fork to your computer, by default that remote's name will be +origin+; - . +git remote add ehcache \git@github.com:ehcache/ehcache3.git+; - . You'll have to keep your +master+ branch in sync (both on your computer and the one on your GitHub account) with the one from +ehcache+ (see §2.1.1 below) - . +git checkout -b issue-''+, where '' of +issue-''+ is the number of the issue you will work on (command that both creates the branch and switches to it). Commit as you see fit on each of these branches (we recommend small commits often; - . You can have as many parallel branches as issues you might be working on; - . Once done, you may want to re-organize you commits by doing a +git rebase -i HEAD~''+ where '' is how many commits you'd be ahead when done; - -== Initiate a pull request - -Now that Ehcache 3.0 has releases out there, bug fixes may apply to both the release branches and/or master. - -Given this, the development team has decided on the following development strategy. - -=== Feature development - -This happens on master only, using a rebase model described below. -We strive on keeping a clean and very linear history for feature development. - - . Right before sharing your changes, make sure your +issue-''+ branch is based of +ehcache/master+'s current +HEAD+, e.g.: - - git pull ehcache - git checkout master - git rebase ehcache/master - git checkout issue- - git rebase master - - . Finally, +git push origin issue-''+ to push your branch to your account; - . You then need to create a pull request, using the UI on GitHub; - . Someone from our team is then going to review it. - -=== Bug fixing - -If what you are working on is a bug fix, we want to be able to merge the fix commits on all impacted release branches and master. -In order to do that, we use a strategy inspired from http://wiki.monotone.ca/DaggyFixes/[DaggyFixes]. - -==== Picking the base commit - -The base commit for your fix must be at the earliest a parent of all branches it will need to be merged to, it can also be at the latest the commit that introduced the bug as describe in DaggyFixes. - -Such a commit can be found using the following (presented here as an alias definiton): - -`alias.oldest-ancestor=!bash -c 'diff --old-line-format='' --new-line-format='' <(git rev-list --first-parent ${1:-master}) <(git rev-list --first-parent ${2:-HEAD}) | head -1' -` - -==== Developing the fix - -That's you doing the work - nothing specific there but the usual commit recommendations. - -==== Pull requests - -As the fix developer, integrating the fix in the different target branches is your responsibility. -So unless your fix can directly be merged in the different branches, you will have to merge the branches into the fix to resolve conflicts. - -The idea behind this strategy is that the commits that were created on branch `issue-1048` in this example are now part of the history of the different releases and tracking which fix exists where is vastly simplified over the different strategies that are `cherry-pick` based. - -===== Create the pull requests - -The easiest way is to use GitHub's *compare across forks* feature when creating the pull request. Use the Ehcache repo as the *base fork* and your own repo as the *head fork*, then pick _your_ branch containing the fix as the *compare* branch. - -Now you just need to select the Ehcache branches you want to target (every necessary `release/3.x` ones, plus `master`) as the *base* branch. GitHub will tell you if these branches can be automatically merged. If they can, just create the pull requests as-is. If all branches can be automatically merged, you're done after you created all the pull requests. - -If GitHub reports some branches as having conflicts, you have to read on to create special pull requests containing the merge work. - -===== When manually merging is necessary - -I will use the `release/3.0` branch as the target in the example below and assume your fix branch is `issue-1048`. These names should be replaced by the one applicable to your context. - - . On your fix branch - - git checkout -b issue-1048-release-3.0 - git merge release/3.0 - // Resolve conflicts - git merge --continue - - . Open a pull request from that, making sure it is against `release/3.0` - . Repeat for each target branch, including `master` - -== Have it reviewed - - . The pull request will be reviewed for: - .. 'Correctness': the pull request should wholly and only be about the related issue; - .. 'Style': which needs to match the style of the project; - .. 'Testing': all changes need to have appropriate test coverage, without breaking existing tests. - .. You can look up link:dev.guidelines[general developer guidelines] as well - . There could be some back and forth between you and the 'reviewer' in that process. Keep in mind that during that time +ehcache/master+ may drift, you'd then need to follow §2.1.1 above, but finally `git push --force origin issue-` to keep the pull request updated. - -== Merging a pull request - -If you are a reviewer (i.e. have commit rights to the ehcache/ehcache3 repo), the way we are looking at this is: - - - When working on an issue, you are the author of a contribution, but you don't have commit rights on the main repo; - - When you are code reviewing someone else's contribution, you do have commit rights. - -As a reviewer, you are expected to verify the following: - - . Branch to be merged is up-to-date with master - . Branch to be merged is pristine - it has not been used in a previous pull request - -As such, every contribution gets reviewed by a committer, that effectively commits the changes to Ehcache's repository for the author. As a reviewer/committer, you do the following: - - . +git remote add '' '+ the contributor's ehcache3 repository; - . +git fetch '' issue-''+; - . +git checkout -b issue-'' ''/issue-''+; - . 'do the actual review'; - --- THEN -- -[start=5] - . Use the GitHub UI to do the merge - --- OR -- -[start=5] - . +git checkout master+; - . +git merge --no-ff issue-''+; - - If this results in something else than having to edit a commit comment - something's wrong, you need to _STOP_ - . +git push ehcache master+ to the main repository. - -Both of these methods will create a merge commit, indicating who accepted the change in the main code line. It will also make sure the resulting history is linear equivalent. -Always use a reference to the issue id in the commit message of the merge. diff --git a/docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc b/docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc deleted file mode 100644 index f59f36615a..0000000000 --- a/docs/src/docs/asciidoc/developer/dev.guidelines.asciidoc +++ /dev/null @@ -1,112 +0,0 @@ -= Developer guidelines - -:toc: - -These are some things to consider when you add code to Ehcache, but certainly when you review a PR! - -== General guidelines - -Whenever you start working on an issue, you probably want to consider some, if not all, of the items below: - -=== API changes - -If you need to change the public API (this includes additions), you probably want to start with that first. An easy way to go about that, is to add or modify `GettingStarted` documentation to concretely expose how the API would be affected. You can do this on your branch, as a first commit, and already share it for review with a larger audience, e.g. on the mailing list or through a preliminary pull request. - -=== Design - -Whether API is modified or not, you'll want to consider how you plan to go about implementing it all. There are a couple of specificities of the Ehcache internals that would need to be accounted for: - - . *`Service` additions or modifications*: this is mainly about http://en.wikipedia.org/wiki/Inversion_of_control[IoC] and http://en.wikipedia.org/wiki/Liskov_substitution_principle[LSP], we want subsystems of your feature to be both injected and abstracted away behind an interface. This allows the actual implementation to be easily replaced with another. We also try to reuse existing `Service` definitions as much as possible. So don't hesitate to slightly tweak an existing one, rather than introducing a new one. - . *Lifecycle*: You'll want to assess how Ehcache's life cycling may affect your change (if at all). If anything requires any special life cycling (e.g. `PersistentCacheManager` services), you will have to account for this. - . *Failure*: Most things eventually do go wrong. Whether it's IO, some user provided implementation throwing, the actual `Store` being unaccessible... things just go wrong. Ehcache tries to never do any harm to the user's application. As such your change should account for failure scenarios and possibly delegate to the `ResilienceStrategy` to enable users to deal with such scenarios sensibly. - -=== Last touches - -Once your change is implemented (see coding guidelines below), you will want to make sure that: - - . You added adequate (but not excessive) logging; - . Configuration is complete: - .. XML configuration was added, but that should never drive the actual configuration concerns; - .. XML Templating is correctly supported. - -== Coding guidelines - -=== Commit comment - -* Make sure the issue the commit relates is referenced in the commit comment. -** If your commit closes an issue, think about using the https://help.github.com/articles/closing-issues-via-commit-messages/[GitHub options] for automatically closing the issue when the commit reaches master. -* For your commit comment, you are strongly encouraged to follow the recommendations found http://chris.beams.io/posts/git-commit/#seven-rules[here] -** Feel free also to use emoji - current ones used are based on https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages[the following] - -Here is an example: - ----- -:bug: Fix #1354 JSR-107 support in ClusteredStore stats - -Some context registrations are required to get the proper statistics -discovered by the JCache stats MBean ----- - -=== Formatting - -See what's there for now... Ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. We'll export settings for majors IDEs here asap. - -=== Unit testing - -All changes need to come with appropriate test coverage. - -==== Adding code - -All this new code you add should have test coverage. - -==== Breaking existing tests - -Should you break an existing test, take great care before touching the test code to "fix it". While it could definitively be that the test is wrong, it may be correct as well. Always assume the latter is true first. If in doubt, again, ping us on the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. - -Changing an existing test for it to pass, because of you recent changes, should really be the last resort. Other than for compilation obviously, or adding mocks and the like. - -==== SPI tests - -We have an SPI module that covers testing functionality that needs to be provided by a given SPI, e.g. `org.ehcache.spi.cache.Store`. - -WARNING: work in progress - -=== Logging - -We use `slf4j` for all our logging here... - -==== Log levels - -What level should be used for logging should be dependent on whether you log for the user's benefit (e.g. lifecycle), debugging purposes (a standard `Cache.get(K): V` path). But we don't log `WARN` or `ERROR`. - -===== At `INFO` level - -We log things about lifecycle: - - * Bootstrapping `CacheManager`, - * Adding, removing `Cache` to CacheManager - * ... - -Basically everything that would be informational to the end-user. - -===== Level `DEBUG` and below - -Helps us trace stuff, when some weird scenario is being debugged. - - * Delegating to `CacheLoader`, - * Delegating to `ResilienceStrategy`, - * `Store` internals... - -===== Levels `WARN` & `ERROR` - -Nothing really, if that level is required, we would rather want to throw! - -=== Javadoc - -==== Public types - -Needs to be fully Javadoc'ed - -==== Internal concrete classes - -Require at least class-level Javadoc. But we value clear method, arguments and variable names above all here. \ No newline at end of file diff --git a/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc b/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc deleted file mode 100644 index 4b681b799d..0000000000 --- a/docs/src/docs/asciidoc/developer/dev.meetings.asciidoc +++ /dev/null @@ -1,294 +0,0 @@ -= Meet up notes - -:toc: - -== Nov 20, 2014 - Hangout on Air - Rogue Edition - -Recording available https://www.youtube.com/watch?v=efCPffwBvaQ[here on YouTube] - -=== Agenda - - * putIfAbsent and CacheWriters - -== Nov 13, 2014 - Hangout on Air - -Next public meeting on https://plus.google.com/u/0/events/cv6v25r855jsn078tebkcbead2s[G+ Hangout on Air] at 11:30pm IST / 8pm CET / 2pm EST / 11am PST - -=== Agenda - - * Stats - * send ideas to the https://groups.google.com/forum/#!forum/ehcache-dev[developer mailing list]. - -== Nov 6, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=9CUnb5np5WM&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * Überjar! - * XML Configuration, - ** How should we parse it? - ** Alex's crazy extension idea for 107 idea - -== Oct 30, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * _Expiry_ to be the Store's concern, just as eviction is - ** Store doesn't know about the public event listeners though, uses internal private mechanism - ** An entry, being present but expired, is considered absent (i.e. a `Cache.putIfAbsent` would succeed). - ** `ValueHolder` probably can go now too - * `storeByValue`, see https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=737[here] - (and followed up on https://groups.google.com/forum/#!topic/ehcache-dev/RoY-P6Zm9tc[ML]) - * Some XML stuff as of https://www.youtube.com/watch?v=MvL7NkF0Qxk&list=UU43PVCp2j0b2og2DtxNOU1A#t=2001[here] - -== Oct 23, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * Exception hierarchy - ** Conclusion being we postpone deciding what we do, until we tackle the OSS Beta milestone. 107 dictates what we need to do now anways - * https://www.youtube.com/watch?v=Rf86ZxtYXaY&list=UU43PVCp2j0b2og2DtxNOU1A#t=2387[Logging (levels, i18n, ...)] - ** `INFO`: Logs lifecycle stuff - ** `WARN`/`ERROR`: We don't log, but throw - ** `DEBUG`/`TRACE`: Regular ops stuff, including delegating to the `ResilienceStrategy` - -== Oct 16, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=HWi7H7glR_o&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * https://github.com/ehcache/ehcache3/pull/109[PR #109] on `ClassLoader` per `Cache` - ** Should it be a `Service` or do we want to keep it as in the PR? - ** Let's revisit this based on user sample code we plan on doing after the _107 Alpha_ - * Update the `README` to explain how to get to this though _sonatype_ - * _107 Alpha_ to be released as `3.0.0-Alpha` to central - -== Oct 9, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=P_P641-hkPs&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * +EhcacheManager+ & +Ehcache+ implicit contract nailed ? - * Lifecycle and state transitions - -== Oct 2, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=YgfsRhQPT7k&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda - - * Project structure and especially the spi-tester sources - * What should a +Cache+ if everything gets veto'ed from being evicted? - * +CacheLoader+ & +CacheWriter+ only for implementing the Cache Through pattern? - ** Some background https://www.youtube.com/watch?v=a8LzwqZNfYE&list=UU43PVCp2j0b2og2DtxNOU1A[here in this previous meeting] - * Mocking time in tests - -== Sep 25, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=KaOagtwTHyw&index=2&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Agenda (sorry, hadn't had time to review it yet) - - * Release https://github.com/ehcache/ehcache3/milestones[milestones]: - ** 107 Alpha - ** OSS Beta - * Recap on SPI Testing - * +CacheLoader+ & +CacheWriter+ lifecycle in +StandaloneCache+ vs. managed ones - * more TBD on the https://groups.google.com/forum/#!forum/ehcache-dev[Ehcache Developer Google Group] - -== Sep 18, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Moved to Cloudbees - -Our build infrastructure is now on Cloudbees here: -https://ehcache.ci.cloudbees.com - -Still need to publish +-SNAPSHOT+ to Sonatype though - -=== Git workflow - -We said we should not +git push --force+ to a branch that's currently under review (because of the PR associated); but rather closing the PR and creating a new one. - -WARNING: This decision has been invalidated since: it's okay to do it, but be vocal about it. One case where you just want to do it, is rebasing your branch should some other PR been merged in between. - -If you do changes based on the feedback from the PR, they probably should be a commit on their own atop of the other - -=== ConcurrentHashMap v8 port - -Is ported from jsr-166 cvs (revision information is recorded in the commit). Still uses +Unsafe+, but lets leave it like that for now (won't work on GAE for instance though). - -Need to have the CHMv8 tests not run everytime (at least not as they stand). - -+JSR166Wrapper+ contains all interfaces to please +javac+ - -Actually make use of CHMv8 in +OnHeapStore+ is still work that's still pending - -Also have a +Unsafe+ wrapper that adds the methods not present in 1.6 - -=== SPI Testing strategy (discussed https://www.youtube.com/watch?v=51PLWgRRLaE&list=UU43PVCp2j0b2og2DtxNOU1A#t=1503[here]) - -Hung is currently working on a proposal, based on this here: https://gist.github.com/alexsnaps/f42557d008e2ed37f2b1 - -Acceptance criteria: - - * Not runtime dependency on a given testing framework (e.g. junit) - ** but can provide support for testing framework (e.g. to provide nice reporting) - * SPI tester should report a complete run, not stop on first failure it encounters - * A given SPI tester doesn't know about any given implementation, but implementations pull the SPI tester in - * Probably want to make the SPI testers available through maven using some qualifier (e.g. +core:SpiTesters+) - * The https://jcp.org/aboutJava/communityprocess/ec-public/TCK-docs/tsdg.pdf[Java™ Technology Test Suite -Development Guide 1.2] would probably contain some good input on writing actual SPI tests - * SPI tests are probably somewhat easier to write, given that we know where and how (UTSL!) a given SPI is actually used - -== Sep 11, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=PPiS6Y9Fzh4&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== CRUD operations - - - Let's implement the void ones (e.g. +remove(K): void+) for now, we may do more later. It's a cache, no real reason to wanting the old value ever... - -=== Resilience of +Ehcache+ - - - Stick to +ResilienceStrategy+ and have +Ehcache+ be resilient: - * No issues for on-heap +Store+ implementations - * Persistent ones will cope just fine (i.e. recover) - * Distributed ones will force some +.dealWithUnconsistentCache()+ cases - - Have a checked, do it all yourself, interface of some kind - - Postponing the work until all CRUD operations are implemented - -=== Travis CI - - - Lacks archiving, more work for us to do, but that's the work we'd want to be part of the _S_ in CIaaS - - Louis to take ownership and most probably move to cloudbees... - -=== Eclipse & Gradle - - - Hung to check the Gradle plugin - - Eclipse plugin in gradle build is on master now - -== Sep 4, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=iehQ9Wxx204&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== Review some proposal on +CacheManager+ and +Cache+ subtyping & their matching +Builder+ - -We want +CacheBuilder+ to create instances of types: - - . +Unmanaged(ShortLived)Cache+ - . +UnmanagedLongLivedCache+ - -While +CacheManagerBuilder+ create: - - . +(ShortLived)CacheManager+ - . +LongLivedCacheManager+ - -which manages +Cache+, i.e. not +Unmanaged+ ones. +LongLived+ exposes the methods to delete 'persistent' data (i.e. that outlives the life of the JVM). A +Cache+ is closed or destroyed through the +CacheManager+. - -=== Initial API issue break down - -Issues are now ordered on https://waffle.io/ehcache/ehcache3[waffle.io]: - - . 'API' labeled issues for public API require - .. JavaDoc - . 'API' labeled issues that are about SPI, require - .. JavaDoc - .. Tester of some kind, that - . 'Enhancement' labeled issues require - .. JavaDoc, as required - .. Unit tests - .. If ported from the 2.x line, best is to have decent coverage on the responsibilities the class will keep, prior to refactoring it; then refactor and add/tweak tests as required - -=== CIaaS - - . drone.io 'failed' - . codeship.io 'failed' - . travis-ci.org 'testing...' - . cloudbees.com 'todo' - -== Aug 28, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=_S2cn4nf0_U&list=UU43PVCp2j0b2og2DtxNOU1A[here on YouTube] - -=== +CacheManagerBuilder+ and +CacheBuilder+ - -Let's try to introduce a type hierarchy for both +Cache+ and +CacheManager+ that the builder would actually build, narrowing the type down à la Quartz 2.0 builders. - -[source,java] ----- -PersistentCache cache = newCacheBuilder() // <1> - .diskPersistent( - cfg // <3> - ) // <2> - .build(); // <4> ----- - -<1> static method that creates a builder: +Builder+ -<2> narrows to the builder's type down to +Builder+ -<3> +cfg+ actually defines the mode to use for persistence, eg: expect data on disk; expect none; use data if there; wipe data if there; wipe data on +Cache.close()+ -<4> actually builds the +PersistentCache+ - -Alex to make an actual proposal by next week. - -=== +CacheManager+-less +Cache+ instances - - - Keep these, where the user is actually responsible to provide services - - Only these +Cache+'s type would expose +.close()+ - - +CacheManager+ managed +Cache+ instances would be 'closed' through the +CacheManager+ - - To further lifecycle +PersistentCache+ instance, managed by a +CacheManager+, the latter could expose some method to retrieve +DiskPersisted+ (interface with minimal lifecycle methods) instances; e.g. - ----- -Iterable> it = cacheManager.getManaged(DiskPersisted.class); -it.next().value() // <1> - .deleteOnDiskFiles(); // <2> ----- - -<1> +DiskPersisted+ could expose methods around lifecycling the data on disk only. No +Cache+ methods -<2> Implies +Cache.close()+, i.e. clear all 'VM transient' data and delete data from disk. - -== Aug 21, 2014 - Hangout on Air - -Recording available https://www.youtube.com/watch?v=rUI4SsPRGQ4[here on YouTube] - -=== +org.ehcache.Cache+ vs. +org.ehcache.spi.cache.Store+ - -==== +Cache+ backed by a +Store>+ - - . Rename +Element+ - . Try +Store>+ for now - -==== Roles - -How much can be solved by having the +Cache+ call into some +Store.process(K, EntryProcessor): T+ equivalent? - - . +Cache+ Roles - .. Expiry - .. Public EntryListeners - .. Cache lifecycle - .. CacheLoaders - .. CacheWriters - . +Store+ Roles - .. Store by Value vs. Ref. - .. Eviction & (private) EvictionListeners - -=== Other items - -==== Integrate 107 TCK - -Created issue #21 - -==== What's with the sizeof modules ? - - . *Hibernate* to be integrated within the h2lc module there - . *Groovy*, either: - .. @candrews takes ownership, or - .. we find someone within TC/SAG to do so (unidentified yet though) \ No newline at end of file From bfde5966e149494d3a0ffc1e88edb3a160781f90 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Thu, 18 Jan 2018 17:06:28 +0530 Subject: [PATCH 107/779] Adding lease mechanism #2197 --- clustered/client/build.gradle | 2 + .../service/DefaultClusteringService.java | 3 +- .../PassthroughLeasedConnectionService.java | 64 +++++++++ .../internal/UnitTestConnectionService.java | 6 + .../service/ConnectionClosedTest.java | 132 ++++++++++++++++++ ...a.lease.connection.LeasedConnectionService | 1 + clustered/clustered-dist/build.gradle | 3 + .../AbstractClusteringManagementTest.java | 2 +- gradle.properties | 2 +- 9 files changed, 212 insertions(+), 3 deletions(-) create mode 100644 clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java create mode 100644 clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java create mode 100644 clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService diff --git a/clustered/client/build.gradle b/clustered/client/build.gradle index dd5e7e5e94..1e65b1cc75 100644 --- a/clustered/client/build.gradle +++ b/clustered/client/build.gradle @@ -22,6 +22,7 @@ dependencies { compile project(':clustered:common'), "org.slf4j:slf4j-api:$slf4jVersion" provided "org.terracotta:entity-client-api:$terracottaApisVersion" provided "org.terracotta:runnel:$terracottaPlatformVersion" + provided "org.terracotta:lease-api:$terracottaPlatformVersion" testCompile project(':api') testCompile project(':xml') @@ -31,6 +32,7 @@ dependencies { } testCompile "org.terracotta:entity-test-lib:$terracottaPassthroughTestingVersion" testCompile "org.terracotta:passthrough-server:$terracottaPassthroughTestingVersion" + testCompile "org.terracotta.internal:common:$terracottaCoreVersion" } test { diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java index 87fe8fb77f..9c08a5a90b 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/service/DefaultClusteringService.java @@ -53,6 +53,7 @@ import org.terracotta.connection.entity.Entity; import org.terracotta.exception.EntityAlreadyExistsException; import org.terracotta.exception.EntityNotFoundException; +import org.terracotta.lease.connection.LeasedConnectionFactory; import java.io.IOException; import java.net.URI; @@ -174,7 +175,7 @@ private void initClusterConnection() { try { properties.put(ConnectionPropertyNames.CONNECTION_NAME, CONNECTION_PREFIX + entityIdentifier); properties.put(ConnectionPropertyNames.CONNECTION_TIMEOUT, Long.toString(timeouts.getConnectionTimeout().toMillis())); - clusterConnection = ConnectionFactory.connect(clusterUri, properties); + clusterConnection = LeasedConnectionFactory.connect(clusterUri, properties); } catch (ConnectionException ex) { throw new RuntimeException(ex); diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java new file mode 100644 index 0000000000..3ea95a4030 --- /dev/null +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java @@ -0,0 +1,64 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.clustered.client.internal; + +import com.tc.classloader.OverrideService; +import org.terracotta.connection.Connection; +import org.terracotta.connection.ConnectionException; +import org.terracotta.connection.ConnectionFactory; +import org.terracotta.connection.entity.Entity; +import org.terracotta.connection.entity.EntityRef; +import org.terracotta.exception.EntityNotProvidedException; +import org.terracotta.lease.connection.LeasedConnection; +import org.terracotta.lease.connection.LeasedConnectionService; + +import java.io.IOException; +import java.net.URI; +import java.util.Properties; + +@OverrideService("org.terracotta.lease.connection.LeasedConnectionServiceImpl") +public class PassthroughLeasedConnectionService implements LeasedConnectionService { + @Override + public boolean handlesURI(URI uri) { + return uri.getScheme().equals("passthrough") || + uri.getScheme().equals("terracotta") || + uri.getScheme().equals("mock"); // for the tests which are using mock connection service + } + + @Override + public LeasedConnection connect(URI uri, Properties properties) throws ConnectionException { + return new PassthroughLeasedConnection(ConnectionFactory.connect(uri, properties)); + } + + private static class PassthroughLeasedConnection implements LeasedConnection { + + private final Connection connection; + + PassthroughLeasedConnection(Connection connection) { + this.connection = connection; + } + + @Override + public EntityRef getEntityRef(Class cls, long version, String name) throws EntityNotProvidedException { + return connection.getEntityRef(cls, version, name); + } + + @Override + public void close() throws IOException { + connection.close(); + } + } +} diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java index dc1b8c3cbf..0a0a7d71df 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java @@ -149,6 +149,7 @@ public static void add(URI uri, PassthroughServer server) { // TODO rework that better server.registerAsynchronousServerCrasher(mock(IAsynchronousServerCrasher.class)); server.start(true, false); + server.addPermanentEntities(); LOGGER.info("Started PassthroughServer at {}", keyURI); } @@ -385,6 +386,11 @@ public static Collection getConnectionProperties(URI uri) { } } + public static Collection getConnections(URI uri) { + ServerDescriptor serverDescriptor = SERVERS.get(createKey(uri)); + return serverDescriptor.getConnections().keySet(); + } + @Override public boolean handlesURI(URI uri) { if (PASSTHROUGH.equals(uri.getScheme())) { diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java new file mode 100644 index 0000000000..bee110559b --- /dev/null +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java @@ -0,0 +1,132 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.clustered.client.internal.service; + +import org.ehcache.Cache; +import org.ehcache.PersistentCacheManager; +import org.ehcache.clustered.client.config.builders.TimeoutsBuilder; +import org.ehcache.clustered.client.internal.UnitTestConnectionService; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.config.units.EntryUnit; +import org.ehcache.config.units.MemoryUnit; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameter; +import org.junit.runners.Parameterized.Parameters; +import org.terracotta.connection.Connection; +import org.terracotta.connection.ConnectionPropertyNames; +import org.terracotta.exception.ConnectionClosedException; +import org.terracotta.lease.connection.LeasedConnection; + +import java.net.URI; +import java.time.Duration; +import java.util.Collection; +import java.util.Properties; + +import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; +import static org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder.cluster; +import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; +import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; +import static org.hamcrest.Matchers.instanceOf; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +@RunWith(Parameterized.class) +public class ConnectionClosedTest { + + private static final URI CLUSTER_URI = URI.create("terracotta://connection.com:9540/timeout"); + + @Parameters + public static ResourcePoolsBuilder[] data() { + return new ResourcePoolsBuilder[]{ResourcePoolsBuilder.newResourcePoolsBuilder() + .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)), + ResourcePoolsBuilder.newResourcePoolsBuilder() + .heap(10, EntryUnit.ENTRIES) + .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)) + }; + } + + @Parameter + public ResourcePoolsBuilder resourcePoolsBuilder; + + @Before + public void definePassthroughServer() throws Exception { + UnitTestConnectionService.add(CLUSTER_URI, + new UnitTestConnectionService.PassthroughServerBuilder() + .resource("primary-server-resource", 64, MemoryUnit.MB) + .resource("secondary-server-resource", 64, MemoryUnit.MB) + .build()); + } + + @After + public void removePassthroughServer() throws Exception { + try { + UnitTestConnectionService.remove(CLUSTER_URI); + } catch (IllegalStateException e) { + assertThat(e.getMessage(), is("Connection already closed")); + } + } + + @Test + public void testConnectionClosed() throws Exception { + + final CacheManagerBuilder clusteredCacheManagerBuilder = + newCacheManagerBuilder() + .with(cluster(CLUSTER_URI) + .timeouts(TimeoutsBuilder + .timeouts() + .connection(Duration.ofSeconds(20)) + .build()) + .autoCreate()) + .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class, + resourcePoolsBuilder)); + final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); + + final Cache cache = cacheManager.getCache("clustered-cache", Long.class, String.class); + + Collection connectionProperties = UnitTestConnectionService.getConnectionProperties(CLUSTER_URI); + + assertThat(connectionProperties.size(), is(1)); + Properties properties = connectionProperties.iterator().next(); + + assertThat(properties.getProperty(ConnectionPropertyNames.CONNECTION_TIMEOUT), is("20000")); + + cache.put(1L, "value"); + assertThat(cache.get(1L), is("value")); + + Collection connections = UnitTestConnectionService.getConnections(CLUSTER_URI); + + assertThat(connections.size(), is(1)); + + Connection connection = connections.iterator().next(); + + connection.close(); + + try { + cache.get(1L); + } catch (Exception e) { + assertThat(e.getCause().getCause(), instanceOf(ConnectionClosedException.class)); + } + + } + + +} diff --git a/clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService b/clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService new file mode 100644 index 0000000000..7e0e407bf7 --- /dev/null +++ b/clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService @@ -0,0 +1 @@ +org.ehcache.clustered.client.internal.PassthroughLeasedConnectionService \ No newline at end of file diff --git a/clustered/clustered-dist/build.gradle b/clustered/clustered-dist/build.gradle index 26882348c6..2489b98c79 100644 --- a/clustered/clustered-dist/build.gradle +++ b/clustered/clustered-dist/build.gradle @@ -45,6 +45,7 @@ configurations { dependencies { compileOnly "org.terracotta.internal:client-runtime:$terracottaCoreVersion" + compileOnly "org.terracotta:lease-api:$terracottaPlatformVersion" serverLibs(project(':clustered:server')) { exclude group: 'org.terracotta', module: 'entity-server-api' @@ -56,6 +57,8 @@ dependencies { // Needed because declared as provided in the different projects serverLibs "org.terracotta:runnel:$parent.terracottaPlatformVersion" + serverLibs "org.terracotta:lease-entity-server:$parent.terracottaPlatformVersion" + kit "org.terracotta.internal:terracotta-kit:$terracottaCoreVersion@zip" shadowCompile "org.slf4j:slf4j-api:$parent.slf4jVersion" diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java index 1826dde539..b360082ac9 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/AbstractClusteringManagementTest.java @@ -152,7 +152,7 @@ public static void beforeClass() throws Exception { "ENTITY_REGISTRY_AVAILABLE", "ENTITY_REGISTRY_AVAILABLE", "ENTITY_REGISTRY_AVAILABLE", "ENTITY_REGISTRY_AVAILABLE", "SERVER_ENTITY_CREATED", "SERVER_ENTITY_CREATED", "SERVER_ENTITY_CREATED", "SERVER_ENTITY_CREATED", "SERVER_ENTITY_CREATED", "SERVER_ENTITY_CREATED", "SERVER_ENTITY_DESTROYED", - "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", + "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_FETCHED", "SERVER_ENTITY_UNFETCHED" ); diff --git a/gradle.properties b/gradle.properties index b163628b4a..58dd6dd86f 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,7 +7,7 @@ slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre14 +terracottaPlatformVersion = 5.4.0-pre15 terracottaApisVersion = 1.4.0-pre8 terracottaCoreVersion = 5.4.0-pre18 terracottaPassthroughTestingVersion = 1.4.0-pre9 From c79848c0f90ed3c049507a519b0efd699503a9c6 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Mon, 22 Jan 2018 18:39:59 +0530 Subject: [PATCH 108/779] Proper passthrough dependency --- .../PassthroughLeasedConnectionService.java | 64 ------------------- .../service/ConnectionClosedTest.java | 14 ++-- ...a.lease.connection.LeasedConnectionService | 1 - gradle.properties | 2 +- 4 files changed, 8 insertions(+), 73 deletions(-) delete mode 100644 clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java delete mode 100644 clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java deleted file mode 100644 index 3ea95a4030..0000000000 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/PassthroughLeasedConnectionService.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright Terracotta, Inc. - * - * 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 org.ehcache.clustered.client.internal; - -import com.tc.classloader.OverrideService; -import org.terracotta.connection.Connection; -import org.terracotta.connection.ConnectionException; -import org.terracotta.connection.ConnectionFactory; -import org.terracotta.connection.entity.Entity; -import org.terracotta.connection.entity.EntityRef; -import org.terracotta.exception.EntityNotProvidedException; -import org.terracotta.lease.connection.LeasedConnection; -import org.terracotta.lease.connection.LeasedConnectionService; - -import java.io.IOException; -import java.net.URI; -import java.util.Properties; - -@OverrideService("org.terracotta.lease.connection.LeasedConnectionServiceImpl") -public class PassthroughLeasedConnectionService implements LeasedConnectionService { - @Override - public boolean handlesURI(URI uri) { - return uri.getScheme().equals("passthrough") || - uri.getScheme().equals("terracotta") || - uri.getScheme().equals("mock"); // for the tests which are using mock connection service - } - - @Override - public LeasedConnection connect(URI uri, Properties properties) throws ConnectionException { - return new PassthroughLeasedConnection(ConnectionFactory.connect(uri, properties)); - } - - private static class PassthroughLeasedConnection implements LeasedConnection { - - private final Connection connection; - - PassthroughLeasedConnection(Connection connection) { - this.connection = connection; - } - - @Override - public EntityRef getEntityRef(Class cls, long version, String name) throws EntityNotProvidedException { - return connection.getEntityRef(cls, version, name); - } - - @Override - public void close() throws IOException { - connection.close(); - } - } -} diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java index bee110559b..532e7b0243 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java @@ -34,7 +34,6 @@ import org.terracotta.connection.Connection; import org.terracotta.connection.ConnectionPropertyNames; import org.terracotta.exception.ConnectionClosedException; -import org.terracotta.lease.connection.LeasedConnection; import java.net.URI; import java.time.Duration; @@ -56,8 +55,9 @@ public class ConnectionClosedTest { @Parameters public static ResourcePoolsBuilder[] data() { - return new ResourcePoolsBuilder[]{ResourcePoolsBuilder.newResourcePoolsBuilder() - .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)), + return new ResourcePoolsBuilder[]{ + ResourcePoolsBuilder.newResourcePoolsBuilder() + .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)), ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(10, EntryUnit.ENTRIES) .with(clusteredDedicated("primary-server-resource", 2, MemoryUnit.MB)) @@ -86,9 +86,9 @@ public void removePassthroughServer() throws Exception { } @Test - public void testConnectionClosed() throws Exception { + public void testCacheOperationThrowsAfterConnectionClosed() throws Exception { - final CacheManagerBuilder clusteredCacheManagerBuilder = + CacheManagerBuilder clusteredCacheManagerBuilder = newCacheManagerBuilder() .with(cluster(CLUSTER_URI) .timeouts(TimeoutsBuilder @@ -98,9 +98,9 @@ public void testConnectionClosed() throws Exception { .autoCreate()) .withCache("clustered-cache", newCacheConfigurationBuilder(Long.class, String.class, resourcePoolsBuilder)); - final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); + PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(true); - final Cache cache = cacheManager.getCache("clustered-cache", Long.class, String.class); + Cache cache = cacheManager.getCache("clustered-cache", Long.class, String.class); Collection connectionProperties = UnitTestConnectionService.getConnectionProperties(CLUSTER_URI); diff --git a/clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService b/clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService deleted file mode 100644 index 7e0e407bf7..0000000000 --- a/clustered/client/src/test/resources/META-INF/services/org.terracotta.lease.connection.LeasedConnectionService +++ /dev/null @@ -1 +0,0 @@ -org.ehcache.clustered.client.internal.PassthroughLeasedConnectionService \ No newline at end of file diff --git a/gradle.properties b/gradle.properties index 58dd6dd86f..b733b6ae87 100644 --- a/gradle.properties +++ b/gradle.properties @@ -10,7 +10,7 @@ sizeofVersion = 0.3.0 terracottaPlatformVersion = 5.4.0-pre15 terracottaApisVersion = 1.4.0-pre8 terracottaCoreVersion = 5.4.0-pre18 -terracottaPassthroughTestingVersion = 1.4.0-pre9 +terracottaPassthroughTestingVersion = 1.4.0-pre11 # Test lib versions junitVersion = 4.12 From 451dae88c8ea433b252bc6be8c1bb5be70d0b0eb Mon Sep 17 00:00:00 2001 From: Chris Dennis Date: Wed, 17 Jan 2018 15:47:15 -0500 Subject: [PATCH 109/779] Fixes #2213 : Extract OversizeMappingException logic in to a common method --- .../server/offheap/OffHeapServerStore.java | 139 ++++++------------ .../offheap/OffHeapServerStoreTest.java | 9 +- 2 files changed, 52 insertions(+), 96 deletions(-) diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapServerStore.java b/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapServerStore.java index b1e7d84709..72d64dec86 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapServerStore.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/offheap/OffHeapServerStore.java @@ -18,6 +18,8 @@ import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.List; +import java.util.function.LongConsumer; +import java.util.function.LongFunction; import org.ehcache.clustered.common.internal.store.Chain; import org.ehcache.clustered.common.internal.store.ServerStore; @@ -88,29 +90,7 @@ public void append(long key, ByteBuffer payLoad) { try { segmentFor(key).append(key, payLoad); } catch (OversizeMappingException e) { - if (handleOversizeMappingException(key)) { - try { - segmentFor(key).append(key, payLoad); - return; - } catch (OversizeMappingException ex) { - //ignore - } - } - - writeLockAll(); - try { - do { - try { - segmentFor(key).append(key, payLoad); - return; - } catch (OversizeMappingException ex) { - e = ex; - } - } while (handleOversizeMappingException(key)); - throw e; - } finally { - writeUnlockAll(); - } + handleOversizeMappingException(key, (long k) -> segmentFor(k).append(k, payLoad)); } } @@ -119,27 +99,7 @@ public Chain getAndAppend(long key, ByteBuffer payLoad) { try { return segmentFor(key).getAndAppend(key, payLoad); } catch (OversizeMappingException e) { - if (handleOversizeMappingException(key)) { - try { - return segmentFor(key).getAndAppend(key, payLoad); - } catch (OversizeMappingException ex) { - //ignore - } - } - - writeLockAll(); - try { - do { - try { - return segmentFor(key).getAndAppend(key, payLoad); - } catch (OversizeMappingException ex) { - e = ex; - } - } while (handleOversizeMappingException(key)); - throw e; - } finally { - writeUnlockAll(); - } + return handleOversizeMappingException(key, (long k) -> segmentFor(k).getAndAppend(k, payLoad)); } } @@ -148,29 +108,7 @@ public void replaceAtHead(long key, Chain expect, Chain update) { try { segmentFor(key).replaceAtHead(key, expect, update); } catch (OversizeMappingException e) { - if (handleOversizeMappingException(key)) { - try { - segmentFor(key).replaceAtHead(key, expect, update); - return; - } catch (OversizeMappingException ex) { - //ignore - } - } - - writeLockAll(); - try { - do { - try { - segmentFor(key).replaceAtHead(key, expect, update); - return; - } catch (OversizeMappingException ex) { - e = ex; - } - } while (handleOversizeMappingException(key)); - throw e; - } finally { - writeUnlockAll(); - } + handleOversizeMappingException(key, (long k) -> segmentFor(k).replaceAtHead(k, expect, update)); } } @@ -178,27 +116,7 @@ public void put(long key, Chain chain) { try { segmentFor(key).put(key, chain); } catch (OversizeMappingException e) { - if (handleOversizeMappingException(key)) { - try { - segmentFor(key).put(key, chain); - } catch (OversizeMappingException ex) { - //ignore - } - } - - writeLockAll(); - try { - do { - try { - segmentFor(key).put(key, chain); - } catch (OversizeMappingException ex) { - e = ex; - } - } while (handleOversizeMappingException(key)); - throw e; - } finally { - writeUnlockAll(); - } + handleOversizeMappingException(key, (long k) -> segmentFor(k).put(k, chain)); } } @@ -226,10 +144,51 @@ private void writeUnlockAll() { } } - boolean handleOversizeMappingException(long hash) { + private void handleOversizeMappingException(long key, LongConsumer operation) { + handleOversizeMappingException(key, k -> { + operation.accept(k); + return null; + }); + } + + /** + * Force eviction from other segments until {@code operation} succeeds or no further eviction is possible. + * + * @param key the target key + * @param operation the previously failed operation + * @param operation result type + * @return the operation result + * @throws OversizeMappingException if the operation cannot be made to succeed + */ + private R handleOversizeMappingException(long key, LongFunction operation) throws OversizeMappingException { + if (tryShrinkOthers(key)) { + try { + return operation.apply(key); + } catch (OversizeMappingException ex) { + //ignore + } + } + + writeLockAll(); + try { + OversizeMappingException e; + do { + try { + return operation.apply(key); + } catch (OversizeMappingException ex) { + e = ex; + } + } while (tryShrinkOthers(key)); + throw e; + } finally { + writeUnlockAll(); + } + } + + boolean tryShrinkOthers(long key) { boolean evicted = false; - OffHeapChainMap target = segmentFor(hash); + OffHeapChainMap target = segmentFor(key); for (OffHeapChainMap s : segments) { if (s != target) { evicted |= s.shrink(); diff --git a/clustered/server/src/test/java/org/ehcache/clustered/server/offheap/OffHeapServerStoreTest.java b/clustered/server/src/test/java/org/ehcache/clustered/server/offheap/OffHeapServerStoreTest.java index 5f85554248..f251e4d450 100644 --- a/clustered/server/src/test/java/org/ehcache/clustered/server/offheap/OffHeapServerStoreTest.java +++ b/clustered/server/src/test/java/org/ehcache/clustered/server/offheap/OffHeapServerStoreTest.java @@ -19,14 +19,12 @@ import java.util.Random; import org.ehcache.clustered.common.internal.store.Chain; -import org.ehcache.clustered.common.internal.store.Element; import org.ehcache.clustered.server.KeySegmentMapper; import org.ehcache.clustered.server.store.ChainBuilder; import org.ehcache.clustered.server.store.ElementBuilder; import org.ehcache.clustered.common.internal.store.ServerStore; import org.ehcache.clustered.server.store.ServerStoreTest; import org.junit.Test; -import org.mockito.ArgumentMatchers; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.terracotta.offheapstore.buffersource.OffHeapBufferSource; @@ -46,7 +44,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.terracotta.offheapstore.util.MemoryUnit.GIGABYTES; -import static org.terracotta.offheapstore.util.MemoryUnit.KILOBYTES; import static org.terracotta.offheapstore.util.MemoryUnit.MEGABYTES; public class OffHeapServerStoreTest extends ServerStoreTest { @@ -109,7 +106,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } } }); - when(store.handleOversizeMappingException(anyLong())).thenReturn(true); + when(store.tryShrinkOthers(anyLong())).thenReturn(true); ByteBuffer payload = createPayload(1L); @@ -134,7 +131,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } } }); - when(store.handleOversizeMappingException(anyLong())).thenReturn(true); + when(store.tryShrinkOthers(anyLong())).thenReturn(true); ByteBuffer payload = createPayload(1L); @@ -165,7 +162,7 @@ public Object answer(InvocationOnMock invocation) throws Throwable { } } }); - when(store.handleOversizeMappingException(anyLong())).thenReturn(true); + when(store.tryShrinkOthers(anyLong())).thenReturn(true); ByteBuffer payload = createPayload(1L); From 09b720247b1ff9a89be9e9cde92b1b274404a638 Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Wed, 24 Jan 2018 16:48:38 -0500 Subject: [PATCH 110/779] :snowflake: Fixing dependency not found when building with Gradle --- clustered/clustered-dist/build.gradle | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/clustered/clustered-dist/build.gradle b/clustered/clustered-dist/build.gradle index 2489b98c79..f49a141127 100644 --- a/clustered/clustered-dist/build.gradle +++ b/clustered/clustered-dist/build.gradle @@ -59,7 +59,7 @@ dependencies { serverLibs "org.terracotta:lease-entity-server:$parent.terracottaPlatformVersion" - kit "org.terracotta.internal:terracotta-kit:$terracottaCoreVersion@zip" + kit "org.terracotta.internal:terracotta-kit:$terracottaCoreVersion@tar.gz" shadowCompile "org.slf4j:slf4j-api:$parent.slf4jVersion" pomOnlyCompile "org.ehcache:ehcache:$parent.baseVersion" @@ -77,7 +77,7 @@ distributions { contents { //tc kit into ('') { - from configurations.kit.files.collect { zipTree(it) } + from configurations.kit.files.collect { tarTree(it) } eachFile { f -> // remove top level directory from the kit f.path = f.path.replace("terracotta-$terracottaCoreVersion/", "") From c14727b79d95367fe236c36155f1f5e331dd607f Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 18 Jan 2018 14:43:46 -0500 Subject: [PATCH 111/779] Refactor getExpiryForCreation call to a common place --- .../org/ehcache/core/config/ExpiryUtils.java | 48 ++++++++++-- .../ehcache/core/config/ExpiryUtilsTest.java | 76 +++++++++++++++++++ .../impl/internal/store/heap/OnHeapStore.java | 18 +---- .../store/offheap/AbstractOffHeapStore.java | 23 ++---- .../org/ehcache/xml/XmlConfigurationTest.java | 4 +- 5 files changed, 133 insertions(+), 36 deletions(-) create mode 100644 core/src/test/java/org/ehcache/core/config/ExpiryUtilsTest.java diff --git a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java index 1386fd7e1a..407b76ee57 100644 --- a/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java +++ b/core/src/main/java/org/ehcache/core/config/ExpiryUtils.java @@ -17,6 +17,8 @@ package org.ehcache.core.config; import org.ehcache.expiry.ExpiryPolicy; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import java.time.Duration; import java.time.temporal.ChronoUnit; @@ -28,7 +30,9 @@ * ExpiryUtils */ @SuppressWarnings("deprecation") -public class ExpiryUtils { +public class ExpiryUtils { + + private static final Logger LOG = LoggerFactory.getLogger(ExpiryUtils.class); public static boolean isExpiryDurationInfinite(Duration duration) { return duration.compareTo(ExpiryPolicy.INFINITE) >= 0; @@ -51,12 +55,12 @@ public org.ehcache.expiry.Duration getExpiryForCreation(K key, V value) { @Override public org.ehcache.expiry.Duration getExpiryForAccess(K key, org.ehcache.ValueSupplier value) { - return convertDuration(expiryPolicy.getExpiryForAccess(key, () -> value.value())); + return convertDuration(expiryPolicy.getExpiryForAccess(key, value::value)); } @Override public org.ehcache.expiry.Duration getExpiryForUpdate(K key, org.ehcache.ValueSupplier oldValue, V newValue) { - return convertDuration(expiryPolicy.getExpiryForUpdate(key, () -> oldValue.value(), newValue)); + return convertDuration(expiryPolicy.getExpiryForUpdate(key, oldValue::value, newValue)); } @Override @@ -115,13 +119,13 @@ public Duration getExpiryForCreation(K key, V value) { @Override public Duration getExpiryForAccess(K key, Supplier value) { - org.ehcache.expiry.Duration duration = expiry.getExpiryForAccess(key, () -> value.get()); + org.ehcache.expiry.Duration duration = expiry.getExpiryForAccess(key, value::get); return convertDuration(duration); } @Override public Duration getExpiryForUpdate(K key, Supplier oldValue, V newValue) { - org.ehcache.expiry.Duration duration = expiry.getExpiryForUpdate(key, () -> oldValue.get(), newValue); + org.ehcache.expiry.Duration duration = expiry.getExpiryForUpdate(key, oldValue::get, newValue); return convertDuration(duration); } @@ -173,5 +177,39 @@ public static long getExpirationMillis(long now, Duration duration) { } catch (ArithmeticException e) { return Long.MAX_VALUE; } + + } + + /** + * Returns the expiry for creation duration returned by the provided {@link ExpiryPolicy} but checks for immediate + * expiry, null expiry and exceptions. In all those cases, {@code null} will be returned. + * + * @param key key to pass to {@link ExpiryPolicy#getExpiryForCreation(Object, Object)} + * @param value value to pass to to pass to {@link ExpiryPolicy#getExpiryForCreation(Object, Object)} + * @param expiry expiry queried + * @param type of key + * @param type of value + * @return the duration returned by to pass to {@link ExpiryPolicy#getExpiryForCreation(Object, Object)}, {@code null} + * if the call throws an exception, if the returned duration is {@code null} or if it is lower or equal to 0 + */ + public static Duration getExpiryForCreation(K key, V value, ExpiryPolicy expiry) { + Duration duration; + try { + duration = expiry.getExpiryForCreation(key, value); + } catch (RuntimeException e) { + LOG.error("Expiry computation caused an exception - Expiry duration will be 0", e); + return Duration.ZERO; + } + + if (duration == null) { + LOG.error("Expiry for creation can't be null - Expiry duration will be 0"); + return Duration.ZERO; + } + + if (Duration.ZERO.compareTo(duration) >= 0) { + return Duration.ZERO; + } + + return duration; } } diff --git a/core/src/test/java/org/ehcache/core/config/ExpiryUtilsTest.java b/core/src/test/java/org/ehcache/core/config/ExpiryUtilsTest.java new file mode 100644 index 0000000000..1de47e2845 --- /dev/null +++ b/core/src/test/java/org/ehcache/core/config/ExpiryUtilsTest.java @@ -0,0 +1,76 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.config; + +import org.ehcache.expiry.ExpiryPolicy; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnit; +import org.mockito.junit.MockitoRule; + +import java.time.Duration; + +import static org.assertj.core.api.Assertions.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ExpiryUtilsTest { + + @Rule + public MockitoRule rule = MockitoJUnit.rule(); + + @Mock + private ExpiryPolicy expiry; + + @Test + public void getExpiryForCreation_valid() { + Duration expected = Duration.ofMinutes(1); + when(expiry.getExpiryForCreation(1, 2)).thenReturn(expected); + Duration actual = ExpiryUtils.getExpiryForCreation(1, 2, expiry); + assertThat(actual).isEqualTo(expected); + } + + @Test + public void getExpiryForCreation_negative() { + Duration expected = Duration.ofMinutes(-1); + when(expiry.getExpiryForCreation(1, 2)).thenReturn(expected); + Duration actual = ExpiryUtils.getExpiryForCreation(1, 2, expiry); + assertThat(actual).isEqualTo(Duration.ZERO); + } + + @Test + public void getExpiryForCreation_zero() { + Duration expected = Duration.ZERO; + when(expiry.getExpiryForCreation(1, 2)).thenReturn(expected); + Duration actual = ExpiryUtils.getExpiryForCreation(1, 2, expiry); + assertThat(actual).isEqualTo(expected); + } + + @Test + public void getExpiryForCreation_null() { + when(expiry.getExpiryForCreation(1, 2)).thenReturn(null); + Duration actual = ExpiryUtils.getExpiryForCreation(1, 2, expiry); + assertThat(actual).isEqualTo(Duration.ZERO); + } + + @Test + public void getExpiryForCreation_exception() { + when(expiry.getExpiryForCreation(1, 2)).thenThrow(new RuntimeException()); + Duration actual = ExpiryUtils.getExpiryForCreation(1, 2, expiry); + assertThat(actual).isEqualTo(Duration.ZERO); + } +} diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index a01d7c187d..1974a9341c 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -83,6 +83,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Objects; import java.util.Random; import java.util.Set; import java.util.concurrent.TimeUnit; @@ -1362,21 +1363,10 @@ private OnHeapValueHolder newUpdateValueHolder(K key, OnHeapValueHolder ol } private OnHeapValueHolder newCreateValueHolder(K key, V value, long now, StoreEventSink eventSink) { - if (value == null) { - throw new NullPointerException(); - } + Objects.requireNonNull(value); - Duration duration; - try { - duration = expiry.getExpiryForCreation(key, value); - if (duration.isNegative()) { - return null; - } - } catch (RuntimeException re) { - LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); - return null; - } - if (Duration.ZERO.equals(duration)) { + Duration duration = ExpiryUtils.getExpiryForCreation(key, value, expiry); + if(duration.isZero()) { return null; } diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index fc41da724a..b2be354a71 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -21,6 +21,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; @@ -1018,26 +1019,18 @@ private OffHeapValueHolder newUpdatedValueHolder(K key, V value, OffHeapValue } private OffHeapValueHolder newCreateValueHolder(K key, V value, long now, StoreEventSink eventSink) { - Duration duration = Duration.ZERO; - try { - duration = expiry.getExpiryForCreation(key, value); - if (duration.isNegative()) { - return null; - } - } catch (RuntimeException re) { - LOG.error("Expiry computation caused an exception - Expiry duration will be 0 ", re); - } - if (Duration.ZERO.equals(duration)) { + Objects.requireNonNull(value); + + Duration duration = ExpiryUtils.getExpiryForCreation(key, value, expiry); + if(duration.isZero()) { return null; } eventSink.created(key, value); - if (isExpiryDurationInfinite(duration)) { - return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, OffHeapValueHolder.NO_EXPIRE); - } else { - return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, ExpiryUtils.getExpirationMillis(now, duration)); - } + long expirationTime = isExpiryDurationInfinite(duration) ? ValueHolder.NO_EXPIRE : ExpiryUtils.getExpirationMillis(now, duration); + + return new BasicOffHeapValueHolder<>(backingMap().nextIdFor(key), value, now, expirationTime); } private OffHeapValueHolder newTransferValueHolder(ValueHolder valueHolder) { diff --git a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java index 39b695adba..aa9fe8e19c 100644 --- a/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java +++ b/xml/src/test/java/org/ehcache/xml/XmlConfigurationTest.java @@ -224,8 +224,8 @@ public void testExpiryIsParsed() throws Exception { expiry = xmlConfiguration.getCacheConfigurations().get("deprecatedClass").getExpiryPolicy(); assertThat(expiry.getExpiryForCreation(null, null), is(Duration.ofSeconds(42))); - assertThat(expiry.getExpiryForAccess(null, null), is(Duration.ofSeconds(42))); - assertThat(expiry.getExpiryForUpdate(null, null, null), is(Duration.ofSeconds(42))); + assertThat(expiry.getExpiryForAccess(null, () -> null), is(Duration.ofSeconds(42))); + assertThat(expiry.getExpiryForUpdate(null, () -> null, null), is(Duration.ofSeconds(42))); expiry = xmlConfiguration.getCacheConfigurations().get("tti").getExpiryPolicy(); value = ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofMillis(500)); From 58096b5ba2090ef792233912e68e7d3244112495 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 23 Jan 2018 21:57:28 -0500 Subject: [PATCH 112/779] Fix tiny feedback from Error-prone --- .../main/java/org/ehcache/clustered/common/PoolAllocation.java | 3 +++ .../common/internal/messages/LifeCycleMessageCodec.java | 3 ++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/PoolAllocation.java b/clustered/common/src/main/java/org/ehcache/clustered/common/PoolAllocation.java index 9a60d37aaa..6917c5b099 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/PoolAllocation.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/PoolAllocation.java @@ -61,6 +61,7 @@ public Dedicated(String resourceName, long size) { * * @return the dedicated allocation size */ + @Override public long getSize() { return size; } @@ -71,6 +72,7 @@ public long getSize() { * * @return the server-side resource name */ + @Override public String getResourceName() { return resourceName; } @@ -117,6 +119,7 @@ public Shared(String resourcePoolName) { * * @return the server-side resource pool name */ + @Override public String getResourcePoolName() { return resourcePoolName; } diff --git a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java index 31070351a2..af1c5b5ba9 100644 --- a/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java +++ b/clustered/common/src/main/java/org/ehcache/clustered/common/internal/messages/LifeCycleMessageCodec.java @@ -117,8 +117,9 @@ public EhcacheEntityMessage decode(EhcacheMessageType messageType, ByteBuffer me return decodeValidateServerStoreMessage(messageBuffer); case PREPARE_FOR_DESTROY: return decodePrepareForDestroyMessage(); + default: + throw new IllegalArgumentException("LifeCycleMessage operation not defined for : " + messageType); } - throw new IllegalArgumentException("LifeCycleMessage operation not defined for : " + messageType); } private LifecycleMessage.PrepareForDestroy decodePrepareForDestroyMessage() { From 3f2100194d29b46d255542e86e9e5a9bfc42d515 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Tue, 23 Jan 2018 21:57:42 -0500 Subject: [PATCH 113/779] Remove deprecation warnings --- .../org/ehcache/core/internal/util/ValueSuppliers.java | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java b/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java index 7d24db1173..3ddf09f839 100644 --- a/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java +++ b/core/src/main/java/org/ehcache/core/internal/util/ValueSuppliers.java @@ -16,10 +16,8 @@ package org.ehcache.core.internal.util; -import org.ehcache.ValueSupplier; - /** - * Utility for creating basic {@link ValueSupplier} instances + * Utility for creating basic {@link org.ehcache.ValueSupplier} instances * * @deprecated Now using {@code Supplier} for {@link org.ehcache.expiry.ExpiryPolicy} */ @@ -27,13 +25,13 @@ public final class ValueSuppliers { /** - * Returns a basic {@link ValueSupplier} that serves the value passed in + * Returns a basic {@link org.ehcache.ValueSupplier} that serves the value passed in * * @param value the value to hold * @param the value type * @return a value supplier with the given value */ - public static ValueSupplier supplierOf(final V value) { + public static org.ehcache.ValueSupplier supplierOf(final V value) { return () -> value; } From 2e9814736fa2bc9a0d50a1f31f39a48de29909e9 Mon Sep 17 00:00:00 2001 From: Mathieu Carbou Date: Fri, 17 Nov 2017 15:19:23 -0500 Subject: [PATCH 114/779] :heavy_plus_sign: Close #2187: Latency statistics --- .../ClusteringManagementServiceTest.java | 4 +- .../PoolStatisticsManagementProvider.java | 4 +- .../core/spi/service/StatisticsService.java | 2 + .../StatisticsServiceConfiguration.java | 42 +++++ .../core/statistics/CacheStatistics.java | 12 ++ gradle.properties | 4 +- .../statistics/DefaultCacheStatistics.java | 164 ++++++++---------- .../statistics/DefaultStatisticsService.java | 30 +++- ...DefaultStatisticsServiceConfiguration.java | 91 ++++++++++ .../DefaultStatisticsServiceFactory.java | 12 +- .../DefaultCacheStatisticsTest.java | 112 +++++++++++- ...ultStatisticsServiceConfigurationTest.java | 64 +++++++ .../DefaultStatisticsServiceFactoryTest.java | 61 +++++++ .../statistics/StandardEhcacheStatistics.java | 12 -- .../DefaultManagementRegistryServiceTest.java | 1 + 15 files changed, 492 insertions(+), 123 deletions(-) create mode 100644 core/src/main/java/org/ehcache/core/spi/service/StatisticsServiceConfiguration.java create mode 100644 impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfiguration.java create mode 100644 impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfigurationTest.java create mode 100644 impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactoryTest.java diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java index 1cfaebd8cb..6fd70f9f20 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java @@ -18,7 +18,6 @@ import org.ehcache.Cache; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; -import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Ignore; import org.junit.Test; @@ -93,7 +92,8 @@ public class ClusteringManagementServiceTest extends AbstractClusteringManagemen new StatisticDescriptor("Cache:PutCount", "COUNTER"), new StatisticDescriptor("Cache:RemovalCount", "COUNTER"), new StatisticDescriptor("Cache:EvictionCount", "COUNTER"), - new StatisticDescriptor("Cache:ExpirationCount", "COUNTER") + new StatisticDescriptor("Cache:ExpirationCount", "COUNTER"), + new StatisticDescriptor("Cache:GetLatency", "GAUGE") ); private static final Collection POOL_DESCRIPTORS = Arrays.asList( new StatisticDescriptor("Pool:AllocatedSize", "GAUGE") diff --git a/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java b/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java index 84013c85c1..47dbf004b8 100644 --- a/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java +++ b/clustered/server/src/main/java/org/ehcache/clustered/server/management/PoolStatisticsManagementProvider.java @@ -60,10 +60,10 @@ protected StatisticRegistry getStatisticRegistry(PoolBinding managedObject) { PoolBinding.AllocationType allocationType = managedObject.getAllocationType(); if (allocationType == PoolBinding.AllocationType.DEDICATED) { - return new StatisticRegistry(ehcacheStateService.getDedicatedResourcePageSource(poolName)); + return new StatisticRegistry(ehcacheStateService.getDedicatedResourcePageSource(poolName), () -> getTimeSource().getTimestamp()); } else { - return new StatisticRegistry(ehcacheStateService.getSharedResourcePageSource(poolName)); + return new StatisticRegistry(ehcacheStateService.getSharedResourcePageSource(poolName), () -> getTimeSource().getTimestamp()); } } diff --git a/core/src/main/java/org/ehcache/core/spi/service/StatisticsService.java b/core/src/main/java/org/ehcache/core/spi/service/StatisticsService.java index eb30fadedf..9acf849c1e 100644 --- a/core/src/main/java/org/ehcache/core/spi/service/StatisticsService.java +++ b/core/src/main/java/org/ehcache/core/spi/service/StatisticsService.java @@ -24,5 +24,7 @@ */ public interface StatisticsService extends Service { + StatisticsServiceConfiguration getConfiguration(); + CacheStatistics getCacheStatistics(String cacheName); } diff --git a/core/src/main/java/org/ehcache/core/spi/service/StatisticsServiceConfiguration.java b/core/src/main/java/org/ehcache/core/spi/service/StatisticsServiceConfiguration.java new file mode 100644 index 0000000000..affd8b347c --- /dev/null +++ b/core/src/main/java/org/ehcache/core/spi/service/StatisticsServiceConfiguration.java @@ -0,0 +1,42 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.spi.service; + +import org.ehcache.spi.service.ServiceCreationConfiguration; + +import java.util.concurrent.TimeUnit; + +public interface StatisticsServiceConfiguration extends ServiceCreationConfiguration { + + /** + * Aggregation is done by keeping the maximum value that has been seen. + * A low value (i.e. 500ms) is better. + * + * @return The interval used to aggregate the latencies of Ehcache operations to create one latency sample. + */ + long getLatencyHistoryWindowInterval(); + + /** + * @return the unit for the latency history interval + */ + TimeUnit getLatencyHistoryWindowUnit(); + + /** + * @return the maximum number of maximum latency samples to keep. + */ + int getLatencyHistorySize(); + +} diff --git a/core/src/main/java/org/ehcache/core/statistics/CacheStatistics.java b/core/src/main/java/org/ehcache/core/statistics/CacheStatistics.java index c49fad1b22..34795c9841 100644 --- a/core/src/main/java/org/ehcache/core/statistics/CacheStatistics.java +++ b/core/src/main/java/org/ehcache/core/statistics/CacheStatistics.java @@ -16,6 +16,7 @@ package org.ehcache.core.statistics; +import org.terracotta.statistics.SampledStatistic; import org.terracotta.statistics.ValueStatistic; import java.util.Map; @@ -130,4 +131,15 @@ public interface CacheStatistics { * @return average remove response time */ float getCacheAverageRemoveTime(); + + /** + * The statistic used to access the latest history of latencies for {@link org.ehcache.Cache#get(Object)} + * operations leading to a {@link org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome#HIT}. + *

+ * The history and latency aggregation is controlled through the {@link org.ehcache.core.spi.service.StatisticsServiceConfiguration}. + * + * @return the sampled statistic + */ + SampledStatistic getCacheGetLatencyHistory(); + } diff --git a/gradle.properties b/gradle.properties index b733b6ae87..fa506f6474 100644 --- a/gradle.properties +++ b/gradle.properties @@ -1,13 +1,13 @@ # Terracotta third parties offheapVersion = 2.4.0 -statisticVersion = 2.0.2 +statisticVersion = 2.0.3 jcacheVersion = 1.1.0 slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre15 +terracottaPlatformVersion = 5.4.0-pre16 terracottaApisVersion = 1.4.0-pre8 terracottaCoreVersion = 5.4.0-pre18 terracottaPassthroughTestingVersion = 1.4.0-pre11 diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java index 7d51329b02..3174d8b0e5 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultCacheStatistics.java @@ -16,25 +16,32 @@ package org.ehcache.impl.internal.statistics; -import java.util.Collections; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.atomic.LongAdder; - import org.ehcache.core.InternalCache; +import org.ehcache.core.spi.service.StatisticsServiceConfiguration; +import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.statistics.BulkOps; -import org.ehcache.core.statistics.CacheOperationOutcomes; +import org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome; +import org.ehcache.core.statistics.CacheOperationOutcomes.PutOutcome; import org.ehcache.core.statistics.CacheStatistics; import org.ehcache.core.statistics.TierStatistics; import org.terracotta.statistics.OperationStatistic; +import org.terracotta.statistics.SampledStatistic; import org.terracotta.statistics.ValueStatistic; -import org.terracotta.statistics.derived.LatencySampling; -import org.terracotta.statistics.derived.MinMaxAverage; -import org.terracotta.statistics.observer.ChainedOperationObserver; +import org.terracotta.statistics.derived.OperationResultFilter; +import org.terracotta.statistics.derived.latency.Jsr107LatencyMonitor; +import org.terracotta.statistics.derived.latency.MaximumLatencyHistory; + +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.atomic.LongAdder; import static java.util.EnumSet.allOf; +import static org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; +import static org.ehcache.core.statistics.CacheOperationOutcomes.PutIfAbsentOutcome; +import static org.ehcache.core.statistics.CacheOperationOutcomes.RemoveOutcome; +import static org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; import static org.ehcache.impl.internal.statistics.StatsUtils.findLowestTier; import static org.ehcache.impl.internal.statistics.StatsUtils.findOperationStatisticOnChildren; import static org.ehcache.impl.internal.statistics.StatsUtils.findTiers; @@ -47,39 +54,41 @@ class DefaultCacheStatistics implements CacheStatistics { private volatile CompensatingCounters compensatingCounters = CompensatingCounters.empty(); - private final OperationStatistic get; - private final OperationStatistic put; - private final OperationStatistic remove; - private final OperationStatistic putIfAbsent; - private final OperationStatistic replace; - private final OperationStatistic conditionalRemove; + private final OperationStatistic get; + private final OperationStatistic put; + private final OperationStatistic remove; + private final OperationStatistic putIfAbsent; + private final OperationStatistic replace; + private final OperationStatistic conditionalRemove; private final Map bulkMethodEntries; - private final LatencyMonitor averageGetTime; - private final LatencyMonitor averagePutTime; - private final LatencyMonitor averageRemoveTime; + private final Jsr107LatencyMonitor averageGetTime; + private final Jsr107LatencyMonitor averagePutTime; + private final Jsr107LatencyMonitor averageRemoveTime; private final Map tierStatistics; private final TierStatistics lowestTier; private final Map> knownStatistics; - public DefaultCacheStatistics(InternalCache cache) { + private final MaximumLatencyHistory latencyHistory; + + public DefaultCacheStatistics(InternalCache cache, StatisticsServiceConfiguration configuration, TimeSource timeSource) { bulkMethodEntries = cache.getBulkMethodEntries(); - get = findOperationStatisticOnChildren(cache, CacheOperationOutcomes.GetOutcome.class, "get"); - put = findOperationStatisticOnChildren(cache, CacheOperationOutcomes.PutOutcome.class, "put"); - remove = findOperationStatisticOnChildren(cache, CacheOperationOutcomes.RemoveOutcome.class, "remove"); - putIfAbsent = findOperationStatisticOnChildren(cache, CacheOperationOutcomes.PutIfAbsentOutcome.class, "putIfAbsent"); - replace = findOperationStatisticOnChildren(cache, CacheOperationOutcomes.ReplaceOutcome.class, "replace"); - conditionalRemove = findOperationStatisticOnChildren(cache, CacheOperationOutcomes.ConditionalRemoveOutcome.class, "conditionalRemove"); + get = findOperationStatisticOnChildren(cache, GetOutcome.class, "get"); + put = findOperationStatisticOnChildren(cache, PutOutcome.class, "put"); + remove = findOperationStatisticOnChildren(cache, RemoveOutcome.class, "remove"); + putIfAbsent = findOperationStatisticOnChildren(cache, PutIfAbsentOutcome.class, "putIfAbsent"); + replace = findOperationStatisticOnChildren(cache, ReplaceOutcome.class, "replace"); + conditionalRemove = findOperationStatisticOnChildren(cache, ConditionalRemoveOutcome.class, "conditionalRemove"); - averageGetTime = new LatencyMonitor<>(allOf(CacheOperationOutcomes.GetOutcome.class)); + averageGetTime = new Jsr107LatencyMonitor<>(allOf(GetOutcome.class), 1.0); get.addDerivedStatistic(averageGetTime); - averagePutTime = new LatencyMonitor<>(allOf(CacheOperationOutcomes.PutOutcome.class)); + averagePutTime = new Jsr107LatencyMonitor<>(allOf(PutOutcome.class), 1.0); put.addDerivedStatistic(averagePutTime); - averageRemoveTime = new LatencyMonitor<>(allOf(CacheOperationOutcomes.RemoveOutcome.class)); + averageRemoveTime = new Jsr107LatencyMonitor<>(allOf(RemoveOutcome.class), 1.0); remove.addDerivedStatistic(averageRemoveTime); String[] tierNames = findTiers(cache); @@ -87,6 +96,13 @@ public DefaultCacheStatistics(InternalCache cache) { String lowestTierName = findLowestTier(tierNames); TierStatistics lowestTier = null; + latencyHistory = new MaximumLatencyHistory( + configuration.getLatencyHistorySize(), + configuration.getLatencyHistoryWindowInterval(), + configuration.getLatencyHistoryWindowUnit(), + timeSource::getTimeMillis); + get.addDerivedStatistic(new OperationResultFilter<>(EnumSet.of(GetOutcome.HIT, GetOutcome.MISS), latencyHistory)); + tierStatistics = new HashMap<>(tierNames.length); for (String tierName : tierNames) { TierStatistics tierStatistics = new DefaultTierStatistics(cache, tierName); @@ -108,6 +124,7 @@ private Map> createKnownStatistics() { knownStatistics.put("Cache:RemovalCount", counter(this::getCacheRemovals)); knownStatistics.put("Cache:EvictionCount", counter(this::getCacheEvictions)); knownStatistics.put("Cache:ExpirationCount", counter(this::getCacheExpirations)); + knownStatistics.put("Cache:GetLatency", latencyHistory); for (TierStatistics tier : tierStatistics.values()) { knownStatistics.putAll(tier.getKnownStatistics()); @@ -161,25 +178,24 @@ public float getCacheMissPercentage() { @Override public long getCacheGets() { - return normalize(getHits() + getMisses() - - compensatingCounters.cacheGets); + return normalize(getHits() + getMisses() - compensatingCounters.cacheGets); } @Override public long getCachePuts() { return normalize(getBulkCount(BulkOps.PUT_ALL) + - put.sum(EnumSet.of(CacheOperationOutcomes.PutOutcome.PUT)) + - putIfAbsent.sum(EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.PUT)) + - replace.sum(EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.HIT)) - - compensatingCounters.cachePuts); + put.sum(EnumSet.of(PutOutcome.PUT)) + + putIfAbsent.sum(EnumSet.of(PutIfAbsentOutcome.PUT)) + + replace.sum(EnumSet.of(ReplaceOutcome.HIT)) - + compensatingCounters.cachePuts); } @Override public long getCacheRemovals() { return normalize(getBulkCount(BulkOps.REMOVE_ALL) + - remove.sum(EnumSet.of(CacheOperationOutcomes.RemoveOutcome.SUCCESS)) + - conditionalRemove.sum(EnumSet.of(CacheOperationOutcomes.ConditionalRemoveOutcome.SUCCESS)) - - compensatingCounters.cacheRemovals); + remove.sum(EnumSet.of(RemoveOutcome.SUCCESS)) + + conditionalRemove.sum(EnumSet.of(ConditionalRemoveOutcome.SUCCESS)) - + compensatingCounters.cacheRemovals); } @Override @@ -194,33 +210,38 @@ public long getCacheExpirations() { @Override public float getCacheAverageGetTime() { - return (float) averageGetTime.value(); + return (float) averageGetTime.average(); } @Override public float getCacheAveragePutTime() { - return (float) averagePutTime.value(); + return (float) averagePutTime.average(); } @Override public float getCacheAverageRemoveTime() { - return (float) averageRemoveTime.value(); + return (float) averageRemoveTime.average(); + } + + @Override + public SampledStatistic getCacheGetLatencyHistory() { + return latencyHistory; } private long getMisses() { return getBulkCount(BulkOps.GET_ALL_MISS) + - get.sum(EnumSet.of(CacheOperationOutcomes.GetOutcome.MISS)) + - putIfAbsent.sum(EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.PUT)) + - replace.sum(EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.MISS_NOT_PRESENT)) + - conditionalRemove.sum(EnumSet.of(CacheOperationOutcomes.ConditionalRemoveOutcome.FAILURE_KEY_MISSING)); + get.sum(EnumSet.of(GetOutcome.MISS)) + + putIfAbsent.sum(EnumSet.of(PutIfAbsentOutcome.PUT)) + + replace.sum(EnumSet.of(ReplaceOutcome.MISS_NOT_PRESENT)) + + conditionalRemove.sum(EnumSet.of(ConditionalRemoveOutcome.FAILURE_KEY_MISSING)); } private long getHits() { return getBulkCount(BulkOps.GET_ALL_HITS) + - get.sum(EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)) + - putIfAbsent.sum(EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.HIT)) + - replace.sum(EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.HIT, CacheOperationOutcomes.ReplaceOutcome.MISS_PRESENT)) + - conditionalRemove.sum(EnumSet.of(CacheOperationOutcomes.ConditionalRemoveOutcome.SUCCESS, CacheOperationOutcomes.ConditionalRemoveOutcome.FAILURE_KEY_PRESENT)); + get.sum(EnumSet.of(GetOutcome.HIT)) + + putIfAbsent.sum(EnumSet.of(PutIfAbsentOutcome.HIT)) + + replace.sum(EnumSet.of(ReplaceOutcome.HIT, ReplaceOutcome.MISS_PRESENT)) + + conditionalRemove.sum(EnumSet.of(ConditionalRemoveOutcome.SUCCESS, ConditionalRemoveOutcome.FAILURE_KEY_PRESENT)); } private long getBulkCount(BulkOps bulkOps) { @@ -267,47 +288,4 @@ CompensatingCounters snapshot(DefaultCacheStatistics statistics) { } } - private static class LatencyMonitor> implements ChainedOperationObserver { - - private final LatencySampling sampling; - private volatile MinMaxAverage average; - - public LatencyMonitor(Set targets) { - this.sampling = new LatencySampling<>(targets, 1.0); - this.average = new MinMaxAverage(); - sampling.addDerivedStatistic(average); - } - - @Override - public void begin(long time) { - sampling.begin(time); - } - - @Override - public void end(long time, T result) { - sampling.end(time, result); - } - - @Override - public void end(long time, T result, long... parameters) { - sampling.end(time, result, parameters); - } - - public double value() { - Double value = average.mean(); - if (value == null) { - //Someone involved with 107 can't do math - return 0; - } else { - //We use nanoseconds, 107 uses microseconds - return value / 1000f; - } - } - - public synchronized void clear() { - sampling.removeDerivedStatistic(average); - average = new MinMaxAverage(); - sampling.addDerivedStatistic(average); - } - } } diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsService.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsService.java index dfc9bb306b..f6a37c39d5 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsService.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsService.java @@ -23,7 +23,10 @@ import org.ehcache.core.events.CacheManagerListener; import org.ehcache.core.spi.service.CacheManagerProviderService; import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.service.StatisticsServiceConfiguration; import org.ehcache.core.spi.store.InternalCacheManager; +import org.ehcache.core.spi.time.TimeSource; +import org.ehcache.core.spi.time.TimeSourceService; import org.ehcache.core.statistics.CacheStatistics; import org.ehcache.spi.service.Service; import org.ehcache.spi.service.ServiceDependencies; @@ -32,22 +35,38 @@ import org.slf4j.LoggerFactory; import java.util.Map; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; /** * Default implementation using the statistics calculated by the observers set on the caches. */ -@ServiceDependencies(CacheManagerProviderService.class) +@ServiceDependencies({CacheManagerProviderService.class, TimeSourceService.class}) public class DefaultStatisticsService implements StatisticsService, CacheManagerListener { private static final Logger LOGGER = LoggerFactory.getLogger(DefaultStatisticsService.class); + private final StatisticsServiceConfiguration configuration; private final ConcurrentMap cacheStatistics = new ConcurrentHashMap<>(); private volatile InternalCacheManager cacheManager; + private volatile TimeSource timeSource; private volatile boolean started = false; + public DefaultStatisticsService() { + this(new DefaultStatisticsServiceConfiguration()); + } + + public DefaultStatisticsService(StatisticsServiceConfiguration configuration) { + this.configuration = Objects.requireNonNull(configuration); + } + + @Override + public StatisticsServiceConfiguration getConfiguration() { + return configuration; + } + public CacheStatistics getCacheStatistics(String cacheName) { CacheStatistics stats = cacheStatistics.get(cacheName); if (stats == null) { @@ -63,9 +82,14 @@ public boolean isStarted() { @Override public void start(ServiceProvider serviceProvider) { LOGGER.debug("Starting service"); + + TimeSourceService timeSourceService = serviceProvider.getService(TimeSourceService.class); + timeSource = timeSourceService.getTimeSource(); + CacheManagerProviderService cacheManagerProviderService = serviceProvider.getService(CacheManagerProviderService.class); cacheManager = cacheManagerProviderService.getCacheManager(); cacheManager.registerListener(this); + started = true; } @@ -80,7 +104,7 @@ public void stop() { @Override public void stateTransition(Status from, Status to) { LOGGER.debug("Moving from " + from + " to " + to); - switch(to) { + switch (to) { case AVAILABLE: registerAllCaches(); break; @@ -107,7 +131,7 @@ private void registerAllCaches() { @Override public void cacheAdded(String alias, Cache cache) { LOGGER.debug("Cache added " + alias); - cacheStatistics.put(alias, new DefaultCacheStatistics((InternalCache) cache)); + cacheStatistics.put(alias, new DefaultCacheStatistics((InternalCache) cache, configuration, timeSource)); } @Override diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfiguration.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfiguration.java new file mode 100644 index 0000000000..c4656f336a --- /dev/null +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfiguration.java @@ -0,0 +1,91 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.impl.internal.statistics; + +import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.service.StatisticsServiceConfiguration; + +import java.util.concurrent.TimeUnit; + +public class DefaultStatisticsServiceConfiguration implements StatisticsServiceConfiguration { + + private long latencyHistoryWindow = 500; + private TimeUnit latencyHistoryWindowUnit = TimeUnit.MILLISECONDS; + private int latencyHistorySize = 60 * 60 * 1_000 / (int) latencyHistoryWindow; // which is equivalent to 1-hour history + + @Override + public long getLatencyHistoryWindowInterval() { + return latencyHistoryWindow; + } + + @Override + public TimeUnit getLatencyHistoryWindowUnit() { + return latencyHistoryWindowUnit; + } + + @Override + public int getLatencyHistorySize() { + return latencyHistorySize; + } + + /** + * The interval used to aggregate the latencies of Ehcache operations to create one latency sample. + * Aggregation is done by keeping the maximum value that has been seen. + * A low value (i.e. 500ms) gives more precision but more overhead. + *

+ * Default value is 500ms. + * + * @param duration Duration of the window + * @param unit Duration unit + * @return this + */ + public DefaultStatisticsServiceConfiguration withLatencyHistoryWindow(long duration, TimeUnit unit) { + if (duration <= 0) { + throw new IllegalArgumentException("Window must be a positive integer"); + } + this.latencyHistoryWindow = duration; + this.latencyHistoryWindowUnit = unit; + return this; + } + + /** + * Maximum number of latency samples kept history. + * A sample is the maximum latency value seen over the configured window time. + * So supposing that we have constantly get operations, the history will cover + * a minimal time frame equivalent to the history size multiplied by the latency + * window duration. + *

+ * Default value is 7200. This means that there will be at least a 1-hour history + * in the case where there are constant {@link org.ehcache.Cache#get(Object)} calls + * in Ehcache with a sample window of 500ms, because 2 samples will be generated per second. + * + * @param size maximum history size + * @return this + */ + public DefaultStatisticsServiceConfiguration withLatencyHistorySize(int size) { + if (size <= 0) { + throw new IllegalArgumentException("Latency history size must be a positive integer"); + } + this.latencyHistorySize = size; + return this; + } + + @Override + public Class getServiceType() { + return StatisticsService.class; + } + +} diff --git a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactory.java b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactory.java index 2e8aaf561d..d4822b4bce 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactory.java +++ b/impl/src/main/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactory.java @@ -18,13 +18,21 @@ import org.ehcache.core.spi.service.ServiceFactory; import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.service.StatisticsServiceConfiguration; import org.ehcache.spi.service.ServiceCreationConfiguration; public class DefaultStatisticsServiceFactory implements ServiceFactory { @Override - public StatisticsService create(ServiceCreationConfiguration serviceConfiguration) { - return new DefaultStatisticsService(); + public StatisticsService create(ServiceCreationConfiguration configuration) { + if (configuration != null && !(configuration instanceof StatisticsServiceConfiguration)) { + throw new IllegalArgumentException("Expected a configuration of type StatisticsServiceConfiguration but got " + configuration.getClass().getSimpleName()); + } + if (configuration == null) { + // configuring this service is optional + configuration = new DefaultStatisticsServiceConfiguration(); + } + return new DefaultStatisticsService((StatisticsServiceConfiguration) configuration); } @Override diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java index 8fbdcef5b8..9cc29b44b9 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultCacheStatisticsTest.java @@ -20,19 +20,34 @@ import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheEventListenerConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.InternalCache; +import org.ehcache.event.CacheEvent; +import org.ehcache.event.CacheEventListener; +import org.ehcache.event.EventType; import org.ehcache.impl.internal.TimeSourceConfiguration; import org.ehcache.internal.TestTimeSource; +import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.terracotta.statistics.Sample; +import org.terracotta.statistics.SampledStatistic; import java.time.Duration; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.concurrent.atomic.AtomicLong; +import static java.lang.Thread.sleep; +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.NANOSECONDS; import static org.assertj.core.api.Assertions.assertThat; -import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; +import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; public class DefaultCacheStatisticsTest { @@ -41,14 +56,42 @@ public class DefaultCacheStatisticsTest { private DefaultCacheStatistics cacheStatistics; private CacheManager cacheManager; private InternalCache cache; - private TestTimeSource timeSource = new TestTimeSource(System.currentTimeMillis()); + private final TestTimeSource timeSource = new TestTimeSource(System.currentTimeMillis()); + private final AtomicLong latency = new AtomicLong(); + private final List> expirations = new ArrayList<>(); + private final Map sor = new HashMap<>(); @Before public void before() { + CacheEventListenerConfigurationBuilder cacheEventListenerConfiguration = CacheEventListenerConfigurationBuilder + .newEventListenerConfiguration((CacheEventListener) expirations::add, EventType.EXPIRED) + .unordered() + .synchronous(); + + // We need a loaderWriter to easily test latencies, to simulate a latency when loading from a SOR. + CacheLoaderWriter loaderWriter = new CacheLoaderWriter() { + @Override + public String load(Long key) throws Exception { + sleep(latency.get()); // latency simulation + return sor.get(key); + } + + @Override + public void write(Long key, String value) { + sor.put(key, value); + } + + @Override + public void delete(Long key) { + sor.remove(key); + } + }; + CacheConfiguration cacheConfiguration = - CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, - newResourcePoolsBuilder().heap(10)) + CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, heap(10)) + .withLoaderWriter(loaderWriter) .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofMillis(TIME_TO_EXPIRATION))) + .add(cacheEventListenerConfiguration) .build(); cacheManager = CacheManagerBuilder.newCacheManagerBuilder() @@ -58,7 +101,9 @@ public void before() { cache = (InternalCache) cacheManager.getCache("aCache", Long.class, String.class); - cacheStatistics = new DefaultCacheStatistics(cache); + cacheStatistics = new DefaultCacheStatistics(cache, new DefaultStatisticsServiceConfiguration() + .withLatencyHistorySize(2) + .withLatencyHistoryWindow(400, MILLISECONDS), timeSource); } @After @@ -74,7 +119,7 @@ public void getKnownStatistics() { "Cache:RemovalCount", "Cache:EvictionCount", "Cache:PutCount", "OnHeap:ExpirationCount", "Cache:ExpirationCount", "OnHeap:HitCount", "OnHeap:MissCount", "OnHeap:PutCount", "OnHeap:RemovalCount", "OnHeap:EvictionCount", - "OnHeap:MappingCount"); + "OnHeap:MappingCount", "Cache:GetLatency"); } @Test @@ -138,8 +183,11 @@ public void getCacheEvictions() throws Exception { @Test public void getExpirations() throws Exception { cache.put(1L, "a"); + assertThat(expirations).isEmpty(); timeSource.advanceTime(TIME_TO_EXPIRATION); - assertThat(cache.get(1L)).isNull(); + assertThat(cache.get(1L)).isEqualTo("a"); + assertThat(expirations).hasSize(1); + assertThat(expirations.get(0).getKey()).isEqualTo(1L); assertThat(cacheStatistics.getCacheExpirations()).isEqualTo(1L); assertStat("Cache:ExpirationCount").isEqualTo(1L); } @@ -162,6 +210,56 @@ public void getCacheAverageRemoveTime() throws Exception { assertThat(cacheStatistics.getCacheAverageRemoveTime()).isGreaterThan(0); } + @Test + public void getCacheGetLatencyHistory() throws Exception { + sor.put(1L, "a"); + sor.put(2L, "b"); + sor.put(3L, "c"); + sor.put(4L, "d"); + sor.put(5L, "e"); + + SampledStatistic latencyHistory = cacheStatistics.getCacheGetLatencyHistory(); + List> history = latencyHistory.history(); + assertThat(history).isEmpty(); + + latency.set(100); + cache.get(1L); + + latency.set(50); + cache.get(2L); + + history = latencyHistory.history(); + assertThat(history).hasSize(1); + assertThat(history.get(0).getSample()).isGreaterThanOrEqualTo(nanos(100L)); + + sleep(300); // next window + + latency.set(50); + cache.get(3L); + + latency.set(150); + cache.get(4L); + + history = latencyHistory.history(); + assertThat(history).hasSize(2); + assertThat(history.get(0).getSample()).isGreaterThanOrEqualTo(nanos(100L)); + assertThat(history.get(1).getSample()).isGreaterThanOrEqualTo(nanos(150L)); + + sleep(300); // next window, first sample it discarded since history size is 2 + + latency.set(200); + cache.get(5L); + + history = latencyHistory.history(); + assertThat(history).hasSize(2); + assertThat(history.get(0).getSample()).isGreaterThanOrEqualTo(nanos(150L)); + assertThat(history.get(1).getSample()).isGreaterThanOrEqualTo(nanos(200L)); + } + + private long nanos(long millis) { + return NANOSECONDS.convert(millis, MILLISECONDS); + } + private AbstractObjectAssert assertStat(String key) { return assertThat((Number) cacheStatistics.getKnownStatistics().get(key).value()); } diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfigurationTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfigurationTest.java new file mode 100644 index 0000000000..867a469e0c --- /dev/null +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceConfigurationTest.java @@ -0,0 +1,64 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.impl.internal.statistics; + +import org.ehcache.core.spi.service.StatisticsService; +import org.junit.Test; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Mathieu Carbou + */ +public class DefaultStatisticsServiceConfigurationTest { + + DefaultStatisticsServiceConfiguration configuration = new DefaultStatisticsServiceConfiguration(); + + @Test + public void getLatencyHistoryWindowInterval() { + assertThat(configuration.getLatencyHistoryWindowInterval()).isEqualTo(500L); + } + + @Test + public void getLatencyHistoryWindowUnit() { + assertThat(configuration.getLatencyHistoryWindowUnit()).isEqualTo(MILLISECONDS); + } + + @Test + public void getLatencyHistorySize() { + assertThat(configuration.getLatencyHistorySize()).isEqualTo(7200); + } + + @Test + public void withLatencyHistoryWindow() { + configuration.withLatencyHistoryWindow(1, SECONDS); + assertThat(configuration.getLatencyHistoryWindowInterval()).isEqualTo(1L); + assertThat(configuration.getLatencyHistoryWindowUnit()).isEqualTo(SECONDS); + } + + @Test + public void withLatencyHistorySize() { + configuration.withLatencyHistorySize(60); + assertThat(configuration.getLatencyHistorySize()).isEqualTo(60); + } + + @Test + public void getServiceType() { + assertThat(configuration.getServiceType()).isEqualTo(StatisticsService.class); + } +} diff --git a/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactoryTest.java b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactoryTest.java new file mode 100644 index 0000000000..73daccb0e5 --- /dev/null +++ b/impl/src/test/java/org/ehcache/impl/internal/statistics/DefaultStatisticsServiceFactoryTest.java @@ -0,0 +1,61 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.impl.internal.statistics; + +import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.service.StatisticsServiceConfiguration; +import org.junit.Test; + +import java.util.concurrent.TimeUnit; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Mathieu Carbou + */ +public class DefaultStatisticsServiceFactoryTest { + + private final DefaultStatisticsServiceFactory factory = new DefaultStatisticsServiceFactory(); + + @Test + public void createNoConfig() { + StatisticsServiceConfiguration configuration = new DefaultStatisticsServiceConfiguration(); + StatisticsService statisticsService = factory.create(null); + assertThat(statisticsService.getConfiguration().getLatencyHistorySize()).isEqualTo(configuration.getLatencyHistorySize()); + assertThat(statisticsService.getConfiguration().getLatencyHistoryWindowInterval()).isEqualTo(configuration.getLatencyHistoryWindowInterval()); + assertThat(statisticsService.getConfiguration().getLatencyHistoryWindowUnit()).isEqualTo(configuration.getLatencyHistoryWindowUnit()); + } + + @Test + public void createWithConfig() { + StatisticsService statisticsService = factory.create(new DefaultStatisticsServiceConfiguration() + .withLatencyHistorySize(1) + .withLatencyHistoryWindow(1, TimeUnit.SECONDS)); + assertThat(statisticsService.getConfiguration().getLatencyHistorySize()).isEqualTo(1); + assertThat(statisticsService.getConfiguration().getLatencyHistoryWindowInterval()).isEqualTo(1L); + assertThat(statisticsService.getConfiguration().getLatencyHistoryWindowUnit()).isEqualTo(TimeUnit.SECONDS); + } + + @Test(expected = IllegalArgumentException.class) + public void createWithBadConfig() { + factory.create(() -> StatisticsService.class); + } + + @Test + public void getServiceType() { + assertThat(factory.getServiceType()).isEqualTo(StatisticsService.class); + } +} diff --git a/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java b/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java index 70c43c83bd..b4e8ec5711 100644 --- a/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java +++ b/management/src/main/java/org/ehcache/management/providers/statistics/StandardEhcacheStatistics.java @@ -23,12 +23,8 @@ import org.ehcache.management.providers.ExposedCacheBinding; import org.terracotta.management.model.capabilities.descriptors.StatisticDescriptor; import org.terracotta.management.registry.collect.StatisticRegistry; -import org.terracotta.statistics.registry.Statistic; -import java.io.Serializable; import java.util.Collection; -import java.util.Map; -import java.util.Optional; public class StandardEhcacheStatistics extends ExposedCacheBinding { @@ -43,14 +39,6 @@ public class StandardEhcacheStatistics extends ExposedCacheBinding { cacheStatistics.getKnownStatistics().forEach(statisticRegistry::registerStatistic); } - public Optional> queryStatistic(String fullStatisticName) { - return statisticRegistry.queryStatistic(fullStatisticName); - } - - public Map> queryStatistics() { - return statisticRegistry.queryStatistics(); - } - @Override public Collection getDescriptors() { return statisticRegistry.getDescriptors(); diff --git a/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java b/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java index 3deea5fedd..ecc4ade821 100644 --- a/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java +++ b/management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java @@ -445,5 +445,6 @@ public static void loadStatsUtil() throws ClassNotFoundException { CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:RemovalCount", "COUNTER")); CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:EvictionCount", "COUNTER")); CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:ExpirationCount", "COUNTER")); + CACHE_DESCRIPTORS.add(new StatisticDescriptor("Cache:GetLatency", "GAUGE")); } } From 28b360030c185f965ebad9bfbc77ae047885d1d7 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Mon, 29 Jan 2018 15:23:48 +0530 Subject: [PATCH 115/779] lease test #2197 --- .../java/org/ehcache/clustered/LeaseTest.java | 176 ++++++++++++++++++ 1 file changed, 176 insertions(+) create mode 100644 clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java new file mode 100644 index 0000000000..82eeef756b --- /dev/null +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java @@ -0,0 +1,176 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.clustered; + +import com.tc.net.proxy.TCPProxy; +import org.ehcache.Cache; +import org.ehcache.PersistentCacheManager; +import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder; +import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder; +import org.ehcache.config.CacheConfiguration; +import org.ehcache.config.builders.CacheConfigurationBuilder; +import org.ehcache.config.builders.CacheManagerBuilder; +import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.config.units.MemoryUnit; +import org.junit.After; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.terracotta.testing.common.PortChooser; +import org.terracotta.testing.rules.Cluster; + +import java.io.File; +import java.net.InetAddress; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import static org.hamcrest.Matchers.equalTo; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.terracotta.testing.rules.BasicExternalClusterBuilder.newCluster; + +public class LeaseTest extends ClusteredTests { + private static final String STRIPE_SEPARATOR = ","; + + private static final String RESOURCE_CONFIG = + "" + + "" + + "64" + + "" + + "\n"; + + @ClassRule + public static Cluster CLUSTER = + newCluster().in(new File("build/cluster")).withServiceFragment(RESOURCE_CONFIG).build(); + + private final List proxies = new ArrayList<>(); + + @BeforeClass + public static void waitForActive() throws Exception { + CLUSTER.getClusterControl().waitForActive(); + } + + @After + public void after() { + proxies.forEach(TCPProxy::stop); + } + + @Test + public void leaseExpiry() throws Exception { + URI connectionURI = getProxyURI(); + + final CacheManagerBuilder clusteredCacheManagerBuilder + = CacheManagerBuilder.newCacheManagerBuilder() + .with(ClusteringServiceConfigurationBuilder.cluster(connectionURI.resolve("/crud-cm")) + .autoCreate() + .defaultServerResource("primary-server-resource")); + final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); + cacheManager.init(); + + try { + CacheConfiguration config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, + ResourcePoolsBuilder.newResourcePoolsBuilder() + .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB))).build(); + + Cache cache = cacheManager.createCache("clustered-cache", config); + cache.put(1L, "The one"); + cache.put(2L, "The two"); + cache.put(3L, "The three"); + assertThat(cache.get(1L), equalTo("The one")); + assertThat(cache.get(2L), equalTo("The two")); + assertThat(cache.get(3L), equalTo("The three")); + + setDelay(6000); + Thread.sleep(6000); + // We will now have lost the lease + + setDelay(0L); + + assertThat(cache.get(1L), is(nullValue())); + assertThat(cache.get(2L), is(nullValue())); + assertThat(cache.get(3L), is(nullValue())); + } finally { + cacheManager.close(); + } + + } + + private void setDelay(long delay) { + for (TCPProxy proxy : proxies) { + proxy.setDelay(delay); + } + } + + private URI getProxyURI() throws Exception { + URI connectionURI = CLUSTER.getConnectionURI(); + + List ports = parsePorts(connectionURI); + List proxyPorts = createProxyPorts(ports.size()); + + for (int i = 0; i < ports.size(); i++) { + int port = ports.get(i); + int proxyPort = proxyPorts.get(i); + + InetAddress host = InetAddress.getByName("localhost"); + TCPProxy proxy = new TCPProxy(proxyPort, host, port, 0L, false, null); + proxies.add(proxy); + proxy.start(); + } + + return createURI(proxyPorts); + } + + private List parsePorts(URI connectionURI) { + String uriString = connectionURI.toString(); + String withoutProtocol = uriString.substring(13); + String[] stripes = withoutProtocol.split(STRIPE_SEPARATOR); + + List ports = new ArrayList<>(stripes.length); + for (String stripe : stripes) { + String portString = stripe.substring(stripe.indexOf(":") + 1); + int port = Integer.parseInt(portString); + ports.add(port); + } + + return ports; + } + + private List createProxyPorts(int portCount) { + PortChooser portChooser = new PortChooser(); + int firstProxyPort = portChooser.chooseRandomPorts(portCount); + + List proxyPorts = new ArrayList<>(portCount); + for (int i = 0; i < portCount; i++) { + proxyPorts.add(firstProxyPort + i); + } + + return proxyPorts; + } + + private URI createURI(List proxyPorts) { + List stripes = new ArrayList<>(); + + for (int proxyPort : proxyPorts) { + String stripe = "localhost:" + proxyPort; + stripes.add(stripe); + } + + String uri = "terracotta://" + String.join(STRIPE_SEPARATOR, stripes); + return URI.create(uri); + } +} \ No newline at end of file From fb24c55e9e9cebc31b792f015501c0dc8dd6f1c2 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Mon, 29 Jan 2018 18:37:46 +0530 Subject: [PATCH 116/779] Lease test & proper invalidation wiring #2197 --- .../store/ClusterTierClientEntity.java | 2 +- .../store/CommonServerStoreProxy.java | 2 + .../store/SimpleClusterTierClientEntity.java | 16 +-- .../store/StrongServerStoreProxy.java | 2 +- .../service/ConnectionClosedTest.java | 7 +- .../java/org/ehcache/clustered/LeaseTest.java | 122 ++++++++++-------- 6 files changed, 85 insertions(+), 66 deletions(-) diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusterTierClientEntity.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusterTierClientEntity.java index b335f247b9..dad2f36924 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusterTierClientEntity.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusterTierClientEntity.java @@ -51,7 +51,7 @@ public interface ClusterTierClientEntity extends Entity { void addResponseListener(Class responseType, ResponseListener responseListener); - void setDisconnectionListener(DisconnectionListener disconnectionListener); + void addDisconnectionListener(DisconnectionListener disconnectionListener); void setReconnectListener(ReconnectListener reconnectListener); diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java index fee33da8d4..1d70c45ed9 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java @@ -52,6 +52,8 @@ class CommonServerStoreProxy implements ServerStoreProxy { this.entity = requireNonNull(entity, "ClusterTierClientEntity must be non-null"); requireNonNull(invalidation, "ServerCallback must be non-null"); + entity.addDisconnectionListener(invalidation::onInvalidateAll); + entity.addResponseListener(ServerInvalidateHash.class, response -> { long key = response.getKey(); LOGGER.debug("CLIENT: on cache {}, server requesting hash {} to be invalidated", cacheId, key); diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java index 8a2fab038c..c1ff9661f8 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/SimpleClusterTierClientEntity.java @@ -43,6 +43,7 @@ import org.terracotta.exception.EntityException; import java.time.Duration; +import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Map; @@ -69,18 +70,16 @@ public class SimpleClusterTierClientEntity implements InternalClusterTierClientE private final ReconnectMessageCodec reconnectMessageCodec = new ReconnectMessageCodec(); private final Map, List>> responseListeners = new ConcurrentHashMap<>(); + private final List disconnectionListeners = new CopyOnWriteArrayList<>(); private ReconnectListener reconnectListener = reconnectMessage -> { // No op }; - private DisconnectionListener disconnectionListener = () -> { - // No op - }; + private Timeouts timeouts = TimeoutsBuilder.timeouts().build(); private String storeIdentifier; private volatile boolean connected = true; - public SimpleClusterTierClientEntity(EntityClientEndpoint endpoint) { this.endpoint = endpoint; this.messageFactory = new LifeCycleMessageFactory(); @@ -102,6 +101,7 @@ public byte[] createExtendedReconnectData() { @Override public void didDisconnectUnexpectedly() { + LOGGER.info("Cluster tier for cache {} disconnected", storeIdentifier); fireDisconnectionEvent(); } }); @@ -114,7 +114,7 @@ public void setTimeouts(Timeouts timeouts) { void fireDisconnectionEvent() { connected = false; - disconnectionListener.onDisconnection(); + disconnectionListeners.forEach(DisconnectionListener::onDisconnection); } private void fireResponseEvent(T response) { @@ -134,7 +134,7 @@ private void fireResponseEvent(T response) { public void close() { endpoint.close(); reconnectListener = null; - disconnectionListener = null; + disconnectionListeners.clear(); } @Override @@ -148,8 +148,8 @@ public void setReconnectListener(ReconnectListener reconnectListener) { } @Override - public void setDisconnectionListener(DisconnectionListener disconnectionListener) { - this.disconnectionListener = disconnectionListener; + public void addDisconnectionListener(DisconnectionListener disconnectionListener) { + this.disconnectionListeners.add(disconnectionListener); } @Override diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/StrongServerStoreProxy.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/StrongServerStoreProxy.java index 8a5b576e39..1ecc5cc694 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/StrongServerStoreProxy.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/StrongServerStoreProxy.java @@ -51,7 +51,7 @@ public StrongServerStoreProxy(final String cacheId, final ClusterTierClientEntit delegate.addResponseListener(EhcacheEntityResponse.AllInvalidationDone.class, this::allInvalidationDoneResponseListener); entity.setReconnectListener(this::reconnectListener); - entity.setDisconnectionListener(this::disconnectionListener); + entity.addDisconnectionListener(this::disconnectionListener); } private void disconnectionListener() { diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java index 532e7b0243..a7e1d63e35 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/service/ConnectionClosedTest.java @@ -46,6 +46,7 @@ import static org.ehcache.config.builders.CacheManagerBuilder.newCacheManagerBuilder; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; @RunWith(Parameterized.class) @@ -120,11 +121,7 @@ public void testCacheOperationThrowsAfterConnectionClosed() throws Exception { connection.close(); - try { - cache.get(1L); - } catch (Exception e) { - assertThat(e.getCause().getCause(), instanceOf(ConnectionClosedException.class)); - } + assertThat(cache.get(1L), nullValue()); } diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java index 82eeef756b..c8bab2fbba 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/LeaseTest.java @@ -18,32 +18,42 @@ import com.tc.net.proxy.TCPProxy; import org.ehcache.Cache; import org.ehcache.PersistentCacheManager; -import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder; import org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder; +import org.ehcache.clustered.client.config.builders.TimeoutsBuilder; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; +import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; import org.junit.After; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; import org.terracotta.testing.common.PortChooser; import org.terracotta.testing.rules.Cluster; import java.io.File; import java.net.InetAddress; import java.net.URI; +import java.time.Duration; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import static org.terracotta.testing.rules.BasicExternalClusterBuilder.newCluster; +@RunWith(Parameterized.class) public class LeaseTest extends ClusteredTests { private static final String STRIPE_SEPARATOR = ","; @@ -51,8 +61,13 @@ public class LeaseTest extends ClusteredTests { "" + "" + "64" - + "" + - "\n"; + + "" + + "\n" + + "" + + "" + + "1" + + "" + + ""; @ClassRule public static Cluster CLUSTER = @@ -70,43 +85,54 @@ public void after() { proxies.forEach(TCPProxy::stop); } + @Parameterized.Parameters + public static ResourcePoolsBuilder[] data() { + return new ResourcePoolsBuilder[]{ + ResourcePoolsBuilder.newResourcePoolsBuilder() + .with(clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)), + ResourcePoolsBuilder.newResourcePoolsBuilder() + .heap(10, EntryUnit.ENTRIES) + .with(clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB)) + }; + } + + @Parameterized.Parameter + public ResourcePoolsBuilder resourcePoolsBuilder; + @Test public void leaseExpiry() throws Exception { URI connectionURI = getProxyURI(); - final CacheManagerBuilder clusteredCacheManagerBuilder + CacheManagerBuilder clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() .with(ClusteringServiceConfigurationBuilder.cluster(connectionURI.resolve("/crud-cm")) + .timeouts(TimeoutsBuilder.timeouts() + .connection(Duration.ofSeconds(20))) .autoCreate() .defaultServerResource("primary-server-resource")); - final PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); + PersistentCacheManager cacheManager = clusteredCacheManagerBuilder.build(false); cacheManager.init(); - try { - CacheConfiguration config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, - ResourcePoolsBuilder.newResourcePoolsBuilder() - .with(ClusteredResourcePoolBuilder.clusteredDedicated("primary-server-resource", 1, MemoryUnit.MB))).build(); - - Cache cache = cacheManager.createCache("clustered-cache", config); - cache.put(1L, "The one"); - cache.put(2L, "The two"); - cache.put(3L, "The three"); - assertThat(cache.get(1L), equalTo("The one")); - assertThat(cache.get(2L), equalTo("The two")); - assertThat(cache.get(3L), equalTo("The three")); - - setDelay(6000); - Thread.sleep(6000); - // We will now have lost the lease - - setDelay(0L); - - assertThat(cache.get(1L), is(nullValue())); - assertThat(cache.get(2L), is(nullValue())); - assertThat(cache.get(3L), is(nullValue())); - } finally { - cacheManager.close(); - } + CacheConfiguration config = CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class, + resourcePoolsBuilder).build(); + + Cache cache = cacheManager.createCache("clustered-cache", config); + cache.put(1L, "The one"); + cache.put(2L, "The two"); + cache.put(3L, "The three"); + assertThat(cache.get(1L), equalTo("The one")); + assertThat(cache.get(2L), equalTo("The two")); + assertThat(cache.get(3L), equalTo("The three")); + + setDelay(2000); + Thread.sleep(2000); + // We will now have lost the lease + + setDelay(0L); + + assertThat(cache.get(1L), is(nullValue())); + assertThat(cache.get(2L), is(nullValue())); + assertThat(cache.get(3L), is(nullValue())); } @@ -140,37 +166,31 @@ private List parsePorts(URI connectionURI) { String withoutProtocol = uriString.substring(13); String[] stripes = withoutProtocol.split(STRIPE_SEPARATOR); - List ports = new ArrayList<>(stripes.length); - for (String stripe : stripes) { - String portString = stripe.substring(stripe.indexOf(":") + 1); - int port = Integer.parseInt(portString); - ports.add(port); - } - - return ports; + return Arrays.stream(stripes) + .map(stripe -> stripe.substring(stripe.indexOf(":") + 1)) + .mapToInt(Integer::parseInt) + .boxed() + .collect(Collectors.toList()); } private List createProxyPorts(int portCount) { PortChooser portChooser = new PortChooser(); int firstProxyPort = portChooser.chooseRandomPorts(portCount); - List proxyPorts = new ArrayList<>(portCount); - for (int i = 0; i < portCount; i++) { - proxyPorts.add(firstProxyPort + i); - } - - return proxyPorts; + return IntStream + .range(0, portCount) + .map(i -> firstProxyPort + i) + .boxed() + .collect(Collectors.toList()); } private URI createURI(List proxyPorts) { - List stripes = new ArrayList<>(); - for (int proxyPort : proxyPorts) { - String stripe = "localhost:" + proxyPort; - stripes.add(stripe); - } + Optional reduce = proxyPorts.stream() + .map(port -> "localhost:" + port) + .reduce((x1, x2) -> x1 + STRIPE_SEPARATOR + x2); - String uri = "terracotta://" + String.join(STRIPE_SEPARATOR, stripes); + String uri = "terracotta://" + reduce.get(); return URI.create(uri); } -} \ No newline at end of file +} From 691f985fdce6ba86f76aa22845984704f883be72 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Tue, 30 Jan 2018 16:37:48 +0530 Subject: [PATCH 117/779] Bump to latest passthrough & platform --- clustered/client/build.gradle | 1 + gradle.properties | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/clustered/client/build.gradle b/clustered/client/build.gradle index 1e65b1cc75..bfb654704b 100644 --- a/clustered/client/build.gradle +++ b/clustered/client/build.gradle @@ -33,6 +33,7 @@ dependencies { testCompile "org.terracotta:entity-test-lib:$terracottaPassthroughTestingVersion" testCompile "org.terracotta:passthrough-server:$terracottaPassthroughTestingVersion" testCompile "org.terracotta.internal:common:$terracottaCoreVersion" + testCompile "org.terracotta:passthrough-leased-connection-api:$terracottaPlatformVersion" } test { diff --git a/gradle.properties b/gradle.properties index fa506f6474..ce4cbb69f5 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,10 +7,10 @@ slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre16 +terracottaPlatformVersion = 5.4.0-pre17 terracottaApisVersion = 1.4.0-pre8 terracottaCoreVersion = 5.4.0-pre18 -terracottaPassthroughTestingVersion = 1.4.0-pre11 +terracottaPassthroughTestingVersion = 1.4.0-pre12 # Test lib versions junitVersion = 4.12 From 1c09582dc3d6820168079656a4daa8f750101282 Mon Sep 17 00:00:00 2001 From: Abhilash Date: Wed, 31 Jan 2018 14:37:40 +0530 Subject: [PATCH 118/779] Bump to latest platform --- gradle.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gradle.properties b/gradle.properties index ce4cbb69f5..f1d0af23c7 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,7 +7,7 @@ slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre17 +terracottaPlatformVersion = 5.4.0-pre18 terracottaApisVersion = 1.4.0-pre8 terracottaCoreVersion = 5.4.0-pre18 terracottaPassthroughTestingVersion = 1.4.0-pre12 From ffea99e8755ae536b222eb65cbc49390cbe5052e Mon Sep 17 00:00:00 2001 From: Albin Suresh Date: Thu, 1 Feb 2018 23:30:14 +0530 Subject: [PATCH 119/779] :arrow_up: Bump to latest Terracotta versions --- gradle.properties | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/gradle.properties b/gradle.properties index f1d0af23c7..76fd3d6374 100644 --- a/gradle.properties +++ b/gradle.properties @@ -7,10 +7,10 @@ slf4jVersion = 1.7.25 sizeofVersion = 0.3.0 # Terracotta clustered -terracottaPlatformVersion = 5.4.0-pre18 -terracottaApisVersion = 1.4.0-pre8 -terracottaCoreVersion = 5.4.0-pre18 -terracottaPassthroughTestingVersion = 1.4.0-pre12 +terracottaPlatformVersion = 5.4.0-pre19 +terracottaApisVersion = 1.4.0-pre9 +terracottaCoreVersion = 5.4.0-pre19 +terracottaPassthroughTestingVersion = 1.4.0-pre13 # Test lib versions junitVersion = 4.12 From d50817264ed9295e71a770ac33ba93faeaf9adba Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 13 Dec 2017 23:33:04 -0500 Subject: [PATCH 120/779] Remove StoreAccessTimeoutException --- .../client/internal/store/ClusteredStore.java | 30 +--- .../internal/store/ClusteredStoreTest.java | 56 ++++--- .../clustered/TerminatedServerTest.java | 152 +++++++----------- .../exceptions/StorePassThroughException.java | 2 +- .../store/StoreAccessTimeoutException.java | 45 ------ 5 files changed, 100 insertions(+), 185 deletions(-) delete mode 100644 core/src/main/java/org/ehcache/core/spi/store/StoreAccessTimeoutException.java diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java index 5cdcbf62ab..faac2ec53e 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java @@ -44,8 +44,6 @@ import org.ehcache.core.events.CacheEventListenerConfiguration; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.core.spi.store.StoreAccessTimeoutException; import org.ehcache.core.spi.store.events.StoreEventSource; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.core.spi.time.TimeSource; @@ -229,10 +227,8 @@ private PutStatus silentPut(final K key, final V value) throws StoreAccessExcept long extractedKey = extractLongKey(key); storeProxy.append(extractedKey, payload); return PutStatus.PUT; - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } @@ -259,10 +255,8 @@ public ValueHolder putIfAbsent(final K key, final V value) throws StoreAccess putIfAbsentObserver.end(StoreOperationOutcomes.PutIfAbsentOutcome.HIT); return new ClusteredValueHolder<>(result.getValue()); } - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } @@ -292,10 +286,8 @@ private boolean silentRemove(final K key) throws StoreAccessException { } else { return false; } - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } @@ -324,10 +316,8 @@ public RemoveStatus remove(final K key, final V value) throws StoreAccessExcepti conditionalRemoveObserver.end(StoreOperationOutcomes.ConditionalRemoveOutcome.MISS); return RemoveStatus.KEY_MISSING; } - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } @@ -354,10 +344,8 @@ public ValueHolder replace(final K key, final V value) throws StoreAccessExce replaceObserver.end(StoreOperationOutcomes.ReplaceOutcome.REPLACED); return new ClusteredValueHolder<>(result.getValue()); } - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } @@ -390,10 +378,8 @@ public ReplaceStatus replace(final K key, final V oldValue, final V newValue) th conditionalReplaceObserver.end(StoreOperationOutcomes.ConditionalReplaceOutcome.MISS); return ReplaceStatus.MISS_NOT_PRESENT; } - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } @@ -401,10 +387,8 @@ public ReplaceStatus replace(final K key, final V oldValue, final V newValue) th public void clear() throws StoreAccessException { try { storeProxy.clear(); - } catch (RuntimeException re) { + } catch (Exception re) { throw handleRuntimeException(re); - } catch (TimeoutException e) { - throw new StoreAccessTimeoutException(e); } } diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java index 99f908cc85..0df3ef37ce 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java @@ -16,6 +16,7 @@ package org.ehcache.clustered.client.internal.store; +import org.assertj.core.api.ThrowableAssert; import org.ehcache.clustered.client.TestTimeSource; import org.ehcache.clustered.client.config.ClusteredResourcePool; import org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder; @@ -32,7 +33,6 @@ import org.ehcache.core.Ehcache; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.core.spi.store.StoreAccessTimeoutException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.statistics.StoreOperationOutcomes; import org.ehcache.impl.store.HashUtils; @@ -56,6 +56,7 @@ import java.util.concurrent.TimeoutException; import java.util.function.Function; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.ehcache.clustered.client.internal.store.ClusteredStore.DEFAULT_CHAIN_COMPACTION_THRESHOLD; import static org.ehcache.clustered.client.internal.store.ClusteredStore.CHAIN_COMPACTION_THRESHOLD_PROP; import static org.ehcache.clustered.util.StatisticsTestUtils.validateStat; @@ -114,6 +115,12 @@ public void tearDown() throws Exception { UnitTestConnectionService.remove("terracotta://localhost/my-application"); } + private void assertTimeoutOccurred(ThrowableAssert.ThrowingCallable throwingCallable) { + assertThatExceptionOfType(StoreAccessException.class) + .isThrownBy(throwingCallable) + .withCauseInstanceOf(TimeoutException.class); + } + @Test public void testPut() throws Exception { assertThat(store.put(1L, "one"), is(Store.PutStatus.PUT)); @@ -123,7 +130,7 @@ public void testPut() throws Exception { validateStat(store, StoreOperationOutcomes.PutOutcome.PUT, 3); } - @Test(expected = StoreAccessTimeoutException.class) + @Test @SuppressWarnings("unchecked") public void testPutTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @@ -131,7 +138,8 @@ public void testPutTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); doThrow(TimeoutException.class).when(proxy).append(anyLong(), isNull()); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.put(1L, "one"); + + assertTimeoutOccurred(() -> store.put(1L, "one")); } @Test @@ -248,20 +256,24 @@ public void testRemove() throws Exception { validateStats(store, EnumSet.of(StoreOperationOutcomes.RemoveOutcome.MISS, StoreOperationOutcomes.RemoveOutcome.REMOVED)); } - @Test(expected = StoreAccessException.class) + @Test public void testRemoveThrowsOnlySAE() throws Exception { @SuppressWarnings("unchecked") OperationsCodec codec = mock(OperationsCodec.class); @SuppressWarnings("unchecked") EternalChainResolver chainResolver = mock(EternalChainResolver.class); ServerStoreProxy serverStoreProxy = mock(ServerStoreProxy.class); - when(serverStoreProxy.get(anyLong())).thenThrow(new RuntimeException()); - TestTimeSource testTimeSource = mock(TestTimeSource.class); + RuntimeException theException = new RuntimeException(); + when(serverStoreProxy.getAndAppend(anyLong(), any())).thenThrow(theException); + TestTimeSource testTimeSource = new TestTimeSource(); + ClusteredStore store = new ClusteredStore<>(codec, chainResolver, serverStoreProxy, testTimeSource); - store.remove(1L); + assertThatExceptionOfType(StoreAccessException.class) + .isThrownBy(() -> store.remove(1L)) + .withCause(theException); } - @Test(expected = StoreAccessTimeoutException.class) + @Test @SuppressWarnings("unchecked") public void testRemoveTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @@ -269,7 +281,8 @@ public void testRemoveTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.remove(1L); + + assertTimeoutOccurred(() -> store.remove(1L)); } @Test @@ -303,7 +316,7 @@ public void testClearThrowsOnlySAE() throws Exception { store.clear(); } - @Test(expected = StoreAccessTimeoutException.class) + @Test public void testClearTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @SuppressWarnings("unchecked") @@ -311,7 +324,8 @@ public void testClearTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); doThrow(TimeoutException.class).when(proxy).clear(); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.clear(); + + assertTimeoutOccurred(() -> store.clear()); } @Test @@ -335,7 +349,7 @@ public void testPutIfAbsentThrowsOnlySAE() throws Exception { store.putIfAbsent(1L, "one"); } - @Test(expected = StoreAccessTimeoutException.class) + @Test @SuppressWarnings("unchecked") public void testPutIfAbsentTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @@ -343,7 +357,8 @@ public void testPutIfAbsentTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.putIfAbsent(1L, "one"); + + assertTimeoutOccurred(() -> store.putIfAbsent(1L, "one")); } @Test @@ -371,7 +386,7 @@ public void testConditionalRemoveThrowsOnlySAE() throws Exception { store.remove(1L, "one"); } - @Test(expected = StoreAccessTimeoutException.class) + @Test @SuppressWarnings("unchecked") public void testConditionalRemoveTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @@ -379,7 +394,8 @@ public void testConditionalRemoveTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.remove(1L, "one"); + + assertTimeoutOccurred(() -> store.remove(1L, "one")); } @Test @@ -404,7 +420,7 @@ public void testReplaceThrowsOnlySAE() throws Exception { store.replace(1L, "one"); } - @Test(expected = StoreAccessTimeoutException.class) + @Test @SuppressWarnings("unchecked") public void testReplaceTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @@ -412,7 +428,8 @@ public void testReplaceTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.replace(1L, "one"); + + assertTimeoutOccurred(() -> store.replace(1L, "one")); } @Test @@ -441,7 +458,7 @@ public void testConditionalReplaceThrowsOnlySAE() throws Exception { store.replace(1L, "one", "another one"); } - @Test(expected = StoreAccessTimeoutException.class) + @Test @SuppressWarnings("unchecked") public void testConditionalReplaceTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); @@ -449,7 +466,8 @@ public void testConditionalReplaceTimeout() throws Exception { TimeSource timeSource = mock(TimeSource.class); when(proxy.getAndAppend(anyLong(), isNull())).thenThrow(TimeoutException.class); ClusteredStore store = new ClusteredStore<>(codec, null, proxy, timeSource); - store.replace(1L, "one", "another one"); + + assertTimeoutOccurred(() -> store.replace(1L, "one", "another one")); } @Test diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java index d5a23b64a2..f125ce8463 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java @@ -17,6 +17,8 @@ package org.ehcache.clustered; import com.google.code.tempusfugit.concurrency.ConcurrentTestRunner; + +import org.assertj.core.api.ThrowableAssertAlternative; import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.CachePersistenceException; @@ -30,8 +32,9 @@ import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.core.spi.store.StoreAccessTimeoutException; -import org.hamcrest.Matchers; +import org.ehcache.core.spi.service.StatisticsService; +import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.impl.internal.statistics.DefaultStatisticsService; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; @@ -46,7 +49,6 @@ import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runners.model.Statement; -import org.terracotta.connection.ConnectionException; import org.terracotta.testing.rules.Cluster; import com.tc.net.protocol.transport.ClientMessageTransport; @@ -57,10 +59,8 @@ import java.io.File; import java.time.Duration; import java.time.temporal.ChronoUnit; -import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; -import java.util.List; import java.util.Map; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; @@ -68,14 +68,8 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import static org.hamcrest.Matchers.containsString; -import static org.hamcrest.Matchers.hasItem; -import static org.hamcrest.Matchers.instanceOf; -import static org.hamcrest.Matchers.is; -import static org.hamcrest.Matchers.not; -import static org.hamcrest.Matchers.nullValue; -import static org.junit.Assert.assertThat; -import static org.junit.Assert.fail; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.junit.Assume.assumeNoException; import static org.terracotta.testing.rules.BasicExternalClusterBuilder.newCluster; @@ -161,6 +155,11 @@ public static void restoreProperties() { } } + private ThrowableAssertAlternative assertExceptionOccurred(Class exception, TimeLimitedTask task) { + return assertThatExceptionOfType(exception) + .isThrownBy(() -> task.run()); + } + private static Cluster createCluster() { try { return newCluster().in(new File("build/cluster")).withServiceFragment(RESOURCE_CONFIG).build(); @@ -259,18 +258,15 @@ public void testTerminationBeforeCacheManagerRetrieve() throws Exception { // Base test time limit on observed TRANSPORT_HANDSHAKE_SYNACK_TIMEOUT; might not have been set in time to be effective long synackTimeout = TimeUnit.MILLISECONDS.toSeconds(ClientMessageTransport.TRANSPORT_HANDSHAKE_SYNACK_TIMEOUT); - try { + assertExceptionOccurred(StateTransitionException.class, new TimeLimitedTask(3 + synackTimeout, TimeUnit.SECONDS) { @Override - Void runTask() throws Exception { + Void runTask() { cacheManagerExisting.init(); return null; } - }.run(); - fail("Expecting StateTransitionException"); - } catch (StateTransitionException e) { - assertThat(getCausalChain(e), hasItem(Matchers.instanceOf(ConnectionException.class))); - } + }) + .withRootCauseInstanceOf(TimeoutException.class); } @Test @@ -297,18 +293,15 @@ public void testTerminationBeforeCacheManagerDestroyCache() throws Exception { cluster.getClusterControl().terminateAllServers(); - try { + assertExceptionOccurred(CachePersistenceException.class, new TimeLimitedTask(5, TimeUnit.SECONDS) { @Override Void runTask() throws Exception { cacheManager.destroyCache("simple-cache"); return null; } - }.run(); - fail("Expecting CachePersistenceException"); - } catch (CachePersistenceException e) { - assertThat(getUltimateCause(e), is(instanceOf(TimeoutException.class))); - } + }) + .withRootCauseInstanceOf(TimeoutException.class); } @Test @@ -324,7 +317,7 @@ public void testTerminationBeforeCacheCreate() throws Exception { cluster.getClusterControl().terminateAllServers(); - try { + assertExceptionOccurred(IllegalStateException.class, new TimeLimitedTask>(5, TimeUnit.SECONDS) { @Override Cache runTask() throws Exception { @@ -333,11 +326,8 @@ Cache runTask() throws Exception { ResourcePoolsBuilder.newResourcePoolsBuilder() .with(ClusteredResourcePoolBuilder.clusteredDedicated(4, MemoryUnit.MB)))); } - }.run(); - fail("Expecting IllegalStateException"); - } catch (IllegalStateException e) { - assertThat(getUltimateCause(e), is(instanceOf(TimeoutException.class))); - } + }) + .withRootCauseInstanceOf(TimeoutException.class); } @Test @@ -387,7 +377,7 @@ public void testTerminationThenGet() throws Exception { cache.put(2L, "deux"); cache.put(3L, "trois"); - assertThat(cache.get(2L), is(not(nullValue()))); + assertThat(cache.get(2L)).isNotNull(); cluster.getClusterControl().terminateAllServers(); @@ -398,7 +388,7 @@ String runTask() throws Exception { } }.run(); - assertThat(value, is(nullValue())); + assertThat(value).isNull(); } @Test @@ -421,7 +411,7 @@ public void testTerminationThenContainsKey() throws Exception { cache.put(2L, "deux"); cache.put(3L, "trois"); - assertThat(cache.containsKey(2L), is(true)); + assertThat(cache.containsKey(2L)).isTrue(); cluster.getClusterControl().terminateAllServers(); @@ -432,7 +422,7 @@ Boolean runTask() throws Exception { } }.run(); - assertThat(value, is(false)); + assertThat(value).isFalse(); } @Ignore("ClusteredStore.iterator() is not implemented") @@ -465,7 +455,7 @@ Iterator> runTask() throws Exception { } }.run(); - assertThat(value.hasNext(), is(false)); + assertThat(value.hasNext()).isFalse(); } @Test @@ -490,19 +480,14 @@ public void testTerminationThenPut() throws Exception { cluster.getClusterControl().terminateAllServers(); - try { - new TimeLimitedTask(5, TimeUnit.SECONDS) { - @Override - Void runTask() throws Exception { - cache.put(2L, "dos"); - return null; - } - }.run(); - fail("Expecting StoreAccessTimeoutException"); - } catch (StoreAccessTimeoutException e) { - //Final timeout occurs on the cleanup which is a remove (hence a GET_AND_APPEND) - assertThat(e.getMessage(), containsString("Timeout exceeded for GET_AND_APPEND")); - } + // The resilience strategy will pick it up and not exception is thrown + new TimeLimitedTask(5, TimeUnit.SECONDS) { + @Override + Void runTask() throws Exception { + cache.put(2L, "dos"); + return null; + } + }.run(); } @Test @@ -527,17 +512,13 @@ public void testTerminationThenPutIfAbsent() throws Exception { cluster.getClusterControl().terminateAllServers(); - try { - new TimeLimitedTask(5, TimeUnit.SECONDS) { - @Override - String runTask() throws Exception { - return cache.putIfAbsent(2L, "dos"); - } - }.run(); - fail("Expecting StoreAccessTimeoutException"); - } catch (StoreAccessTimeoutException e) { - assertThat(e.getMessage(), containsString("Timeout exceeded for GET_AND_APPEND")); - } + // The resilience strategy will pick it up and not exception is thrown + new TimeLimitedTask(5, TimeUnit.SECONDS) { + @Override + String runTask() throws Exception { + return cache.putIfAbsent(2L, "dos"); + } + }.run(); } @Test @@ -562,24 +543,21 @@ public void testTerminationThenRemove() throws Exception { cluster.getClusterControl().terminateAllServers(); - try { - new TimeLimitedTask(5, TimeUnit.SECONDS) { - @Override - Void runTask() throws Exception { - cache.remove(2L); - return null; - } - }.run(); - fail("Expecting StoreAccessTimeoutException"); - } catch (StoreAccessTimeoutException e) { - assertThat(e.getMessage(), containsString("Timeout exceeded for GET_AND_APPEND")); - } + new TimeLimitedTask(5, TimeUnit.SECONDS) { + @Override + Void runTask() throws Exception { + cache.remove(2L); + return null; + } + }.run(); } @Test public void testTerminationThenClear() throws Exception { + StatisticsService statisticsService = new DefaultStatisticsService(); CacheManagerBuilder clusteredCacheManagerBuilder = CacheManagerBuilder.newCacheManagerBuilder() + .using(statisticsService) .with(ClusteringServiceConfigurationBuilder.cluster(cluster.getConnectionURI().resolve("/MyCacheManagerName")) .timeouts(TimeoutsBuilder.timeouts().write(Duration.of(1, ChronoUnit.SECONDS)).build()) .autoCreate() @@ -598,34 +576,14 @@ public void testTerminationThenClear() throws Exception { cluster.getClusterControl().terminateAllServers(); - try { - new TimeLimitedTask(5, TimeUnit.SECONDS) { + // The resilience strategy will pick it up and not exception is thrown + new TimeLimitedTask(5, TimeUnit.SECONDS) { @Override - Void runTask() throws Exception { + Void runTask() { cache.clear(); return null; } }.run(); - fail("Expecting StoreAccessTimeoutException"); - } catch (StoreAccessTimeoutException e) { - assertThat(e.getMessage(), containsString("Timeout exceeded for CLEAR")); - } - } - - private Throwable getUltimateCause(Throwable t) { - Throwable ultimateCause = t; - while (ultimateCause.getCause() != null) { - ultimateCause = ultimateCause.getCause(); - } - return ultimateCause; - } - - private List getCausalChain(Throwable t) { - ArrayList causalChain = new ArrayList<>(); - for (Throwable cause = t; cause != null; cause = cause.getCause()) { - causalChain.add(cause); - } - return causalChain; } private static void overrideProperty(Map oldProperties, String propertyName, String propertyValue) { @@ -735,7 +693,7 @@ V run() throws Exception { future.cancel(true); Thread.interrupted(); // Reset interrupted status } - assertThat(testName.getMethodName() + " test thread exceeded its time limit of " + timeLimit + " " + unit, isExpired, is(false)); + assertThat(isExpired).describedAs( "%s test thread exceeded its time limit of %d %s", testName.getMethodName(), timeLimit, unit).isFalse(); } return result; diff --git a/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java b/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java index 362d6ea606..795e464d31 100644 --- a/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java +++ b/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java @@ -66,7 +66,7 @@ public synchronized Throwable fillInStackTrace() { * @return StoreAccessException to be thrown * @throws RuntimeException if {@code re} is a {@code StorePassThroughException} containing a {@code RuntimeException} */ - public static StoreAccessException handleRuntimeException(RuntimeException re) { + public static StoreAccessException handleRuntimeException(Exception re) { if(re instanceof StorePassThroughException) { Throwable cause = re.getCause(); if(cause instanceof RuntimeException) { diff --git a/core/src/main/java/org/ehcache/core/spi/store/StoreAccessTimeoutException.java b/core/src/main/java/org/ehcache/core/spi/store/StoreAccessTimeoutException.java deleted file mode 100644 index 9bb8505616..0000000000 --- a/core/src/main/java/org/ehcache/core/spi/store/StoreAccessTimeoutException.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright Terracotta, Inc. - * - * 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 org.ehcache.core.spi.store; - -/** - * Thrown when a cache {@link Store} operation exceeds a configured time limit. - * This exception is not handled by the - * {@link org.ehcache.core.internal.resilience.ResilienceStrategy ResilienceStrategy}. - */ -public class StoreAccessTimeoutException extends RuntimeException { - private static final long serialVersionUID = 7824475930240423944L; - - /** - * Creates a new exception wrapping the {@link Throwable cause} passed in. - * - * @param cause the cause of this exception - */ - public StoreAccessTimeoutException(Throwable cause) { - super(cause); - } - - /** - * Creates a new exception wrapping the {@link Throwable cause} passed in and with the provided message. - * - * @param message information about the exception - * @param cause the cause of this exception - */ - public StoreAccessTimeoutException(String message, Throwable cause) { - super(message, cause); - } -} From 0df6f1cc8a71fc83862f5a78d823930136b2cc38 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Thu, 14 Dec 2017 15:07:52 -0500 Subject: [PATCH 121/779] Move resilience strategy to API (#2198) --- .../java/org/ehcache}/resilience/ResilienceStrategy.java | 3 +-- .../resilience/RethrowingStoreAccessException.java | 4 +--- .../org/ehcache/resilience}/StoreAccessException.java | 2 +- .../clustered/client/internal/store/ClusteredStore.java | 1 + .../client/internal/store/ClusteredStoreTest.java | 2 +- .../java/org/ehcache/clustered/TerminatedServerTest.java | 1 - .../org/ehcache/clustered/replication/DuplicateTest.java | 4 ++-- .../internal/store/StoreBulkComputeIfAbsentTest.java | 2 +- .../org/ehcache/internal/store/StoreBulkComputeTest.java | 2 +- .../java/org/ehcache/internal/store/StoreClearTest.java | 2 +- .../java/org/ehcache/internal/store/StoreCloseTest.java | 2 +- .../ehcache/internal/store/StoreComputeIfAbsentTest.java | 2 +- .../org/ehcache/internal/store/StoreComputeTest.java | 2 +- .../org/ehcache/internal/store/StoreContainsKeyTest.java | 2 +- .../internal/store/StoreCreationEventListenerTest.java | 2 +- .../internal/store/StoreEvictionEventListenerTest.java | 2 +- .../java/org/ehcache/internal/store/StoreGetTest.java | 2 +- .../ehcache/internal/store/StoreIteratorHasNextTest.java | 2 +- .../ehcache/internal/store/StoreIteratorNextTest.java | 2 +- .../org/ehcache/internal/store/StoreIteratorTest.java | 2 +- .../org/ehcache/internal/store/StorePutIfAbsentTest.java | 2 +- .../java/org/ehcache/internal/store/StorePutTest.java | 2 +- .../internal/store/StoreRemovalEventListenerTest.java | 2 +- .../org/ehcache/internal/store/StoreRemoveKeyTest.java | 2 +- .../ehcache/internal/store/StoreRemoveKeyValueTest.java | 2 +- .../ehcache/internal/store/StoreReplaceKeyValueTest.java | 2 +- .../internal/store/StoreReplaceKeyValueValueTest.java | 2 +- .../internal/store/StoreUpdateEventListenerTest.java | 2 +- .../tier/AuthoritativeTierComputeIfAbsentAndFault.java | 2 +- .../ehcache/internal/tier/AuthoritativeTierFlush.java | 2 +- .../internal/tier/AuthoritativeTierGetAndFault.java | 4 ++-- .../java/org/ehcache/internal/tier/CachingTierClear.java | 2 +- .../internal/tier/CachingTierGetOrComputeIfAbsent.java | 2 +- .../org/ehcache/internal/tier/CachingTierInvalidate.java | 2 +- .../org/ehcache/internal/tier/CachingTierRemove.java | 2 +- core/src/main/java/org/ehcache/core/Ehcache.java | 2 +- core/src/main/java/org/ehcache/core/EhcacheBase.java | 4 ++-- .../java/org/ehcache/core/EhcacheWithLoaderWriter.java | 2 +- core/src/main/java/org/ehcache/core/SpecIterator.java | 2 +- .../core/exceptions/StorePassThroughException.java | 2 +- .../resilience/LoggingRobustResilienceStrategy.java | 2 +- .../ehcache/core/internal/resilience/RecoveryCache.java | 2 +- .../internal/resilience/RobustResilienceStrategy.java | 4 +++- core/src/main/java/org/ehcache/core/spi/store/Store.java | 1 + .../core/spi/store/tiering/AuthoritativeTier.java | 2 +- .../org/ehcache/core/spi/store/tiering/CachingTier.java | 2 +- .../core/spi/store/tiering/HigherCachingTier.java | 2 +- .../ehcache/core/spi/store/tiering/LowerCachingTier.java | 2 +- core/src/test/java/org/ehcache/core/CacheTest.java | 4 +--- .../java/org/ehcache/core/EhcacheBasicClearTest.java | 2 +- .../org/ehcache/core/EhcacheBasicContainsKeyTest.java | 2 +- .../test/java/org/ehcache/core/EhcacheBasicCrudBase.java | 4 ++-- .../java/org/ehcache/core/EhcacheBasicGetAllTest.java | 2 +- .../test/java/org/ehcache/core/EhcacheBasicGetTest.java | 2 +- .../java/org/ehcache/core/EhcacheBasicIteratorTest.java | 2 +- .../java/org/ehcache/core/EhcacheBasicPutAllTest.java | 4 +--- .../org/ehcache/core/EhcacheBasicPutIfAbsentTest.java | 2 +- .../test/java/org/ehcache/core/EhcacheBasicPutTest.java | 2 +- .../java/org/ehcache/core/EhcacheBasicRemoveAllTest.java | 4 +--- .../java/org/ehcache/core/EhcacheBasicRemoveTest.java | 2 +- .../org/ehcache/core/EhcacheBasicRemoveValueTest.java | 2 +- .../java/org/ehcache/core/EhcacheBasicReplaceTest.java | 2 +- .../org/ehcache/core/EhcacheBasicReplaceValueTest.java | 2 +- .../java/org/ehcache/core/EhcacheLoaderWriterTest.java | 2 +- .../core/EhcacheWithLoaderWriterBasicClearTest.java | 2 +- .../EhcacheWithLoaderWriterBasicContainsKeyTest.java | 2 +- .../core/EhcacheWithLoaderWriterBasicGetAllTest.java | 7 ++++--- .../core/EhcacheWithLoaderWriterBasicGetTest.java | 2 +- .../core/EhcacheWithLoaderWriterBasicPutAllTest.java | 5 +++-- .../EhcacheWithLoaderWriterBasicPutIfAbsentTest.java | 2 +- .../core/EhcacheWithLoaderWriterBasicPutTest.java | 2 +- .../core/EhcacheWithLoaderWriterBasicRemoveAllTest.java | 5 +++-- .../core/EhcacheWithLoaderWriterBasicRemoveTest.java | 2 +- .../EhcacheWithLoaderWriterBasicRemoveValueTest.java | 2 +- .../core/EhcacheWithLoaderWriterBasicReplaceTest.java | 2 +- .../EhcacheWithLoaderWriterBasicReplaceValueTest.java | 2 +- .../org/ehcache/core/EhcacheWithLoaderWriterTest.java | 2 +- .../core/exceptions/StorePassThroughExceptionTest.java | 2 +- .../org/ehcache/impl/internal/store/basic/NopStore.java | 2 +- .../ehcache/impl/internal/store/heap/OnHeapStore.java | 2 +- .../internal/store/offheap/AbstractOffHeapStore.java | 2 +- .../impl/internal/store/offheap/OffHeapStore.java | 2 +- .../impl/internal/store/tiering/CompoundCachingTier.java | 2 +- .../ehcache/impl/internal/store/tiering/TieredStore.java | 2 +- .../impl/internal/store/disk/OffHeapDiskStoreTest.java | 2 +- .../impl/internal/store/heap/BaseOnHeapStoreTest.java | 2 +- .../impl/internal/store/heap/OnHeapStoreByValueTest.java | 2 +- .../internal/store/heap/OnHeapStoreEvictionTest.java | 2 +- .../internal/store/heap/OnHeapStoreKeyCopierTest.java | 2 +- .../internal/store/heap/OnHeapStoreValueCopierTest.java | 2 +- .../store/heap/bytesized/ByteAccountingTest.java | 2 +- .../internal/store/offheap/AbstractOffHeapStoreTest.java | 2 +- .../internal/store/tiering/TieredStoreMutatorTest.java | 2 +- .../impl/internal/store/tiering/TieredStoreTest.java | 2 +- .../org/ehcache/integration/EhcacheBulkMethodsITest.java | 2 +- .../ehcache/transactions/xa/XAStoreAccessException.java | 9 ++++----- .../transactions/xa/internal/EhcacheXAResource.java | 2 +- .../org/ehcache/transactions/xa/internal/XAStore.java | 2 +- .../transactions/xa/internal/XATransactionContext.java | 2 +- 99 files changed, 114 insertions(+), 118 deletions(-) rename {core/src/main/java/org/ehcache/core/internal => api/src/main/java/org/ehcache}/resilience/ResilienceStrategy.java (99%) rename {core/src/main/java/org/ehcache/core/internal => api/src/main/java/org/ehcache}/resilience/RethrowingStoreAccessException.java (92%) rename {core/src/main/java/org/ehcache/core/spi/store => api/src/main/java/org/ehcache/resilience}/StoreAccessException.java (97%) diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/ResilienceStrategy.java b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java similarity index 99% rename from core/src/main/java/org/ehcache/core/internal/resilience/ResilienceStrategy.java rename to api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java index b033d9f002..023fb34cb6 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/ResilienceStrategy.java +++ b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java @@ -14,14 +14,13 @@ * limitations under the License. */ -package org.ehcache.core.internal.resilience; +package org.ehcache.resilience; import java.util.Map; import org.ehcache.Cache; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/RethrowingStoreAccessException.java b/api/src/main/java/org/ehcache/resilience/RethrowingStoreAccessException.java similarity index 92% rename from core/src/main/java/org/ehcache/core/internal/resilience/RethrowingStoreAccessException.java rename to api/src/main/java/org/ehcache/resilience/RethrowingStoreAccessException.java index c6f155c52f..9fa41dcccb 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/RethrowingStoreAccessException.java +++ b/api/src/main/java/org/ehcache/resilience/RethrowingStoreAccessException.java @@ -14,9 +14,7 @@ * limitations under the License. */ -package org.ehcache.core.internal.resilience; - -import org.ehcache.core.spi.store.StoreAccessException; +package org.ehcache.resilience; /** * Generic exception used when an internal operation fails on a {@link org.ehcache.Cache} but shouldn't be diff --git a/core/src/main/java/org/ehcache/core/spi/store/StoreAccessException.java b/api/src/main/java/org/ehcache/resilience/StoreAccessException.java similarity index 97% rename from core/src/main/java/org/ehcache/core/spi/store/StoreAccessException.java rename to api/src/main/java/org/ehcache/resilience/StoreAccessException.java index 6c4cf9cbd7..b446a894b3 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/StoreAccessException.java +++ b/api/src/main/java/org/ehcache/resilience/StoreAccessException.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.ehcache.core.spi.store; +package org.ehcache.resilience; /** * Generic exception used when an internal operation fails on a {@link org.ehcache.Cache}. diff --git a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java index faac2ec53e..25475e7de8 100644 --- a/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java +++ b/clustered/client/src/main/java/org/ehcache/clustered/client/internal/store/ClusteredStore.java @@ -45,6 +45,7 @@ import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEventSource; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.time.TimeSourceService; diff --git a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java index 0df3ef37ce..7fba20bc6f 100644 --- a/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java +++ b/clustered/client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java @@ -32,7 +32,7 @@ import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.Ehcache; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.statistics.StoreOperationOutcomes; import org.ehcache.impl.store.HashUtils; diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java index f125ce8463..efb7eb1071 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/TerminatedServerTest.java @@ -33,7 +33,6 @@ import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.spi.service.StatisticsService; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.impl.internal.statistics.DefaultStatisticsService; import org.junit.AfterClass; import org.junit.Before; diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java index 73c52e6aac..7f6b427068 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/replication/DuplicateTest.java @@ -28,8 +28,8 @@ import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.EhcacheBase; -import org.ehcache.core.internal.resilience.ResilienceStrategy; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.ResilienceStrategy; +import org.ehcache.resilience.StoreAccessException; import org.junit.After; import org.junit.Before; import org.junit.ClassRule; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java index 87b975a530..7346569dc9 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeIfAbsentTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.exceptions.StorePassThroughException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java index ad2a6c7814..5556d1ebd2 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreBulkComputeTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.exceptions.StorePassThroughException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreClearTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreClearTest.java index 1edb4dc6f4..ef94738342 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreClearTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreClearTest.java @@ -16,7 +16,7 @@ package org.ehcache.internal.store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCloseTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCloseTest.java index b260b712a7..c5515f0c9e 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCloseTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCloseTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java index 180b8f2f78..d859b18981 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeIfAbsentTest.java @@ -16,7 +16,7 @@ package org.ehcache.internal.store; import org.ehcache.core.exceptions.StorePassThroughException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.internal.TestExpiries; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java index a706ea8ccb..e485119beb 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreComputeTest.java @@ -16,7 +16,7 @@ package org.ehcache.internal.store; import org.ehcache.core.exceptions.StorePassThroughException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.internal.TestExpiries; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreContainsKeyTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreContainsKeyTest.java index a55f4109a1..793545389a 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreContainsKeyTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreContainsKeyTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java index 978f5d2a08..70b860fea1 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreCreationEventListenerTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.event.EventType; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java index a418d58ff5..32b525e89a 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreEvictionEventListenerTest.java @@ -19,7 +19,7 @@ import org.ehcache.Cache; import org.ehcache.core.spi.store.Store; import org.ehcache.event.EventType; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; import org.ehcache.spi.test.After; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java index af2b044204..6822736560 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreGetTest.java @@ -17,8 +17,8 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorHasNextTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorHasNextTest.java index b319599d12..c713f0c021 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorHasNextTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorHasNextTest.java @@ -18,7 +18,7 @@ import org.ehcache.Cache; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java index 71221ff927..bfd293a5ef 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorNextTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.Cache; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java index 649dd356f7..0f31048642 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreIteratorTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.Cache; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java index 384e3d5215..41f635c073 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutIfAbsentTest.java @@ -17,8 +17,8 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.spi.test.After; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java index 686de8f584..90b504cff5 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StorePutTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java index 8de281a66b..c503e9f8fc 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemovalEventListenerTest.java @@ -19,7 +19,7 @@ import org.ehcache.event.EventType; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyTest.java index 87423b5b32..1ca597c2e9 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java index 30ca6f4f97..5b95be51f4 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreRemoveKeyValueTest.java @@ -18,7 +18,7 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.RemoveStatus; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java index 112d94be2a..b7c71de2e9 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueTest.java @@ -17,7 +17,7 @@ package org.ehcache.internal.store; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java index a1c2c60ddc..d5ba7c1cc4 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreReplaceKeyValueValueTest.java @@ -18,7 +18,7 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ReplaceStatus; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java index 530cf326f1..76b9b48abe 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/store/StoreUpdateEventListenerTest.java @@ -19,7 +19,7 @@ import org.ehcache.event.EventType; import org.ehcache.core.spi.store.events.StoreEvent; import org.ehcache.core.spi.store.events.StoreEventListener; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.After; import org.ehcache.spi.test.Before; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java index d0ff40933e..20b05aadfe 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierComputeIfAbsentAndFault.java @@ -16,7 +16,7 @@ package org.ehcache.internal.tier; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java index eb99068b88..41ca727ef5 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierFlush.java @@ -16,7 +16,7 @@ package org.ehcache.internal.tier; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.spi.test.After; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java index 5a02869a92..436612d754 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/AuthoritativeTierGetAndFault.java @@ -16,11 +16,11 @@ package org.ehcache.internal.tier; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.internal.TestExpiries; import org.ehcache.internal.TestTimeSource; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; -import org.ehcache.spi.test.After; +import org.ehcache.spi.test.After;; import org.ehcache.spi.test.Ignore; import org.ehcache.spi.test.LegalSPITesterException; import org.ehcache.spi.test.SPITest; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java index 1dfdeba49a..6e0ca54500 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierClear.java @@ -16,7 +16,7 @@ package org.ehcache.internal.tier; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.spi.test.After; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java index ddc5b52ebf..3637ed2ef9 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierGetOrComputeIfAbsent.java @@ -16,7 +16,7 @@ package org.ehcache.internal.tier; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.spi.test.After; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java index b55f142175..0152c0f516 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierInvalidate.java @@ -17,7 +17,7 @@ package org.ehcache.internal.tier; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.spi.test.After; import org.ehcache.spi.test.LegalSPITesterException; diff --git a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java index 9f57a95dbf..a4ecce34fe 100644 --- a/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java +++ b/core-spi-test/src/main/java/org/ehcache/internal/tier/CachingTierRemove.java @@ -16,7 +16,7 @@ package org.ehcache.internal.tier; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.spi.test.After; diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index f0af8fd4e9..c1dc7f5f48 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -35,7 +35,7 @@ import org.ehcache.core.spi.store.Store.RemoveStatus; import org.ehcache.core.spi.store.Store.ReplaceStatus; import org.ehcache.core.spi.store.Store.ValueHolder; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.BulkOps; import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetAllOutcome; diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index 0862d6de16..08ab144de6 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -21,11 +21,9 @@ import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.internal.resilience.LoggingRobustResilienceStrategy; import org.ehcache.core.internal.resilience.RecoveryCache; -import org.ehcache.core.internal.resilience.ResilienceStrategy; import org.ehcache.core.spi.LifeCycled; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.core.statistics.BulkOps; import org.ehcache.core.statistics.CacheOperationOutcomes.ClearOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; @@ -38,6 +36,8 @@ import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.resilience.ResilienceStrategy; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.slf4j.Logger; diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index af9e9c02bd..0657e33432 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -22,7 +22,7 @@ import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.core.spi.store.Store; diff --git a/core/src/main/java/org/ehcache/core/SpecIterator.java b/core/src/main/java/org/ehcache/core/SpecIterator.java index 6d198293a5..e8f481e368 100644 --- a/core/src/main/java/org/ehcache/core/SpecIterator.java +++ b/core/src/main/java/org/ehcache/core/SpecIterator.java @@ -17,7 +17,7 @@ import org.ehcache.Cache; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import java.util.Iterator; diff --git a/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java b/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java index 795e464d31..942b59c0c7 100644 --- a/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java +++ b/core/src/main/java/org/ehcache/core/exceptions/StorePassThroughException.java @@ -16,7 +16,7 @@ package org.ehcache.core.exceptions; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; /** * A generic wrapper runtime exception that will not be caught and diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java index 5d79ca5b47..72a929bd30 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java @@ -17,7 +17,7 @@ package org.ehcache.core.internal.resilience; import org.ehcache.Cache; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.CacheIterationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java b/core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java index 5ebcac1c71..8740326eba 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java +++ b/core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java @@ -16,7 +16,7 @@ package org.ehcache.core.internal.resilience; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; /** * diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java index 8de48c3082..a8c7c6641b 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java @@ -19,9 +19,11 @@ import java.util.HashMap; import java.util.Map; +import org.ehcache.resilience.ResilienceStrategy; +import org.ehcache.resilience.RethrowingStoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; diff --git a/core/src/main/java/org/ehcache/core/spi/store/Store.java b/core/src/main/java/org/ehcache/core/spi/store/Store.java index cea0dccfa3..a62bb7cdb9 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/Store.java +++ b/core/src/main/java/org/ehcache/core/spi/store/Store.java @@ -22,6 +22,7 @@ import org.ehcache.config.ResourceType; import org.ehcache.core.spi.store.events.StoreEventSource; import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.serialization.Serializer; import org.ehcache.spi.service.PluralService; import org.ehcache.spi.service.Service; diff --git a/core/src/main/java/org/ehcache/core/spi/store/tiering/AuthoritativeTier.java b/core/src/main/java/org/ehcache/core/spi/store/tiering/AuthoritativeTier.java index f709fcd88d..f0ca9c4837 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/tiering/AuthoritativeTier.java +++ b/core/src/main/java/org/ehcache/core/spi/store/tiering/AuthoritativeTier.java @@ -17,7 +17,7 @@ package org.ehcache.core.spi.store.tiering; import org.ehcache.config.ResourceType; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.service.PluralService; import org.ehcache.spi.service.Service; diff --git a/core/src/main/java/org/ehcache/core/spi/store/tiering/CachingTier.java b/core/src/main/java/org/ehcache/core/spi/store/tiering/CachingTier.java index f68530d5ff..4575c2503b 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/tiering/CachingTier.java +++ b/core/src/main/java/org/ehcache/core/spi/store/tiering/CachingTier.java @@ -17,7 +17,7 @@ package org.ehcache.core.spi.store.tiering; import org.ehcache.config.ResourceType; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.ConfigurationChangeSupport; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.service.PluralService; diff --git a/core/src/main/java/org/ehcache/core/spi/store/tiering/HigherCachingTier.java b/core/src/main/java/org/ehcache/core/spi/store/tiering/HigherCachingTier.java index 685aa1fc19..4f7d73a7ce 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/tiering/HigherCachingTier.java +++ b/core/src/main/java/org/ehcache/core/spi/store/tiering/HigherCachingTier.java @@ -16,7 +16,7 @@ package org.ehcache.core.spi.store.tiering; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.service.PluralService; import org.ehcache.spi.service.Service; diff --git a/core/src/main/java/org/ehcache/core/spi/store/tiering/LowerCachingTier.java b/core/src/main/java/org/ehcache/core/spi/store/tiering/LowerCachingTier.java index 62d9384f6f..4038af1c3c 100644 --- a/core/src/main/java/org/ehcache/core/spi/store/tiering/LowerCachingTier.java +++ b/core/src/main/java/org/ehcache/core/spi/store/tiering/LowerCachingTier.java @@ -18,7 +18,7 @@ import org.ehcache.core.spi.store.ConfigurationChangeSupport; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.service.PluralService; import org.ehcache.spi.service.Service; import org.ehcache.spi.service.ServiceConfiguration; diff --git a/core/src/test/java/org/ehcache/core/CacheTest.java b/core/src/test/java/org/ehcache/core/CacheTest.java index 3642bb2b91..1d97793b48 100644 --- a/core/src/test/java/org/ehcache/core/CacheTest.java +++ b/core/src/test/java/org/ehcache/core/CacheTest.java @@ -18,13 +18,11 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.StateTransitionException; import org.ehcache.core.spi.LifeCycled; import org.hamcrest.CoreMatchers; import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import java.util.Collections; import java.util.Iterator; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java index b0b7ecb761..3eaa4c6756 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java @@ -21,7 +21,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.Matchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java index 21098479f6..5217a1e255 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java @@ -21,7 +21,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.Matchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java index 910548921a..ec8184d175 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java @@ -26,8 +26,8 @@ import org.ehcache.core.spi.store.events.StoreEventSource; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; -import org.ehcache.core.internal.resilience.ResilienceStrategy; +import org.ehcache.resilience.StoreAccessException; +import org.ehcache.resilience.ResilienceStrategy; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.Description; import org.hamcrest.Factory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java index 6852ba6169..1f7aa76eef 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java @@ -19,7 +19,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.BulkOps; import org.hamcrest.Matchers; import org.junit.Test; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java index 1d09624e64..aa18f22355 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java @@ -20,7 +20,7 @@ import org.ehcache.Status; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java index 67be0b252a..7f0a80b457 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java @@ -18,7 +18,7 @@ import org.ehcache.Cache; import org.ehcache.Status; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.CacheIterationException; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.RemoveStatus; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java index 797887a746..b71720830c 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java @@ -19,7 +19,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.BulkOps; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -31,8 +31,6 @@ import org.mockito.ArgumentMatchers; import org.mockito.Captor; import org.mockito.InOrder; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.slf4j.LoggerFactory; import java.util.AbstractMap; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java index 1087836108..ded2a39359 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java @@ -23,7 +23,7 @@ import org.ehcache.core.config.BaseCacheConfiguration; import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.hamcrest.Matchers; import org.junit.Test; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java index 8df8e35052..72ae8a920f 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java @@ -21,7 +21,7 @@ import org.ehcache.Status; import org.ehcache.config.CacheConfiguration; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java index 5af4df49ca..1f92f2e966 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java @@ -19,7 +19,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.BulkOps; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; @@ -30,8 +30,6 @@ import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; import org.slf4j.LoggerFactory; import java.util.ArrayList; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java index 09dbbef8aa..292300a1fb 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java @@ -20,7 +20,7 @@ import org.ehcache.Status; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java index 81e657af2e..d8f2e9c34e 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java @@ -20,7 +20,7 @@ import org.ehcache.Status; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java index fcffdb7a97..84ef1bd464 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java @@ -20,7 +20,7 @@ import org.ehcache.Status; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java index a65b0ab6d8..7a84c53745 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java @@ -20,7 +20,7 @@ import org.ehcache.Status; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.CoreMatchers; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java b/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java index b169b68b9e..9844a8e61d 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheLoaderWriterTest.java @@ -22,7 +22,7 @@ import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicClearTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicClearTest.java index d286fb9799..b25672b34a 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicClearTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicClearTest.java @@ -18,7 +18,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mock; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicContainsKeyTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicContainsKeyTest.java index 71f5c518f5..e9e2debdc3 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicContainsKeyTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicContainsKeyTest.java @@ -18,7 +18,7 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mock; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java index 4a1fdf6504..245795dc58 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java @@ -24,8 +24,9 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.CacheOperationOutcomes; +import org.ehcache.resilience.ResilienceStrategy; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.Matchers; import org.junit.Test; @@ -93,7 +94,7 @@ public class EhcacheWithLoaderWriterBasicGetAllTest extends EhcacheBasicCrudBase /** * A Mockito {@code ArgumentCaptor} for the {@code Set} argument to the - * {@link org.ehcache.core.internal.resilience.ResilienceStrategy#getAllFailure(Iterable, Map, StoreAccessException) + * {@link ResilienceStrategy#getAllFailure(Iterable, Map, StoreAccessException) * ResilienceStrategy.getAllFailure(Iterable, Map, StoreAccessException)} method. */ @Captor @@ -103,7 +104,7 @@ public class EhcacheWithLoaderWriterBasicGetAllTest extends EhcacheBasicCrudBase * A Mockito {@code ArgumentCaptor} for the * {@link BulkCacheLoadingException BulkCacheLoadingException} * provided to the - * {@link org.ehcache.core.internal.resilience.ResilienceStrategy#getAllFailure(Iterable, StoreAccessException, BulkCacheLoadingException) + * {@link ResilienceStrategy#getAllFailure(Iterable, StoreAccessException, BulkCacheLoadingException) * ResilienceStrategy.getAllFailure(Iterable, StoreAccessException, BulkCacheLoadingException)} method. */ @Captor diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java index 7bcf910e23..905d3cc3f3 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java @@ -17,7 +17,7 @@ package org.ehcache.core; import org.ehcache.Status; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.core.exceptions.ExceptionFactory; import org.ehcache.core.statistics.CacheOperationOutcomes; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java index 3a522f3450..1eb210bd1e 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutAllTest.java @@ -30,8 +30,9 @@ import org.ehcache.core.statistics.BulkOps; import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.expiry.ExpiryPolicy; +import org.ehcache.resilience.ResilienceStrategy; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.Matchers; import org.junit.Test; @@ -109,7 +110,7 @@ public class EhcacheWithLoaderWriterBasicPutAllTest extends EhcacheBasicCrudBase * A Mockito {@code ArgumentCaptor} for the * {@link BulkCacheWritingException BulkCacheWritingException} * provided to the - * {@link org.ehcache.core.internal.resilience.ResilienceStrategy#putAllFailure(Map, StoreAccessException, BulkCacheWritingException)} + * {@link ResilienceStrategy#putAllFailure(Map, StoreAccessException, BulkCacheWritingException)} * ResilienceStrategy.putAllFailure(Iterable, StoreAccessException, BulkCacheWritingException)} method. */ @Captor diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java index 80b03fdaa8..074026ed86 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java @@ -22,7 +22,7 @@ import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java index 2ee2a09f92..037d94f59f 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java @@ -19,7 +19,7 @@ import org.ehcache.Status; import org.ehcache.config.CacheConfiguration; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hamcrest.CoreMatchers; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveAllTest.java index 4fdfb936d4..b6a496ae44 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveAllTest.java @@ -24,8 +24,9 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.CacheOperationOutcomes; +import org.ehcache.resilience.ResilienceStrategy; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.core.statistics.BulkOps; import org.hamcrest.Matchers; @@ -86,7 +87,7 @@ public class EhcacheWithLoaderWriterBasicRemoveAllTest extends EhcacheBasicCrudB * A Mockito {@code ArgumentCaptor} for the * {@link BulkCacheWritingException BulkCacheWritingException} * provided to the - * {@link org.ehcache.core.internal.resilience.ResilienceStrategy#removeAllFailure(Iterable, StoreAccessException, BulkCacheWritingException)} + * {@link ResilienceStrategy#removeAllFailure(Iterable, StoreAccessException, BulkCacheWritingException)} * ResilienceStrategy.putAllFailure(Iterable, StoreAccessException, BulkCacheWritingException)} method. */ @Captor diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java index 48014f3d05..c34ecbbae4 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java @@ -17,7 +17,7 @@ package org.ehcache.core; import org.ehcache.Status; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.core.statistics.CacheOperationOutcomes; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveValueTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveValueTest.java index 7449062be6..f21bd1d0db 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveValueTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveValueTest.java @@ -17,7 +17,7 @@ package org.ehcache.core; import org.ehcache.Status; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.core.statistics.CacheOperationOutcomes; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java index 2b73b8cfad..696e00197f 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceTest.java @@ -21,7 +21,7 @@ import org.ehcache.core.config.BaseCacheConfiguration; import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java index 1fe7fe1efd..fc8624541a 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicReplaceValueTest.java @@ -21,7 +21,7 @@ import org.ehcache.core.config.BaseCacheConfiguration; import org.ehcache.core.config.ResourcePoolsHelper; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.spi.loaderwriter.CacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java index 6902c2dd56..56549c3520 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterTest.java @@ -34,7 +34,7 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.events.StoreEventSource; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.junit.Test; import org.slf4j.LoggerFactory; diff --git a/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java b/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java index 74400335b3..815ba2f7ad 100644 --- a/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java +++ b/core/src/test/java/org/ehcache/core/exceptions/StorePassThroughExceptionTest.java @@ -15,7 +15,7 @@ */ package org.ehcache.core.exceptions; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.junit.Test; import static org.assertj.core.api.Assertions.*; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java index 13be97cc87..8f706c0ded 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/basic/NopStore.java @@ -17,7 +17,7 @@ import org.ehcache.Cache; import org.ehcache.core.CacheConfigurationChangeListener; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.events.StoreEventFilter; import org.ehcache.core.spi.store.events.StoreEventListener; import org.ehcache.core.spi.store.events.StoreEventSource; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java index 1974a9341c..468346b29f 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/heap/OnHeapStore.java @@ -28,7 +28,7 @@ import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.heap.LimitExceededException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java index b2be354a71..455030e519 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStore.java @@ -35,7 +35,7 @@ import org.ehcache.core.config.ExpiryUtils; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.internal.store.offheap.factories.EhcacheSegmentFactory; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java index 7bd39b9e6f..bf7503a4dd 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/offheap/OffHeapStore.java @@ -22,7 +22,7 @@ import org.ehcache.config.ResourceType; import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.events.StoreEventDispatcher; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.AuthoritativeTierOperationOutcomes; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.core.statistics.StoreOperationOutcomes; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java index a4456d33d8..eb5c209404 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/CompoundCachingTier.java @@ -19,7 +19,7 @@ import org.ehcache.core.CacheConfigurationChangeListener; import org.ehcache.core.collections.ConcurrentWeakIdentityHashMap; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.core.spi.store.tiering.HigherCachingTier; import org.ehcache.core.spi.store.tiering.LowerCachingTier; diff --git a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java index ef593d33bc..124b8bb830 100644 --- a/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java +++ b/impl/src/main/java/org/ehcache/impl/internal/store/tiering/TieredStore.java @@ -22,7 +22,7 @@ import org.ehcache.core.collections.ConcurrentWeakIdentityHashMap; import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.events.StoreEventSource; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.core.spi.store.tiering.CachingTier; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java index 953c2485fc..951215ec2e 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/disk/OffHeapDiskStoreTest.java @@ -25,7 +25,7 @@ import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.MemoryUnit; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.LowerCachingTierOperationsOutcome; import org.ehcache.CachePersistenceException; import org.ehcache.expiry.ExpiryPolicy; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java index c70e458e38..5148b582a8 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/BaseOnHeapStoreTest.java @@ -21,7 +21,7 @@ import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.core.events.StoreEventDispatcher; import org.ehcache.core.events.StoreEventSink; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.impl.internal.store.heap.holders.CopiedOnHeapValueHolder; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java index b5e5e8f050..f0833d8a90 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreByValueTest.java @@ -24,7 +24,7 @@ import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.serialization.SerializerException; import org.ehcache.impl.copy.SerializingCopier; import org.ehcache.core.spi.time.SystemTimeSource; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java index e8668d228f..3f967ff0fc 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreEvictionTest.java @@ -20,7 +20,7 @@ import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.core.internal.store.StoreConfigurationImpl; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.event.EventType; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java index 0b2703b008..413df8669a 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreKeyCopierTest.java @@ -19,7 +19,7 @@ import org.ehcache.Cache; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java index 8eb89d34e5..d3dc98871c 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStoreValueCopierTest.java @@ -19,7 +19,7 @@ import org.ehcache.Cache; import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.EntryUnit; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java index edcd9504a5..8722fb0857 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/heap/bytesized/ByteAccountingTest.java @@ -22,7 +22,7 @@ import org.ehcache.config.units.MemoryUnit; import org.ehcache.event.EventType; import org.ehcache.core.events.StoreEventDispatcher; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.heap.LimitExceededException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.copy.IdentityCopier; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java index 6947fc3cfe..0f67676c27 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/offheap/AbstractOffHeapStoreTest.java @@ -21,7 +21,7 @@ import org.ehcache.config.builders.ExpiryPolicyBuilder; import org.ehcache.config.units.MemoryUnit; import org.ehcache.event.EventType; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.store.AbstractValueHolder; import org.ehcache.core.spi.store.Store; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java index dae21e8655..767fb11858 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreMutatorTest.java @@ -21,7 +21,7 @@ import org.ehcache.config.units.MemoryUnit; import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.core.spi.time.SystemTimeSource; diff --git a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java index bee5aac2d6..69ca82a131 100644 --- a/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java +++ b/impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java @@ -24,7 +24,7 @@ import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.RemoveStatus; import org.ehcache.core.spi.store.Store.ReplaceStatus; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.tiering.AuthoritativeTier; import org.ehcache.core.spi.store.tiering.CachingTier; import org.ehcache.impl.internal.store.heap.OnHeapStore; diff --git a/integration-test/src/test/java/org/ehcache/integration/EhcacheBulkMethodsITest.java b/integration-test/src/test/java/org/ehcache/integration/EhcacheBulkMethodsITest.java index e9b0786fe0..158566495f 100644 --- a/integration-test/src/test/java/org/ehcache/integration/EhcacheBulkMethodsITest.java +++ b/integration-test/src/test/java/org/ehcache/integration/EhcacheBulkMethodsITest.java @@ -23,7 +23,7 @@ import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.impl.copy.IdentityCopier; import org.ehcache.core.events.NullStoreEventDispatcher; import org.ehcache.impl.internal.sizeof.NoopSizeOfEngine; diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/XAStoreAccessException.java b/transactions/src/main/java/org/ehcache/transactions/xa/XAStoreAccessException.java index f2d9a34b6e..91a18df98e 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/XAStoreAccessException.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/XAStoreAccessException.java @@ -13,11 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package org.ehcache.transactions.xa; -import org.ehcache.core.internal.resilience.ResilienceStrategy; -import org.ehcache.core.internal.resilience.RethrowingStoreAccessException; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.ResilienceStrategy; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.transactions.xa.internal.XAStore; /** @@ -26,7 +24,8 @@ * * @author Ludovic Orban */ -public class XAStoreAccessException extends RethrowingStoreAccessException { +@SuppressWarnings("deprecation") +public class XAStoreAccessException extends org.ehcache.resilience.RethrowingStoreAccessException { public XAStoreAccessException(RuntimeException cause) { super(cause); } diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java index f429c53162..7aa06a1533 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/EhcacheXAResource.java @@ -16,7 +16,7 @@ package org.ehcache.transactions.xa.internal; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.store.Store; import org.ehcache.transactions.xa.EhcacheXAException; import org.ehcache.transactions.xa.internal.journal.Journal; diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java index cc9a301d46..9ed93898b8 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XAStore.java @@ -23,7 +23,7 @@ import org.ehcache.core.internal.store.StoreConfigurationImpl; import org.ehcache.core.internal.store.StoreSupport; import org.ehcache.core.spi.service.DiskResourceService; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.expiry.ExpiryPolicy; import org.ehcache.impl.config.copy.DefaultCopierConfiguration; import org.ehcache.impl.copy.SerializingCopier; diff --git a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java index 5eface9096..132793752b 100644 --- a/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java +++ b/transactions/src/main/java/org/ehcache/transactions/xa/internal/XATransactionContext.java @@ -16,7 +16,7 @@ package org.ehcache.transactions.xa.internal; -import org.ehcache.core.spi.store.StoreAccessException; +import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.spi.time.TimeSource; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.RemoveStatus; From 46d2a18a08028b616e9d32a13ca9c53ebd39e404 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Fri, 22 Dec 2017 11:03:41 -0500 Subject: [PATCH 122/779] Resilience implementation moved out of internal (#2198) --- core/src/main/java/org/ehcache/core/EhcacheBase.java | 4 ++-- .../resilience/LoggingRobustResilienceStrategy.java | 2 +- .../ehcache/core/{internal => }/resilience/RecoveryCache.java | 2 +- .../{internal => }/resilience/RobustResilienceStrategy.java | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) rename core/src/main/java/org/ehcache/core/{internal => }/resilience/LoggingRobustResilienceStrategy.java (98%) rename core/src/main/java/org/ehcache/core/{internal => }/resilience/RecoveryCache.java (95%) rename core/src/main/java/org/ehcache/core/{internal => }/resilience/RobustResilienceStrategy.java (99%) diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index 08ab144de6..8ea4b779f6 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -19,8 +19,8 @@ import org.ehcache.Status; import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.core.events.CacheEventDispatcher; -import org.ehcache.core.internal.resilience.LoggingRobustResilienceStrategy; -import org.ehcache.core.internal.resilience.RecoveryCache; +import org.ehcache.core.resilience.LoggingRobustResilienceStrategy; +import org.ehcache.core.resilience.RecoveryCache; import org.ehcache.core.spi.LifeCycled; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/LoggingRobustResilienceStrategy.java similarity index 98% rename from core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java rename to core/src/main/java/org/ehcache/core/resilience/LoggingRobustResilienceStrategy.java index 72a929bd30..6edd5cb050 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/LoggingRobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/LoggingRobustResilienceStrategy.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.ehcache.core.internal.resilience; +package org.ehcache.core.resilience; import org.ehcache.Cache; import org.ehcache.resilience.StoreAccessException; diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java b/core/src/main/java/org/ehcache/core/resilience/RecoveryCache.java similarity index 95% rename from core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java rename to core/src/main/java/org/ehcache/core/resilience/RecoveryCache.java index 8740326eba..06006dd481 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/RecoveryCache.java +++ b/core/src/main/java/org/ehcache/core/resilience/RecoveryCache.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.ehcache.core.internal.resilience; +package org.ehcache.core.resilience; import org.ehcache.resilience.StoreAccessException; diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java similarity index 99% rename from core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java rename to core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java index a8c7c6641b..2a6511ed6b 100644 --- a/core/src/main/java/org/ehcache/core/internal/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package org.ehcache.core.internal.resilience; +package org.ehcache.core.resilience; import java.util.HashMap; import java.util.Map; From 0bae20ec4b35fb772da32d888d4bdafc35552310 Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 17 Jan 2018 13:05:49 -0500 Subject: [PATCH 123/779] Push fallback loading to the resilience strategy (#2198) --- .../resilience/ResilienceStrategy.java | 22 -- .../main/java/org/ehcache/core/Ehcache.java | 8 +- .../java/org/ehcache/core/EhcacheBase.java | 57 ++-- .../ehcache/core/EhcacheWithLoaderWriter.java | 55 +--- .../CacheLoaderWriterResilienceStrategy.java | 33 +++ ...ltCacheLoaderWriterResilienceStrategy.java | 53 ++++ ...y.java => AbstractResilienceStrategy.java} | 19 +- .../core/resilience/DefaultRecoveryStore.java | 27 ++ ...{RecoveryCache.java => RecoveryStore.java} | 9 +- .../RobustLoaderWriterResilienceStrategy.java | 252 ++++++++++++++++++ .../resilience/RobustResilienceStrategy.java | 40 +-- .../statistics/CacheOperationOutcomes.java | 10 - .../ehcache/core/EhcacheBasicCrudBase.java | 8 +- .../ehcache/core/EhcacheBasicGetAllTest.java | 3 - ...hcacheWithLoaderWriterBasicGetAllTest.java | 78 ------ .../EhcacheWithLoaderWriterBasicGetTest.java | 33 +-- 16 files changed, 437 insertions(+), 270 deletions(-) create mode 100644 core/src/main/java/org/ehcache/core/internal/resilience/CacheLoaderWriterResilienceStrategy.java create mode 100644 core/src/main/java/org/ehcache/core/internal/resilience/DefaultCacheLoaderWriterResilienceStrategy.java rename core/src/main/java/org/ehcache/core/resilience/{LoggingRobustResilienceStrategy.java => AbstractResilienceStrategy.java} (84%) create mode 100644 core/src/main/java/org/ehcache/core/resilience/DefaultRecoveryStore.java rename core/src/main/java/org/ehcache/core/resilience/{RecoveryCache.java => RecoveryStore.java} (82%) create mode 100644 core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java diff --git a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java index 023fb34cb6..e3ac98db43 100644 --- a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java +++ b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java @@ -57,28 +57,6 @@ public interface ResilienceStrategy { */ V getFailure(K key, StoreAccessException e); - /** - * Called when a {@link Cache#get(java.lang.Object)} fails on a cache with a - * cache loader due to an underlying store failure. - * - * @param key the key being retrieved - * @param loaded the value from the loader - * @param e the triggered failure - * @return the value to return from the operation - */ - V getFailure(K key, V loaded, StoreAccessException e); - - /** - * Called when a {@link Cache#get(java.lang.Object)} fails on a cache with a - * cache loader due to an underlying store failure. - * - * @param key the key being retrieved - * @param e the cache failure - * @param f the loader failure - * @return the value to return from the operation - */ - V getFailure(K key, StoreAccessException e, CacheLoadingException f); - /** * Called when a {@link Cache#containsKey(java.lang.Object)} fails due to an * underlying store failure, and the resultant cache load operation also fails. diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index c1dc7f5f48..b2e49cbe34 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -30,11 +30,13 @@ import org.ehcache.Cache; import org.ehcache.config.CacheConfiguration; import org.ehcache.core.events.CacheEventDispatcher; +import org.ehcache.core.resilience.RobustResilienceStrategy; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.PutStatus; import org.ehcache.core.spi.store.Store.RemoveStatus; import org.ehcache.core.spi.store.Store.ReplaceStatus; import org.ehcache.core.spi.store.Store.ValueHolder; +import org.ehcache.resilience.ResilienceStrategy; import org.ehcache.resilience.StoreAccessException; import org.ehcache.core.statistics.BulkOps; import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; @@ -76,15 +78,15 @@ public Ehcache(CacheConfiguration configuration, final Store store, Ehcache(EhcacheRuntimeConfiguration runtimeConfiguration, Store store, CacheEventDispatcher eventDispatcher, Logger logger, StatusTransitioner statusTransitioner) { - super(runtimeConfiguration, store, eventDispatcher, logger, statusTransitioner); + super(runtimeConfiguration, store, new RobustResilienceStrategy<>(store), eventDispatcher, logger, statusTransitioner); } /** * {@inheritDoc} */ @Override - public V get(final K key) { - return getNoLoader(key); + protected Store.ValueHolder doGet(K key) throws StoreAccessException { + return store.get(key); } /** diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index 8ea4b779f6..dd6ea722c1 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -19,8 +19,7 @@ import org.ehcache.Status; import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.core.events.CacheEventDispatcher; -import org.ehcache.core.resilience.LoggingRobustResilienceStrategy; -import org.ehcache.core.resilience.RecoveryCache; +import org.ehcache.core.resilience.RecoveryStore; import org.ehcache.core.spi.LifeCycled; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; @@ -94,17 +93,13 @@ public abstract class EhcacheBase implements InternalCache { * @param eventDispatcher the event dispatcher * @param logger the logger */ - EhcacheBase(EhcacheRuntimeConfiguration runtimeConfiguration, Store store, + EhcacheBase(EhcacheRuntimeConfiguration runtimeConfiguration, Store store, ResilienceStrategy resilienceStrategy, CacheEventDispatcher eventDispatcher, Logger logger, StatusTransitioner statusTransitioner) { this.store = store; runtimeConfiguration.addCacheConfigurationListener(store.getConfigurationChangeListeners()); StatisticsManager.associate(store).withParent(this); - if (store instanceof RecoveryCache) { - this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(castToRecoveryCache(store)); - } else { - this.resilienceStrategy = new LoggingRobustResilienceStrategy<>(recoveryCache(store)); - } + this.resilienceStrategy = resilienceStrategy; this.runtimeConfiguration = runtimeConfiguration; runtimeConfiguration.addCacheConfigurationListener(eventDispatcher.getConfigurationChangeListeners()); @@ -116,33 +111,37 @@ public abstract class EhcacheBase implements InternalCache { } } - @SuppressWarnings("unchecked") - private RecoveryCache castToRecoveryCache(Store store) { - return (RecoveryCache) store; - } - - private static RecoveryCache recoveryCache(final Store store) { - return new RecoveryCache() { + /** + * {@inheritDoc} + */ + @Override + public V get(K key) { + getObserver.begin(); + statusTransitioner.checkAvailable(); + checkNonNull(key); - @Override - public void obliterate() throws StoreAccessException { - store.clear(); - } + try { + Store.ValueHolder valueHolder = doGet(key); - @Override - public void obliterate(K key) throws StoreAccessException { - store.remove(key); + // Check for expiry first + if (valueHolder == null) { + getObserver.end(GetOutcome.MISS); + return null; + } else { + getObserver.end(GetOutcome.HIT); + return valueHolder.get(); } - - @Override - public void obliterate(Iterable keys) throws StoreAccessException { - for (K key : keys) { - obliterate(key); - } + } catch (StoreAccessException e) { + try { + return resilienceStrategy.getFailure(key, e); + } finally { + getObserver.end(GetOutcome.FAILURE); } - }; + } } + protected abstract Store.ValueHolder doGet(K key) throws StoreAccessException; + protected V getNoLoader(K key) { getObserver.begin(); statusTransitioner.checkAvailable(); diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index 0657e33432..abf53e3f87 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -20,6 +20,7 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.exceptions.StorePassThroughException; +import org.ehcache.core.resilience.RobustLoaderWriterResilienceStrategy; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.resilience.StoreAccessException; @@ -29,7 +30,6 @@ import org.ehcache.core.spi.store.Store.ValueHolder; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.ehcache.core.statistics.BulkOps; -import org.ehcache.core.statistics.CacheOperationOutcomes.CacheLoadingOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetAllOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome; @@ -40,7 +40,6 @@ import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; import org.slf4j.Logger; -import org.terracotta.statistics.observer.OperationObserver; import java.util.Collection; import java.util.Collections; @@ -60,7 +59,6 @@ import static org.ehcache.core.internal.util.Functions.memoize; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheWritingException; -import static org.terracotta.statistics.StatisticBuilder.operation; /** * Implementation of the {@link Cache} interface when a {@link CacheLoaderWriter} is involved. @@ -77,8 +75,6 @@ public class EhcacheWithLoaderWriter extends EhcacheBase { private final CacheLoaderWriter cacheLoaderWriter; private final boolean useLoaderInAtomics; - private final OperationObserver cacheLoadingObserver = operation(CacheLoadingOutcome.class).named("cacheLoading").of(this).tag("cache").build(); - /** * Constructs a new {@code EhcacheWithLoaderWriter} based on the provided parameters. * @@ -104,59 +100,22 @@ public EhcacheWithLoaderWriter(CacheConfiguration configuration, Store runtimeConfiguration, Store store, CacheLoaderWriter cacheLoaderWriter, CacheEventDispatcher eventDispatcher, boolean useLoaderInAtomics, Logger logger, StatusTransitioner statusTransitioner) { - super(runtimeConfiguration, store, eventDispatcher, logger, statusTransitioner); + super(runtimeConfiguration, store, new RobustLoaderWriterResilienceStrategy<>(store, cacheLoaderWriter), eventDispatcher, logger, statusTransitioner); this.cacheLoaderWriter = Objects.requireNonNull(cacheLoaderWriter, "CacheLoaderWriter cannot be null"); this.useLoaderInAtomics = useLoaderInAtomics; } - /** - * {@inheritDoc} - */ - @Override - public V get(final K key) throws CacheLoadingException { - getObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - - final Function mappingFunction = memoize(k -> { - V loaded; + protected Store.ValueHolder doGet(K key) throws StoreAccessException { + Function mappingFunction = k -> { try { - cacheLoadingObserver.begin(); - loaded = cacheLoaderWriter.load(k); - cacheLoadingObserver.end(CacheLoadingOutcome.SUCCESS); + return cacheLoaderWriter.load(k); } catch (Exception e) { - cacheLoadingObserver.end(CacheLoadingOutcome.FAILURE); throw new StorePassThroughException(newCacheLoadingException(e)); } + }; - return loaded; - }); - - try { - final Store.ValueHolder valueHolder = store.computeIfAbsent(key, mappingFunction); - - // Check for expiry first - if (valueHolder == null) { - getObserver.end(GetOutcome.MISS); - return null; - } else { - getObserver.end(GetOutcome.HIT); - return valueHolder.get(); - } - } catch (StoreAccessException e) { - try { - V fromLoader; - try { - fromLoader = mappingFunction.apply(key); - } catch (StorePassThroughException cpte) { - return resilienceStrategy.getFailure(key, e, (CacheLoadingException) cpte.getCause()); - } - return resilienceStrategy.getFailure(key, fromLoader, e); - } finally { - getObserver.end(GetOutcome.FAILURE); - } - } + return store.computeIfAbsent(key, mappingFunction); } /** diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/CacheLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/internal/resilience/CacheLoaderWriterResilienceStrategy.java new file mode 100644 index 0000000000..6235693ef9 --- /dev/null +++ b/core/src/main/java/org/ehcache/core/internal/resilience/CacheLoaderWriterResilienceStrategy.java @@ -0,0 +1,33 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.internal.resilience; + +import java.util.Map; + +public interface CacheLoaderWriterResilienceStrategy { + + V load(K key, Exception e) throws Exception; + + Map loadAll(Iterable keys, Exception e) throws Exception; + + void write(K key, V value, Exception e) throws Exception; + + void writeAll(Iterable> entries, Exception e) throws Exception; + + void delete(K key, Exception e) throws Exception; + + void deleteAll(Iterable keys, Exception e) throws Exception; +} diff --git a/core/src/main/java/org/ehcache/core/internal/resilience/DefaultCacheLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/internal/resilience/DefaultCacheLoaderWriterResilienceStrategy.java new file mode 100644 index 0000000000..d34e1daef9 --- /dev/null +++ b/core/src/main/java/org/ehcache/core/internal/resilience/DefaultCacheLoaderWriterResilienceStrategy.java @@ -0,0 +1,53 @@ +package org.ehcache.core.internal.resilience; + +import org.ehcache.core.resilience.RecoveryStore; + +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.StreamSupport; + +public class DefaultCacheLoaderWriterResilienceStrategy implements CacheLoaderWriterResilienceStrategy { + + private final RecoveryStore recoveryCache; + + public DefaultCacheLoaderWriterResilienceStrategy(RecoveryStore recoveryCache) { + this.recoveryCache = recoveryCache; + } + + @Override + public V load(K key, Exception e) throws Exception { + throw e; + } + + @Override + public Map loadAll(Iterable keys, Exception e) throws Exception { + throw e; + } + + @Override + public void write(K key, V value, Exception e) throws Exception { + recoveryCache.obliterate(key); + throw e; + } + + @Override + public void writeAll(Iterable> entries, Exception e) throws Exception { + recoveryCache.obliterate( + StreamSupport.stream(entries.spliterator(), false) + .map(entry -> entry.getKey()) + .collect(Collectors.toSet())); + throw e; + } + + @Override + public void delete(K key, Exception e) throws Exception { + recoveryCache.obliterate(key); + throw e; + } + + @Override + public void deleteAll(Iterable keys, Exception e) throws Exception { + recoveryCache.obliterate(keys); + throw e; + } +} diff --git a/core/src/main/java/org/ehcache/core/resilience/LoggingRobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/AbstractResilienceStrategy.java similarity index 84% rename from core/src/main/java/org/ehcache/core/resilience/LoggingRobustResilienceStrategy.java rename to core/src/main/java/org/ehcache/core/resilience/AbstractResilienceStrategy.java index 6edd5cb050..409e36eb82 100644 --- a/core/src/main/java/org/ehcache/core/resilience/LoggingRobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/AbstractResilienceStrategy.java @@ -13,26 +13,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.ehcache.core.resilience; import org.ehcache.Cache; -import org.ehcache.resilience.StoreAccessException; import org.ehcache.CacheIterationException; +import org.ehcache.resilience.ResilienceStrategy; +import org.ehcache.resilience.StoreAccessException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * - * @author cdennis */ -public class LoggingRobustResilienceStrategy extends RobustResilienceStrategy { +public abstract class AbstractResilienceStrategy implements ResilienceStrategy{ - private static final Logger LOGGER = LoggerFactory.getLogger(LoggingRobustResilienceStrategy.class); - - public LoggingRobustResilienceStrategy(RecoveryCache store) { - super(store); - } + private final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Override public Cache.Entry iteratorFailure(StoreAccessException e) { @@ -40,32 +35,26 @@ public Cache.Entry iteratorFailure(StoreAccessException e) { throw new CacheIterationException(e); } - @Override protected void recovered(K key, StoreAccessException from) { LOGGER.info("Ehcache key {} recovered from", key, from); } - @Override protected void recovered(Iterable keys, StoreAccessException from) { LOGGER.info("Ehcache keys {} recovered from", keys, from); } - @Override protected void recovered(StoreAccessException from) { LOGGER.info("Ehcache recovered from", from); } - @Override protected void inconsistent(K key, StoreAccessException because, StoreAccessException... cleanup) { LOGGER.error("Ehcache key {} in possible inconsistent state due to ", key, because); } - @Override protected void inconsistent(Iterable keys, StoreAccessException because, StoreAccessException... cleanup) { LOGGER.error("Ehcache keys {} in possible inconsistent state due to ", keys, because); } - @Override protected void inconsistent(StoreAccessException because, StoreAccessException... cleanup) { LOGGER.error("Ehcache in possible inconsistent state due to ", because); } diff --git a/core/src/main/java/org/ehcache/core/resilience/DefaultRecoveryStore.java b/core/src/main/java/org/ehcache/core/resilience/DefaultRecoveryStore.java new file mode 100644 index 0000000000..25e9208c06 --- /dev/null +++ b/core/src/main/java/org/ehcache/core/resilience/DefaultRecoveryStore.java @@ -0,0 +1,27 @@ +package org.ehcache.core.resilience; + +import org.ehcache.core.spi.store.Store; +import org.ehcache.resilience.StoreAccessException; + +/** + * @author Henri Tremblay + */ +public class DefaultRecoveryStore implements RecoveryStore { + + private final Store store; + + public DefaultRecoveryStore(Store store) { + this.store = store; + } + + @Override + public void obliterate() throws StoreAccessException { + store.clear(); + } + + @Override + public void obliterate(K key) throws StoreAccessException { + store.remove(key); + } + +} diff --git a/core/src/main/java/org/ehcache/core/resilience/RecoveryCache.java b/core/src/main/java/org/ehcache/core/resilience/RecoveryStore.java similarity index 82% rename from core/src/main/java/org/ehcache/core/resilience/RecoveryCache.java rename to core/src/main/java/org/ehcache/core/resilience/RecoveryStore.java index 06006dd481..e89ba32d41 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RecoveryCache.java +++ b/core/src/main/java/org/ehcache/core/resilience/RecoveryStore.java @@ -22,11 +22,16 @@ * * @author Chris Dennis */ -public interface RecoveryCache { +public interface RecoveryStore { void obliterate() throws StoreAccessException; void obliterate(K key) throws StoreAccessException; - void obliterate(Iterable keys) throws StoreAccessException; + default void obliterate(Iterable keys) throws StoreAccessException { + for (K key : keys) { + obliterate(key); + } + } + } diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java new file mode 100644 index 0000000000..fc3bfb23a6 --- /dev/null +++ b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java @@ -0,0 +1,252 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.resilience; + +import org.ehcache.core.spi.store.Store; +import org.ehcache.resilience.RethrowingStoreAccessException; +import org.ehcache.resilience.StoreAccessException; +import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; +import org.ehcache.spi.loaderwriter.BulkCacheWritingException; +import org.ehcache.spi.loaderwriter.CacheLoaderWriter; +import org.ehcache.spi.loaderwriter.CacheLoadingException; +import org.ehcache.spi.loaderwriter.CacheWritingException; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; + +import static java.util.Collections.emptyMap; + +/** + * + * @author Chris Dennis + */ +public class RobustLoaderWriterResilienceStrategy extends AbstractResilienceStrategy { + + private final RecoveryStore store; + private final CacheLoaderWriter loaderWriter; + + public RobustLoaderWriterResilienceStrategy(Store store, CacheLoaderWriter loaderWriter) { + this.store = new DefaultRecoveryStore<>(Objects.requireNonNull(store)); + this.loaderWriter = Objects.requireNonNull(loaderWriter); + } + + @Override + public V getFailure(K key, StoreAccessException e) { + cleanup(key, e); + try { + return loaderWriter.load(key); + } catch (Exception e1) { + throw new CacheLoadingException(e1); + } + } + + @Override + public boolean containsKeyFailure(K key, StoreAccessException e) { + cleanup(key, e); + return false; + } + + @Override + public void putFailure(K key, V value, StoreAccessException e) { + cleanup(key, e); + } + + @Override + public void putFailure(K key, V value, StoreAccessException e, CacheWritingException f) { + cleanup(key, e); + throw f; + } + + @Override + public void removeFailure(K key, StoreAccessException e) { + cleanup(key, e); + } + + @Override + public void removeFailure(K key, StoreAccessException e, CacheWritingException f) { + cleanup(key, e); + throw f; + } + + @Override + public void clearFailure(StoreAccessException e) { + cleanup(e); + } + + @Override + public V putIfAbsentFailure(K key, V value, V loaderWriterFunctionResult, StoreAccessException e, boolean knownToBeAbsent) { + cleanup(key, e); + if (loaderWriterFunctionResult != null && !loaderWriterFunctionResult.equals(value)) { + return loaderWriterFunctionResult; + } else { + return null; + } + } + + @Override + public V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheWritingException f) { + cleanup(key, e); + throw f; + } + + @Override + public V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheLoadingException f) { + cleanup(key, e); + throw f; + } + + @Override + public boolean removeFailure(K key, V value, StoreAccessException e, boolean knownToBePresent) { + cleanup(key, e); + return knownToBePresent; + } + + @Override + public boolean removeFailure(K key, V value, StoreAccessException e, CacheWritingException f) { + cleanup(key, e); + throw f; + } + + @Override + public boolean removeFailure(K key, V value, StoreAccessException e, CacheLoadingException f) { + cleanup(key, e); + throw f; + } + + @Override + public V replaceFailure(K key, V value, StoreAccessException e) { + cleanup(key, e); + return null; + } + + @Override + public V replaceFailure(K key, V value, StoreAccessException e, CacheWritingException f) { + cleanup(key, e); + throw f; + } + + @Override + public V replaceFailure(K key, V value, StoreAccessException e, CacheLoadingException f) { + cleanup(key, e); + throw f; + } + + @Override + public boolean replaceFailure(K key, V value, V newValue, StoreAccessException e, boolean knownToMatch) { + cleanup(key, e); + return knownToMatch; + } + + @Override + public boolean replaceFailure(K key, V value, V newValue, StoreAccessException e, CacheWritingException f) { + cleanup(key, e); + throw f; + } + + @Override + public boolean replaceFailure(K key, V value, V newValue, StoreAccessException e, CacheLoadingException f) { + cleanup(key, e); + throw f; + } + + @Override + public Map getAllFailure(Iterable keys, StoreAccessException e) { + cleanup(keys, e); + HashMap result = new HashMap<>(); + for (K key : keys) { + result.put(key, null); + } + return result; + } + + @Override + public Map getAllFailure(Iterable keys, Map loaded, StoreAccessException e) { + cleanup(keys, e); + return loaded; + } + + @Override + public Map getAllFailure(Iterable keys, StoreAccessException e, BulkCacheLoadingException f) { + cleanup(keys, e); + throw f; + } + + @Override + public void putAllFailure(Map entries, StoreAccessException e) { + cleanup(entries.keySet(), e); + } + + @Override + public void putAllFailure(Map entries, StoreAccessException e, BulkCacheWritingException f) { + cleanup(entries.keySet(), e); + throw f; + } + + @Override + public Map removeAllFailure(Iterable entries, StoreAccessException e) { + cleanup(entries, e); + return emptyMap(); + } + + @Override + public Map removeAllFailure(Iterable entries, StoreAccessException e, BulkCacheWritingException f) { + cleanup(entries, e); + throw f; + } + + private void cleanup(StoreAccessException from) { + filterException(from); + try { + store.obliterate(); + } catch (StoreAccessException e) { + inconsistent(from, e); + return; + } + recovered(from); + } + + private void cleanup(Iterable keys, StoreAccessException from) { + filterException(from); + try { + store.obliterate(keys); + } catch (StoreAccessException e) { + inconsistent(keys, from, e); + return; + } + recovered(keys, from); + } + + private void cleanup(K key, StoreAccessException from) { + filterException(from); + try { + store.obliterate(key); + } catch (StoreAccessException e) { + inconsistent(key, from, e); + return; + } + recovered(key, from); + } + + @Deprecated + void filterException(StoreAccessException cae) throws RuntimeException { + if (cae instanceof RethrowingStoreAccessException) { + throw ((RethrowingStoreAccessException) cae).getCause(); + } + } + +} diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java index 2a6511ed6b..74296161c7 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java @@ -18,8 +18,9 @@ import java.util.HashMap; import java.util.Map; +import java.util.Objects; -import org.ehcache.resilience.ResilienceStrategy; +import org.ehcache.core.spi.store.Store; import org.ehcache.resilience.RethrowingStoreAccessException; import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; @@ -33,12 +34,12 @@ * * @author Chris Dennis */ -public abstract class RobustResilienceStrategy implements ResilienceStrategy { +public class RobustResilienceStrategy extends AbstractResilienceStrategy { - private final RecoveryCache cache; + private final RecoveryStore store; - public RobustResilienceStrategy(RecoveryCache cache) { - this.cache = cache; + public RobustResilienceStrategy(Store store) { + this.store = new DefaultRecoveryStore<>(Objects.requireNonNull(store)); } @Override @@ -47,18 +48,6 @@ public V getFailure(K key, StoreAccessException e) { return null; } - @Override - public V getFailure(K key, V loaded, StoreAccessException e) { - cleanup(key, e); - return loaded; - } - - @Override - public V getFailure(K key, StoreAccessException e, CacheLoadingException f) { - cleanup(key, e); - throw f; - } - @Override public boolean containsKeyFailure(K key, StoreAccessException e) { cleanup(key, e); @@ -216,7 +205,7 @@ public Map removeAllFailure(Iterable entries, StoreAccessExce private void cleanup(StoreAccessException from) { filterException(from); try { - cache.obliterate(); + store.obliterate(); } catch (StoreAccessException e) { inconsistent(from, e); return; @@ -227,7 +216,7 @@ private void cleanup(StoreAccessException from) { private void cleanup(Iterable keys, StoreAccessException from) { filterException(from); try { - cache.obliterate(keys); + store.obliterate(keys); } catch (StoreAccessException e) { inconsistent(keys, from, e); return; @@ -238,7 +227,7 @@ private void cleanup(Iterable keys, StoreAccessException from) { private void cleanup(K key, StoreAccessException from) { filterException(from); try { - cache.obliterate(key); + store.obliterate(key); } catch (StoreAccessException e) { inconsistent(key, from, e); return; @@ -253,15 +242,4 @@ void filterException(StoreAccessException cae) throws RuntimeException { } } - protected abstract void recovered(K key, StoreAccessException from); - - protected abstract void recovered(Iterable keys, StoreAccessException from); - - protected abstract void recovered(StoreAccessException from); - - protected abstract void inconsistent(K key, StoreAccessException because, StoreAccessException... cleanup); - - protected abstract void inconsistent(Iterable keys, StoreAccessException because, StoreAccessException... cleanup); - - protected abstract void inconsistent(StoreAccessException because, StoreAccessException... cleanup); } diff --git a/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java b/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java index ad85ef4c48..a686dd68b5 100755 --- a/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java +++ b/core/src/main/java/org/ehcache/core/statistics/CacheOperationOutcomes.java @@ -135,16 +135,6 @@ enum ConditionalRemoveOutcome implements CacheOperationOutcomes { FAILURE } - /** - * The cache loading outcomes. - */ - enum CacheLoadingOutcome implements CacheOperationOutcomes { - /** success. */ - SUCCESS, - /** failure */ - FAILURE - } - /** * The putIfAbsent outcomes. */ diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java index ec8184d175..fab1f875af 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java @@ -220,14 +220,12 @@ protected static Supplier getBooleanSupplier() { protected final ResilienceStrategy setResilienceStrategySpy(final InternalCache ehcache) { assert ehcache != null; try { - final Field resilienceStrategyField = EhcacheBase.class.getDeclaredField("resilienceStrategy"); + Field resilienceStrategyField = EhcacheBase.class.getDeclaredField("resilienceStrategy"); resilienceStrategyField.setAccessible(true); @SuppressWarnings("unchecked") ResilienceStrategy resilienceStrategy = (ResilienceStrategy)resilienceStrategyField.get(ehcache); - if (resilienceStrategy != null) { - resilienceStrategy = spy(resilienceStrategy); - resilienceStrategyField.set(ehcache, resilienceStrategy); - } + resilienceStrategy = spy(resilienceStrategy); + resilienceStrategyField.set(ehcache, resilienceStrategy); return resilienceStrategy; } catch (Exception e) { throw new AssertionError(String.format("Unable to wrap ResilienceStrategy in Ehcache instance: %s", e)); diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java index 1f7aa76eef..6c6a0468de 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java @@ -298,9 +298,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeNoLoader() throws private void validateStatsNoneof(Ehcache cache) { validateStats(cache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - if (!(cache instanceof Ehcache)) { - validateStats(cache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); - } } /** diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java index 245795dc58..5b20a8ba5d 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java @@ -136,7 +136,6 @@ public void testGetAllEmptyRequestWithLoader() throws Exception { verify(this.loaderWriter, never()).loadAll(eq(Collections.emptySet())); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, 0, 0); } @@ -177,7 +176,6 @@ public void testGetAllStoreNoMatchLoaderAllFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -217,7 +215,6 @@ public void testGetAllStoreNoMatchLoaderAllFailWithBulkCacheLoadingException() t verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -257,7 +254,6 @@ public void testGetAllStoreNoMatchLoaderSomeFailWithBulkCacheLoadingException() verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -304,7 +300,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderAllFail() thro assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(KEY_SET_A)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -351,7 +346,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderAllFailWithBul verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -398,7 +392,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderSomeFailWithBu verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_C, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -443,7 +436,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderAllFail() throw assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(KEY_SET_A)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -488,7 +480,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderAllFailWithBulk verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -534,7 +525,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderSomeFailWithBul verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_C, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -568,7 +558,6 @@ public void testGetAllStoreNoMatchLoaderNoMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, 0, KEY_SET_A.size()); } @@ -608,7 +597,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderNoMatchNoneFai .getAllFailure(eq(KEY_SET_A), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -646,7 +634,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderNoMatchNoneFail .getAllFailure(eq(KEY_SET_A), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -686,7 +673,6 @@ public void testGetAllStoreNoMatchLoaderNoMatchSomeFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -733,7 +719,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderNoMatchSomeFai assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -781,7 +766,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderNoMatchSomeFail assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(failKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -817,7 +801,6 @@ public void testGetAllStoreNoMatchLoaderSomeMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, KEY_SET_C.size(), KEY_SET_A.size()); } @@ -859,7 +842,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderSomeMatchNoneF .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -899,7 +881,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderSomeMatchNoneFa .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -935,7 +916,6 @@ public void testGetAllStoreNoMatchLoaderSomeMatchDisjointFail() throws Exception verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, KEY_SET_C.size(), KEY_SET_A.size()); } @@ -977,7 +957,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderSomeMatchDisjo .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1017,7 +996,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderSomeMatchDisjoi .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1053,7 +1031,6 @@ public void testGetAllStoreNoMatchLoaderAllMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, KEY_SET_A.size() + KEY_SET_C.size(), 0); } @@ -1095,7 +1072,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionBeforeLoaderAllMatchNoneFa .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1135,7 +1111,6 @@ public void testGetAllStoreNoMatchStoreAccessExceptionAfterLoaderAllMatchNoneFai .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1179,7 +1154,6 @@ public void testGetAllStoreSomeMatchLoaderAllFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size(), 0); } @@ -1219,7 +1193,6 @@ public void testGetAllStoreSomeMatchLoaderAllFailWithBulkCacheLoadingException() verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size(), 0); } @@ -1259,7 +1232,6 @@ public void testGetAllStoreSomeMatchLoaderSomeFailWithBulkCacheLoadingException( verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size(), 0); } @@ -1307,7 +1279,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderAllFail() th assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1355,7 +1326,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderAllFailWithB verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), fetchKeys); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1403,7 +1373,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderLSomeFailWit verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_D, union(KEY_SET_A, KEY_SET_C)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1450,7 +1419,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderAllFail() thr assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1495,7 +1463,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderAllFailWithBu verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), fetchKeys); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1541,7 +1508,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderSomeFailWithB verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_C, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1578,7 +1544,6 @@ public void testGetAllStoreSomeMatchLoaderNoMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, KEY_SET_A.size(), KEY_SET_C.size()); } @@ -1620,7 +1585,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderNoMatchNoneF .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1660,7 +1624,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderNoMatchNoneFa .getAllFailure(eq(fetchKeys), eq(actual), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1701,7 +1664,6 @@ public void testGetAllStoreSomeMatchLoaderNoMatchSomeFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size(), 0); } @@ -1742,7 +1704,6 @@ public void testGetAllStoreSomeMatchLoaderNoMatchSomeFailWithBulkCacheLoadingExc verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size(), 0); } @@ -1789,7 +1750,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderNoMatchSomeF assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1837,7 +1797,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderNoMatchAllFa verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), fetchKeys); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1885,7 +1844,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderNoMatchSomeFa assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(failKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -1921,7 +1879,6 @@ public void testGetAllStoreSomeMatchLoaderSomeMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, KEY_SET_A.size() + KEY_SET_C.size(), KEY_SET_D.size()); } @@ -1963,7 +1920,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderSomeMatchNon .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2003,7 +1959,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderSomeMatchNone .getAllFailure(eq(fetchKeys), eq(actual), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2045,7 +2000,6 @@ public void testGetAllStoreSomeMatchLoaderSomeMatchDisjointFail() throws Excepti verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size() + KEY_SET_C.size(), 0); } @@ -2086,7 +2040,6 @@ public void testGetAllStoreSomeMatchLoaderSomeMatchDisjointFailWithBulkCacheLoad verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, KEY_SET_A.size(), 0); } @@ -2134,7 +2087,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderSomeMatchDis assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2182,7 +2134,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderSomeMatchDis verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_E, union(KEY_SET_A, KEY_SET_C)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2232,7 +2183,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderSomeMatchDisj assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(failKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2274,7 +2224,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderSomeMatchDisj assertThat(this.getLoadAllArgs(), equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2310,7 +2259,6 @@ public void testGetAllStoreSomeMatchLoaderAllMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -2352,7 +2300,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionBeforeLoaderAllMatchNone .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2392,7 +2339,6 @@ public void testGetAllStoreSomeMatchStoreAccessExceptionAfterLoaderAllMatchNoneF .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2432,7 +2378,6 @@ public void testGetAllStoreAllMatchLoaderAllFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -2480,7 +2425,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderAllFail() thr assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2528,7 +2472,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderAllFailWithBu verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), fetchKeys); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2577,7 +2520,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderSomeFailWithB verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_B, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2623,7 +2565,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderAllFail() thro assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2668,7 +2609,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderAllFailWithBul verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), fetchKeys); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2714,7 +2654,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderSomeFailWithBu verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_B, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2749,7 +2688,6 @@ public void testGetAllStoreAllMatchLoaderNoMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -2791,7 +2729,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderNoMatchNoneFa .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2826,7 +2763,6 @@ public void testGetAllStoreAllMatchLoaderNoMatchSomeFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -2873,7 +2809,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderNoMatchSomeFa assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2920,7 +2855,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderNoMatchSomeFa verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), Collections. emptySet(), fetchKeys); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -2965,7 +2899,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderNoMatchSomeFai assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3000,7 +2933,6 @@ public void testGetAllStoreAllMatchLoaderSomeMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -3041,7 +2973,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderSomeMatchNone .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3080,7 +3011,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderSomeMatchNoneF .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3116,7 +3046,6 @@ public void testGetAllStoreAllMatchLoaderSomeMatchDisjointFail() throws Exceptio verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -3163,7 +3092,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderSomeMatchDisj assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3212,7 +3140,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderSomeMatchDisj verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_B, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3258,7 +3185,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderSomeMatchDisjo assertThat(this.bulkExceptionCaptor.getValue().getFailures().keySet(), Matchers.>equalTo(fetchKeys)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3304,7 +3230,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderSomeMatchDisjo verifyBulkLoadingException(this.bulkExceptionCaptor.getValue(), KEY_SET_B, KEY_SET_A); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3339,7 +3264,6 @@ public void testGetAllStoreAllMatchLoaderAllMatchNoneFail() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); validateBulkCounters(ehcache, fetchKeys.size(), 0); } @@ -3382,7 +3306,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionBeforeLoaderAllMatchNoneF .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } @@ -3423,7 +3346,6 @@ public void testGetAllStoreAllMatchStoreAccessExceptionAfterLoaderAllMatchNoneFa .getAllFailure(eq(fetchKeys), eq(expected), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.FAILURE)); validateBulkCounters(ehcache, 0, 0); } diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java index 905d3cc3f3..af5f2b710e 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetTest.java @@ -38,7 +38,6 @@ import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -80,9 +79,8 @@ public void testGetNoStoreEntry() throws Exception { assertThat(ehcache.get("key"), is(nullValue())); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); - verifyZeroInteractions(this.spiedResilienceStrategy); + verifyZeroInteractions(this.spiedResilienceStrategy, this.cacheLoaderWriter); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.MISS)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); } /** @@ -105,7 +103,6 @@ public void testGetNoStoreEntryNoCacheLoaderWriterEntry() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.MISS)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.SUCCESS)); } /** @@ -129,7 +126,6 @@ public void testGetNoStoreEntryHasCacheLoaderWriterEntry() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.SUCCESS)); } /** @@ -157,7 +153,6 @@ public void testGetNoStoreEntryCacheLoadingException() throws Exception { verify(this.cacheLoaderWriter).load(eq("key")); verifyZeroInteractions(this.spiedResilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.GetOutcome.class)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.FAILURE)); } /** @@ -179,9 +174,8 @@ public void testGetNoStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry() th ehcache.get("key"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoaderWriter).load(eq("key")); - verify(this.spiedResilienceStrategy).getFailure(eq("key"), (String) isNull(), any(StoreAccessException.class)); + verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.FAILURE)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.SUCCESS)); } /** @@ -204,9 +198,8 @@ public void testGetNoStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry() t ehcache.get("key"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoaderWriter).load(eq("key")); - verify(this.spiedResilienceStrategy).getFailure(eq("key"), eq("value"), any(StoreAccessException.class)); + verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.FAILURE)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.SUCCESS)); } /** @@ -234,9 +227,8 @@ public void testGetNoStoreEntryStoreAccessExceptionCacheLoadingException() throw } verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoaderWriter).load(eq("key")); - verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class), any(CacheLoadingException.class)); + verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.FAILURE)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.FAILURE)); } /** @@ -255,10 +247,9 @@ public void testGetHasStoreEntry() throws Exception { assertThat(ehcache.get("key"), equalTo("value")); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); - verifyZeroInteractions(this.spiedResilienceStrategy); + verifyZeroInteractions(this.spiedResilienceStrategy, this.cacheLoaderWriter); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); } /** @@ -282,7 +273,6 @@ public void testGetHasStoreEntryNoCacheLoaderWriterEntry() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); } /** @@ -307,7 +297,6 @@ public void testGetHasStoreEntryHasCacheLoaderWriterEntry() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); } /** @@ -332,7 +321,6 @@ public void testGetHasStoreEntryCacheLoadingException() throws Exception { verifyZeroInteractions(this.spiedResilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)); - validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.CacheLoadingOutcome.class)); } /** @@ -355,9 +343,8 @@ public void testGetHasStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry() t ehcache.get("key"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoaderWriter).load(eq("key")); - verify(this.spiedResilienceStrategy).getFailure(eq("key"), (String) isNull(), any(StoreAccessException.class)); + verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.FAILURE)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.SUCCESS)); } /** @@ -381,9 +368,8 @@ public void testGetHasStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry() ehcache.get("key"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoaderWriter).load(eq("key")); - verify(this.spiedResilienceStrategy).getFailure(eq("key"), eq("value"), any(StoreAccessException.class)); + verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.FAILURE)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.SUCCESS)); } /** @@ -396,7 +382,7 @@ public void testGetHasStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry() */ @Test public void testGetHasStoreEntryStoreAccessExceptionCacheLoadingException() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "value")); + FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "value")); this.store = spy(fakeStore); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); doThrow(new StoreAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); @@ -412,9 +398,8 @@ public void testGetHasStoreEntryStoreAccessExceptionCacheLoadingException() thro } verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); verify(this.cacheLoaderWriter).load(eq("key")); - verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class), any(CacheLoadingException.class)); + verify(this.spiedResilienceStrategy).getFailure(eq("key"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.FAILURE)); - validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.CacheLoadingOutcome.FAILURE)); } /** From 02cf3603aa6986ba8dde7435c07d232916ac6f6e Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 17 Jan 2018 13:38:28 -0500 Subject: [PATCH 124/779] Push fallback write to the resilience strategy (#2198) --- .../resilience/ResilienceStrategy.java | 12 ------- .../main/java/org/ehcache/core/Ehcache.java | 30 ++--------------- .../java/org/ehcache/core/EhcacheBase.java | 32 +++++++++++++++++++ .../ehcache/core/EhcacheWithLoaderWriter.java | 32 ++++--------------- .../RobustLoaderWriterResilienceStrategy.java | 13 ++++---- .../resilience/RobustResilienceStrategy.java | 6 ---- .../EhcacheWithLoaderWriterBasicPutTest.java | 14 ++++---- 7 files changed, 53 insertions(+), 86 deletions(-) diff --git a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java index e3ac98db43..469491c18f 100644 --- a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java +++ b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java @@ -77,18 +77,6 @@ public interface ResilienceStrategy { */ void putFailure(K key, V value, StoreAccessException e); - /** - * Called when a {@link Cache#put(java.lang.Object, java.lang.Object)} fails - * due to an underlying store failure, and the associated cache write - * operation also failed. - * - * @param key the key being put - * @param value the value being put - * @param e the cache failure - * @param f the writer failure - */ - void putFailure(K key, V value, StoreAccessException e, CacheWritingException f); - /** * Called when a {@link Cache#remove(java.lang.Object)} fails due to an * underlying store failure. diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index b2e49cbe34..c1bad0bc27 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -89,34 +89,8 @@ protected Store.ValueHolder doGet(K key) throws StoreAccessException { return store.get(key); } - /** - * {@inheritDoc} - */ - @Override - public void put(final K key, final V value) { - putObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key, value); - - try { - PutStatus status = store.put(key, value); - switch (status) { - case PUT: - putObserver.end(PutOutcome.PUT); - break; - case NOOP: - putObserver.end(PutOutcome.NOOP); - break; - default: - throw new AssertionError("Invalid Status."); - } - } catch (StoreAccessException e) { - try { - resilienceStrategy.putFailure(key, value, e); - } finally { - putObserver.end(PutOutcome.FAILURE); - } - } + protected Store.PutStatus doPut(K key, V value) throws StoreAccessException { + return store.put(key, value); } protected boolean removeInternal(final K key) { diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index dd6ea722c1..0291b1c5b7 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -167,6 +167,38 @@ protected V getNoLoader(K key) { } } + /** + * {@inheritDoc} + */ + @Override + public void put(K key, V value) { + putObserver.begin(); + statusTransitioner.checkAvailable(); + checkNonNull(key, value); + + try { + Store.PutStatus status = doPut(key, value); + switch (status) { + case PUT: + putObserver.end(PutOutcome.PUT); + break; + case NOOP: + putObserver.end(PutOutcome.NOOP); + break; + default: + throw new AssertionError("Invalid Status."); + } + } catch (StoreAccessException e) { + try { + resilienceStrategy.putFailure(key, value, e); + } finally { + putObserver.end(PutOutcome.FAILURE); + } + } + } + + protected abstract Store.PutStatus doPut(K key, V value) throws StoreAccessException; + /** * {@inheritDoc} */ diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index abf53e3f87..9ed877997a 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -106,6 +106,7 @@ public EhcacheWithLoaderWriter(CacheConfiguration configuration, Store doGet(K key) throws StoreAccessException { Function mappingFunction = k -> { try { @@ -118,40 +119,19 @@ protected Store.ValueHolder doGet(K key) throws StoreAccessException { return store.computeIfAbsent(key, mappingFunction); } - /** - * {@inheritDoc} - */ @Override - public void put(final K key, final V value) throws CacheWritingException { - putObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key, value); - - final BiFunction remappingFunction = memoize((key1, previousValue) -> { + public Store.PutStatus doPut(K key, V value) throws StoreAccessException { + BiFunction remappingFunction = (key1, previousValue) -> { try { cacheLoaderWriter.write(key1, value); } catch (Exception e) { throw new StorePassThroughException(newCacheWritingException(e)); } return value; - }); + }; - try { - store.compute(key, remappingFunction); - putObserver.end(PutOutcome.PUT); - } catch (StoreAccessException e) { - try { - try { - remappingFunction.apply(key, value); - } catch (StorePassThroughException cpte) { - resilienceStrategy.putFailure(key, value, e, (CacheWritingException) cpte.getCause()); - return; - } - resilienceStrategy.putFailure(key, value, e); - } finally { - putObserver.end(PutOutcome.FAILURE); - } - } + store.compute(key, remappingFunction); + return Store.PutStatus.PUT; } protected boolean removeInternal(final K key) throws CacheWritingException { diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java index fc3bfb23a6..578f4d5970 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java @@ -16,6 +16,7 @@ package org.ehcache.core.resilience; +import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.Store; import org.ehcache.resilience.RethrowingStoreAccessException; import org.ehcache.resilience.StoreAccessException; @@ -30,6 +31,7 @@ import java.util.Objects; import static java.util.Collections.emptyMap; +import static org.ehcache.core.exceptions.ExceptionFactory.newCacheWritingException; /** * @@ -64,12 +66,11 @@ public boolean containsKeyFailure(K key, StoreAccessException e) { @Override public void putFailure(K key, V value, StoreAccessException e) { cleanup(key, e); - } - - @Override - public void putFailure(K key, V value, StoreAccessException e, CacheWritingException f) { - cleanup(key, e); - throw f; + try { + loaderWriter.write(key, value); + } catch (Exception e1) { + throw new CacheWritingException(e1); + } } @Override diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java index 74296161c7..79989057fb 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java @@ -59,12 +59,6 @@ public void putFailure(K key, V value, StoreAccessException e) { cleanup(key, e); } - @Override - public void putFailure(K key, V value, StoreAccessException e, CacheWritingException f) { - cleanup(key, e); - throw f; - } - @Override public void removeFailure(K key, StoreAccessException e) { cleanup(key, e); diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java index 037d94f59f..1f3e30bf64 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutTest.java @@ -226,8 +226,8 @@ public void testPutNoStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry() th ehcache.put("key", "value"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy).putFailure(eq("key"), eq("value"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.FAILURE)); } @@ -254,8 +254,8 @@ public void testPutNoStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry() t ehcache.put("key", "value"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy).putFailure(eq("key"), eq("value"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.FAILURE)); } @@ -288,9 +288,8 @@ public void testPutNoStoreEntryStoreAccessExceptionCacheLoaderWriterException() // Expected } verify(this.store).compute(eq("key"), getAnyBiFunction()); + ordered.verify(this.spiedResilienceStrategy).putFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); - ordered.verify(this.spiedResilienceStrategy) - .putFailure(eq("key"), eq("value"), any(StoreAccessException.class), any(CacheWritingException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.FAILURE)); } @@ -432,8 +431,8 @@ public void testPutHasStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry() t ehcache.put("key", "value"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy).putFailure(eq("key"), eq("value"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.FAILURE)); } @@ -460,8 +459,8 @@ public void testPutHasStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry() ehcache.put("key", "value"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); ordered.verify(this.spiedResilienceStrategy).putFailure(eq("key"), eq("value"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); assertThat(fakeWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.FAILURE)); } @@ -494,9 +493,8 @@ public void testPutHasStoreEntryStoreAccessExceptionCacheLoaderWriterException() // Expected } verify(this.store).compute(eq("key"), getAnyBiFunction()); + ordered.verify(this.spiedResilienceStrategy).putFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); - ordered.verify(this.spiedResilienceStrategy) - .putFailure(eq("key"), eq("value"), any(StoreAccessException.class), any(CacheWritingException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.FAILURE)); } From a0d95fd515c8facebed5ddb5b7beae301021c7ee Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Wed, 17 Jan 2018 14:05:17 -0500 Subject: [PATCH 125/779] Push fallback delete to the resilience strategy (#2198) --- .../resilience/ResilienceStrategy.java | 11 ------- .../main/java/org/ehcache/core/Ehcache.java | 25 ++------------- .../java/org/ehcache/core/EhcacheBase.java | 26 +++++++++++++++- .../ehcache/core/EhcacheWithLoaderWriter.java | 31 +++---------------- .../RobustLoaderWriterResilienceStrategy.java | 11 +++---- .../resilience/RobustResilienceStrategy.java | 6 ---- ...hcacheWithLoaderWriterBasicRemoveTest.java | 14 ++++----- 7 files changed, 43 insertions(+), 81 deletions(-) diff --git a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java index 469491c18f..572ae5734a 100644 --- a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java +++ b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java @@ -86,17 +86,6 @@ public interface ResilienceStrategy { */ void removeFailure(K key, StoreAccessException e); - /** - * Called when a {@link Cache#remove(java.lang.Object)} fails - * due to an underlying store failure, and the associated cache write - * operation also failed. - * - * @param key the key being removed - * @param e the cache failure - * @param f the writer failure - */ - void removeFailure(K key, StoreAccessException e, CacheWritingException f); - /** * Called when a {@link Cache#clear()} fails due to an underlying store * failure. diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index c1bad0bc27..621ab723da 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -52,6 +52,7 @@ import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; +import org.ehcache.spi.loaderwriter.CacheWritingException; import org.slf4j.Logger; /** @@ -93,28 +94,8 @@ protected Store.PutStatus doPut(K key, V value) throws StoreAccessException { return store.put(key, value); } - protected boolean removeInternal(final K key) { - removeObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - - boolean removed = false; - try { - removed = store.remove(key); - if (removed) { - removeObserver.end(RemoveOutcome.SUCCESS); - } else { - removeObserver.end(RemoveOutcome.NOOP); - } - } catch (StoreAccessException e) { - try { - resilienceStrategy.removeFailure(key, e); - } finally { - removeObserver.end(RemoveOutcome.FAILURE); - } - } - - return removed; + protected boolean doRemoveInternal(final K key) throws StoreAccessException { + return store.remove(key); } protected Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index 0291b1c5b7..c60cd174d1 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -221,7 +221,31 @@ public void remove(K key) throws CacheWritingException { removeInternal(key); // ignore return value; } - protected abstract boolean removeInternal(final K key); + protected boolean removeInternal(final K key) { + removeObserver.begin(); + statusTransitioner.checkAvailable(); + checkNonNull(key); + + boolean removed = false; + try { + removed = doRemoveInternal(key); + if (removed) { + removeObserver.end(RemoveOutcome.SUCCESS); + } else { + removeObserver.end(RemoveOutcome.NOOP); + } + } catch (StoreAccessException e) { + try { + resilienceStrategy.removeFailure(key, e); + } finally { + removeObserver.end(RemoveOutcome.FAILURE); + } + } + + return removed; + } + + protected abstract boolean doRemoveInternal(final K key) throws StoreAccessException; /** * {@inheritDoc} diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index 9ed877997a..9b42fa81b3 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -134,14 +134,10 @@ public Store.PutStatus doPut(K key, V value) throws StoreAccessException { return Store.PutStatus.PUT; } - protected boolean removeInternal(final K key) throws CacheWritingException { - removeObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - - final AtomicBoolean modified = new AtomicBoolean(); + protected boolean doRemoveInternal(final K key) throws StoreAccessException { + AtomicBoolean modified = new AtomicBoolean(); - final BiFunction remappingFunction = memoize((key1, previousValue) -> { + BiFunction remappingFunction = memoize((key1, previousValue) -> { modified.set(previousValue != null); try { @@ -152,26 +148,7 @@ protected boolean removeInternal(final K key) throws CacheWritingException { return null; }); - try { - store.compute(key, remappingFunction); - if (modified.get()) { - removeObserver.end(RemoveOutcome.SUCCESS); - } else { - removeObserver.end(RemoveOutcome.NOOP); - } - } catch (StoreAccessException e) { - try { - try { - remappingFunction.apply(key, null); - } catch (StorePassThroughException f) { - resilienceStrategy.removeFailure(key, e, (CacheWritingException) f.getCause()); - } - resilienceStrategy.removeFailure(key, e); - } finally { - removeObserver.end(RemoveOutcome.FAILURE); - } - } - + store.compute(key, remappingFunction); return modified.get(); } diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java index 578f4d5970..c9b5bab309 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java @@ -76,12 +76,11 @@ public void putFailure(K key, V value, StoreAccessException e) { @Override public void removeFailure(K key, StoreAccessException e) { cleanup(key, e); - } - - @Override - public void removeFailure(K key, StoreAccessException e, CacheWritingException f) { - cleanup(key, e); - throw f; + try { + loaderWriter.delete(key); + } catch(Exception e1) { + throw new CacheWritingException(e1); + } } @Override diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java index 79989057fb..138497dee9 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java @@ -64,12 +64,6 @@ public void removeFailure(K key, StoreAccessException e) { cleanup(key, e); } - @Override - public void removeFailure(K key, StoreAccessException e, CacheWritingException f) { - cleanup(key, e); - throw f; - } - @Override public void clearFailure(StoreAccessException e) { cleanup(e); diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java index c34ecbbae4..3018593423 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicRemoveTest.java @@ -200,8 +200,8 @@ public void testRemoveNoStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry() ehcache.remove("key"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).delete(eq("key")); ordered.verify(this.spiedResilienceStrategy).removeFailure(eq("key"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).delete(eq("key")); assertThat(fakeWriter.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); } @@ -228,8 +228,8 @@ public void testRemoveNoStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry( ehcache.remove("key"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).delete(eq("key")); ordered.verify(this.spiedResilienceStrategy).removeFailure(eq("key"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).delete(eq("key")); assertThat(fakeWriter.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); } @@ -262,9 +262,8 @@ public void testRemoveNoStoreEntryStoreAccessExceptionCacheLoaderWriterException // Expected } verify(this.store).compute(eq("key"), getAnyBiFunction()); + ordered.verify(this.spiedResilienceStrategy).removeFailure(eq("key"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).delete(eq("key")); - ordered.verify(this.spiedResilienceStrategy) - .removeFailure(eq("key"), any(StoreAccessException.class), any(CacheWritingException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); } @@ -406,8 +405,8 @@ public void testRemoveHasStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry( ehcache.remove("key"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).delete(eq("key")); ordered.verify(this.spiedResilienceStrategy).removeFailure(eq("key"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).delete(eq("key")); assertThat(fakeWriter.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); } @@ -434,8 +433,8 @@ public void testRemoveHasStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry ehcache.remove("key"); verify(this.store).compute(eq("key"), getAnyBiFunction()); - ordered.verify(this.cacheLoaderWriter).delete(eq("key")); ordered.verify(this.spiedResilienceStrategy).removeFailure(eq("key"), any(StoreAccessException.class)); + ordered.verify(this.cacheLoaderWriter).delete(eq("key")); assertThat(fakeWriter.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); } @@ -468,9 +467,8 @@ public void testRemoveHasStoreEntryStoreAccessExceptionCacheLoaderWriterExceptio // Expected } verify(this.store).compute(eq("key"), getAnyBiFunction()); + ordered.verify(this.spiedResilienceStrategy).removeFailure(eq("key"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).delete(eq("key")); - ordered.verify(this.spiedResilienceStrategy) - .removeFailure(eq("key"), any(StoreAccessException.class), any(CacheWritingException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.FAILURE)); } From 366ad43b71d0e975f49c1e7df1057d4a33b3719e Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Fri, 19 Jan 2018 13:42:04 -0500 Subject: [PATCH 126/779] Push fallback putIfAbsent to the resilience strategy (#2198) --- .../resilience/ResilienceStrategy.java | 29 +---------- .../main/java/org/ehcache/core/Ehcache.java | 30 +++--------- .../java/org/ehcache/core/EhcacheBase.java | 39 ++++++++++++++- .../ehcache/core/EhcacheWithLoaderWriter.java | 48 +++---------------- .../RobustLoaderWriterResilienceStrategy.java | 39 ++++++++------- .../resilience/RobustResilienceStrategy.java | 20 +------- .../core/EhcacheBasicPutIfAbsentTest.java | 4 +- ...eWithLoaderWriterBasicPutIfAbsentTest.java | 46 ++++++++---------- 8 files changed, 96 insertions(+), 159 deletions(-) diff --git a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java index 572ae5734a..760da0e2c3 100644 --- a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java +++ b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java @@ -114,36 +114,9 @@ public interface ResilienceStrategy { * @param key the key being put * @param value the value being put * @param e the triggered failure - * @param knownToBeAbsent {@code true} if the value is known to be absent * @return the value to return from the operation */ - V putIfAbsentFailure(K key, V value, V loaderWriterFunctionResult, StoreAccessException e, boolean knownToBeAbsent); - - /** - * Called when a {@link Cache#putIfAbsent(java.lang.Object, java.lang.Object)} - * fails due to an underlying store failure, and the associated cache write - * operation also failed. - * - * @param key the key being put - * @param value the value being put - * @param e the cache failure - * @param f the writer failure - * @return the value to return from the operation - */ - V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheWritingException f); - - /** - * Called when a {@link Cache#putIfAbsent(java.lang.Object, java.lang.Object)} - * fails due to an underlying store failure, and the associated cache load - * operation also failed. - * - * @param key the key being put - * @param value the value being put - * @param e the cache failure - * @param f the loader failure - * @return the value to return from the operation - */ - V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheLoadingException f); + V putIfAbsentFailure(K key, V value, StoreAccessException e); /** * Called when a {@link Cache#remove(java.lang.Object, java.lang.Object)} diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index 621ab723da..04ee8bdeb6 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -208,32 +209,13 @@ public void removeAll(final Set keys) throws BulkCacheWritingExcept } } - /** - * {@inheritDoc} - */ @Override - public V putIfAbsent(final K key, final V value) { - putIfAbsentObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key, value); - - try { - ValueHolder inCache = store.putIfAbsent(key, value); - boolean absent = (inCache == null); - if (absent) { - putIfAbsentObserver.end(PutIfAbsentOutcome.PUT); - return null; - } else { - putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return inCache.get(); - } - } catch (StoreAccessException e) { - try { - return resilienceStrategy.putIfAbsentFailure(key, value, null, e, false); // FIXME: We can't know if it's absent or not - } finally { - putIfAbsentObserver.end(PutIfAbsentOutcome.FAILURE); - } + public ValueHolder doPutIfAbsent(final K key, final V value, Consumer put) throws StoreAccessException { + ValueHolder result = store.putIfAbsent(key, value); + if(result == null) { + put.accept(true); } + return result; } /** diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index c60cd174d1..61288745a1 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -19,7 +19,6 @@ import org.ehcache.Status; import org.ehcache.config.CacheRuntimeConfiguration; import org.ehcache.core.events.CacheEventDispatcher; -import org.ehcache.core.resilience.RecoveryStore; import org.ehcache.core.spi.LifeCycled; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.ValueHolder; @@ -53,7 +52,9 @@ import java.util.NoSuchElementException; import java.util.Objects; import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.LongAdder; +import java.util.function.Consumer; import java.util.function.Function; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; @@ -148,7 +149,7 @@ protected V getNoLoader(K key) { checkNonNull(key); try { - final Store.ValueHolder valueHolder = store.get(key); + Store.ValueHolder valueHolder = store.get(key); // Check for expiry first if (valueHolder == null) { @@ -263,6 +264,40 @@ public void clear() { } } + /** + * {@inheritDoc} + */ + @Override + public V putIfAbsent(final K key, final V value) { + putIfAbsentObserver.begin(); + statusTransitioner.checkAvailable(); + checkNonNull(key, value); + + AtomicBoolean put = new AtomicBoolean(false); + + try { + ValueHolder inCache = doPutIfAbsent(key, value, b -> put.set(b)); + if(put.get()) { + putIfAbsentObserver.end(PutIfAbsentOutcome.PUT); + return null; + } else if (inCache == null) { + putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); + return null; + } else { + putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); + return inCache.get(); + } + } catch (StoreAccessException e) { + try { + return resilienceStrategy.putIfAbsentFailure(key, value, e); // FIXME: We can't know if it's absent or not + } finally { + putIfAbsentObserver.end(PutIfAbsentOutcome.FAILURE); + } + } + } + + protected abstract ValueHolder doPutIfAbsent(K key, V value, Consumer put) throws StoreAccessException; + /** * {@inheritDoc} */ diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index 9b42fa81b3..82915b27e6 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -53,6 +53,7 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiFunction; +import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; @@ -100,7 +101,7 @@ public EhcacheWithLoaderWriter(CacheConfiguration configuration, Store runtimeConfiguration, Store store, CacheLoaderWriter cacheLoaderWriter, CacheEventDispatcher eventDispatcher, boolean useLoaderInAtomics, Logger logger, StatusTransitioner statusTransitioner) { - super(runtimeConfiguration, store, new RobustLoaderWriterResilienceStrategy<>(store, cacheLoaderWriter), eventDispatcher, logger, statusTransitioner); + super(runtimeConfiguration, store, new RobustLoaderWriterResilienceStrategy<>(store, cacheLoaderWriter, useLoaderInAtomics), eventDispatcher, logger, statusTransitioner); this.cacheLoaderWriter = Objects.requireNonNull(cacheLoaderWriter, "CacheLoaderWriter cannot be null"); this.useLoaderInAtomics = useLoaderInAtomics; @@ -480,13 +481,9 @@ private Set cacheLoaderWriterDeleteAllCall(Iterable doPutIfAbsent(K key, V value, Consumer put) throws StoreAccessException { - final Function mappingFunction = memoize(k -> { + Function mappingFunction = k -> { if (useLoaderInAtomics) { try { V loaded = cacheLoaderWriter.load(k); @@ -504,42 +501,11 @@ public V putIfAbsent(final K key, final V value) throws CacheWritingException { throw new StorePassThroughException(newCacheWritingException(e)); } - installed.set(true); + put.accept(true); return value; - }); + }; - try { - ValueHolder inCache = store.computeIfAbsent(key, mappingFunction); - if (installed.get()) { - putIfAbsentObserver.end(PutIfAbsentOutcome.PUT); - return null; - } else if (inCache == null) { - putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return null; - } else { - putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return inCache.get(); - } - } catch (StoreAccessException e) { - try { - V loaded; - try { - loaded = mappingFunction.apply(key); - } catch (StorePassThroughException f) { - Throwable cause = f.getCause(); - if(cause instanceof CacheLoadingException) { - return resilienceStrategy.putIfAbsentFailure(key, value, e, (CacheLoadingException) cause); - } else if(cause instanceof CacheWritingException) { - return resilienceStrategy.putIfAbsentFailure(key, value, e, (CacheWritingException) cause); - } else { - throw new AssertionError(); - } - } - return resilienceStrategy.putIfAbsentFailure(key, value, loaded, e, installed.get()); - } finally { - putIfAbsentObserver.end(PutIfAbsentOutcome.FAILURE); - } - } + return store.computeIfAbsent(key, mappingFunction); } /** diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java index c9b5bab309..8889eb8c19 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java @@ -18,6 +18,7 @@ import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.Store; +import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.resilience.RethrowingStoreAccessException; import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; @@ -29,8 +30,10 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; +import java.util.function.Function; import static java.util.Collections.emptyMap; +import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; import static org.ehcache.core.exceptions.ExceptionFactory.newCacheWritingException; /** @@ -41,10 +44,12 @@ public class RobustLoaderWriterResilienceStrategy extends AbstractResilien private final RecoveryStore store; private final CacheLoaderWriter loaderWriter; + private final boolean useLoaderInAtomics; - public RobustLoaderWriterResilienceStrategy(Store store, CacheLoaderWriter loaderWriter) { + public RobustLoaderWriterResilienceStrategy(Store store, CacheLoaderWriter loaderWriter, boolean useLoaderInAtomics) { this.store = new DefaultRecoveryStore<>(Objects.requireNonNull(store)); this.loaderWriter = Objects.requireNonNull(loaderWriter); + this.useLoaderInAtomics = useLoaderInAtomics; } @Override @@ -89,25 +94,23 @@ public void clearFailure(StoreAccessException e) { } @Override - public V putIfAbsentFailure(K key, V value, V loaderWriterFunctionResult, StoreAccessException e, boolean knownToBeAbsent) { + public V putIfAbsentFailure(K key, V value, StoreAccessException e) { cleanup(key, e); - if (loaderWriterFunctionResult != null && !loaderWriterFunctionResult.equals(value)) { - return loaderWriterFunctionResult; - } else { - return null; + // FIXME: This is not atomic + try { + V loaded = loaderWriter.load(key); + if(loaded != null) { + return loaded; + } + } catch (Exception e1) { + throw new CacheLoadingException(e1); } - } - - @Override - public V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheWritingException f) { - cleanup(key, e); - throw f; - } - - @Override - public V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheLoadingException f) { - cleanup(key, e); - throw f; + try { + loaderWriter.write(key, value); + } catch (Exception e1) { + throw new CacheWritingException(e1); + } + return null; } @Override diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java index 138497dee9..ee13eb96d0 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java @@ -70,25 +70,9 @@ public void clearFailure(StoreAccessException e) { } @Override - public V putIfAbsentFailure(K key, V value, V loaderWriterFunctionResult, StoreAccessException e, boolean knownToBeAbsent) { + public V putIfAbsentFailure(K key, V value, StoreAccessException e) { cleanup(key, e); - if (loaderWriterFunctionResult != null && !loaderWriterFunctionResult.equals(value)) { - return loaderWriterFunctionResult; - } else { - return null; - } - } - - @Override - public V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheWritingException f) { - cleanup(key, e); - throw f; - } - - @Override - public V putIfAbsentFailure(K key, V value, StoreAccessException e, CacheLoadingException f) { - cleanup(key, e); - throw f; + return null; // Should it be 'value'? } @Override diff --git a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java index ded2a39359..d6e3297326 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java @@ -142,7 +142,7 @@ public void testPutIfAbsentNoStoreEntryStoreAccessException() throws Exception { ehcache.putIfAbsent("key", "value"); verify(this.store).putIfAbsent(eq("key"), eq("value")); verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), (String) isNull(), any(StoreAccessException.class), eq(false)); + .putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } @@ -164,7 +164,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessException() throws Exception ehcache.putIfAbsent("key", "value"); verify(this.store).putIfAbsent(eq("key"), eq("value")); verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), (String) isNull(), any(StoreAccessException.class), eq(false)); + .putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java index 074026ed86..018bd31b4f 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicPutIfAbsentTest.java @@ -104,7 +104,7 @@ public void testPutIfAbsentNullValue() { */ @Test public void testPutIfAbsentNoStoreEntry() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); final EhcacheWithLoaderWriter ehcache = this.getEhcache(this.cacheLoaderWriter); @@ -145,10 +145,10 @@ public void testPutIfAbsentHasStoreEntry() throws Exception { */ @Test public void testPutIfAbsentNoStoreEntryNoCacheLoaderWriterEntry() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); final EhcacheWithLoaderWriter ehcache = this.getEhcache(fakeLoaderWriter); assertThat(ehcache.putIfAbsent("key", "value"), is(nullValue())); @@ -171,7 +171,7 @@ public void testPutIfAbsentHasStoreEntryNoCacheLoaderWriterEntry() throws Except final FakeStore fakeStore = new FakeStore(Collections.singletonMap("key", "oldValue")); this.store = spy(fakeStore); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); final EhcacheWithLoaderWriter ehcache = this.getEhcache(fakeLoaderWriter); assertThat(ehcache.putIfAbsent("key", "value"), is(equalTo("oldValue"))); @@ -192,11 +192,11 @@ public void testPutIfAbsentHasStoreEntryNoCacheLoaderWriterEntry() throws Except */ @Test public void testPutIfAbsentNoStoreEntryStoreAccessExceptionNoCacheLoaderWriterEntry() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); this.cacheLoaderWriter = spy(fakeLoaderWriter); final EhcacheWithLoaderWriter ehcache = this.getEhcache(this.cacheLoaderWriter); @@ -204,9 +204,8 @@ public void testPutIfAbsentNoStoreEntryStoreAccessExceptionNoCacheLoaderWriterEn assertThat(ehcache.putIfAbsent("key", "value"), nullValue()); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); + ordered.verify(this.spiedResilienceStrategy).putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); - ordered.verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), eq("value"), any(StoreAccessException.class), eq(true)); assertThat(fakeLoaderWriter.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } @@ -225,7 +224,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionNoCacheLoaderWriterE this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); this.cacheLoaderWriter = spy(fakeLoaderWriter); final EhcacheWithLoaderWriter ehcache = this.getEhcache(this.cacheLoaderWriter); @@ -233,9 +232,8 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionNoCacheLoaderWriterE assertThat(ehcache.putIfAbsent("key", "value"), nullValue()); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); + ordered.verify(this.spiedResilienceStrategy).putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); - ordered.verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), eq("value"), any(StoreAccessException.class), eq(true)); // Broken initial state: CacheLoaderWriter check omitted validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } @@ -249,7 +247,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionNoCacheLoaderWriterE */ @Test public void testPutIfAbsentNoStoreEntryHasCacheLoaderWriterEntry() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.singletonMap("key", "oldValue")); @@ -296,7 +294,7 @@ public void testPutIfAbsentHasStoreEntryHasCacheLoaderWriterEntry() throws Excep */ @Test public void testPutIfAbsentNoStoreEntryStoreAccessExceptionHasCacheLoaderWriterEntry() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); @@ -308,9 +306,8 @@ public void testPutIfAbsentNoStoreEntryStoreAccessExceptionHasCacheLoaderWriterE ehcache.putIfAbsent("key", "value"); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); + ordered.verify(this.spiedResilienceStrategy).putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).load(eq("key")); - ordered.verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), eq("oldValue"), any(StoreAccessException.class), eq(false)); assertThat(fakeLoaderWriter.getEntryMap().get("key"), equalTo("oldValue")); // Broken initial state: CacheLoaderWriter check omitted validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); @@ -338,9 +335,8 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionHasCacheLoaderWriter assertThat(ehcache.putIfAbsent("key", "value"), is("oldValue")); verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); + ordered.verify(this.spiedResilienceStrategy).putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).load(eq("key")); - ordered.verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), eq("oldValue"), any(StoreAccessException.class), eq(false)); assertThat(fakeLoaderWriter.getEntryMap().get("key"), equalTo("oldValue")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } @@ -354,10 +350,10 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionHasCacheLoaderWriter */ @Test public void testPutIfAbsentNoStoreEntryCacheLoaderWriterException() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); this.cacheLoaderWriter = spy(fakeLoaderWriter); doThrow(new Exception()).when(this.cacheLoaderWriter).write("key", "value"); final EhcacheWithLoaderWriter ehcache = this.getEhcache(this.cacheLoaderWriter); @@ -407,11 +403,11 @@ public void testPutIfAbsentHasStoreEntryCacheLoaderWriterException() throws Exce */ @Test public void testPutIfAbsentNoStoreEntryStoreAccessExceptionCacheLoaderWriterException() throws Exception { - final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); + final FakeStore fakeStore = new FakeStore(Collections.emptyMap()); this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); this.cacheLoaderWriter = spy(fakeLoaderWriter); doThrow(new Exception()).when(this.cacheLoaderWriter).write("key", "value"); final EhcacheWithLoaderWriter ehcache = this.getEhcache(this.cacheLoaderWriter); @@ -425,9 +421,8 @@ public void testPutIfAbsentNoStoreEntryStoreAccessExceptionCacheLoaderWriterExce // Expected } verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); + ordered.verify(this.spiedResilienceStrategy).putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); - ordered.verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class), any(CacheWritingException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } @@ -445,7 +440,7 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionCacheLoaderWriterExc this.store = spy(fakeStore); doThrow(new StoreAccessException("")).when(this.store).computeIfAbsent(eq("key"), getAnyFunction()); - final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); + final FakeCacheLoaderWriter fakeLoaderWriter = new FakeCacheLoaderWriter(Collections.emptyMap()); this.cacheLoaderWriter = spy(fakeLoaderWriter); doThrow(new Exception()).when(this.cacheLoaderWriter).write("key", "value"); final EhcacheWithLoaderWriter ehcache = this.getEhcache(this.cacheLoaderWriter); @@ -459,9 +454,8 @@ public void testPutIfAbsentHasStoreEntryStoreAccessExceptionCacheLoaderWriterExc // Expected } verify(this.store).computeIfAbsent(eq("key"), getAnyFunction()); + ordered.verify(this.spiedResilienceStrategy).putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class)); ordered.verify(this.cacheLoaderWriter).write(eq("key"), eq("value")); - ordered.verify(this.spiedResilienceStrategy) - .putIfAbsentFailure(eq("key"), eq("value"), any(StoreAccessException.class), any(CacheWritingException.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.FAILURE)); } From 521ef4df69626f32aeea56770a9b898f4ef2d58b Mon Sep 17 00:00:00 2001 From: Henri Tremblay Date: Mon, 22 Jan 2018 12:36:25 -0500 Subject: [PATCH 127/779] Push fallback getAll to the resilience strategy (#2198) --- .../resilience/ResilienceStrategy.java | 23 - .../main/java/org/ehcache/core/Ehcache.java | 35 +- .../java/org/ehcache/core/EhcacheBase.java | 212 ++-- .../ehcache/core/EhcacheWithLoaderWriter.java | 101 +- .../core/internal/util/CollectionUtil.java | 53 + .../RobustLoaderWriterResilienceStrategy.java | 31 +- .../resilience/RobustResilienceStrategy.java | 17 +- ...hcacheWithLoaderWriterBasicGetAllTest.java | 957 ++++++++---------- .../EhcacheWithLoaderWriterBasicGetTest.java | 2 +- ...eWithLoaderWriterBasicPutIfAbsentTest.java | 2 +- .../EhcacheWithLoaderWriterBasicPutTest.java | 4 +- ...hcacheWithLoaderWriterBasicRemoveTest.java | 4 +- .../internal/util/CollectionUtilTest.java | 67 ++ 13 files changed, 717 insertions(+), 791 deletions(-) create mode 100644 core/src/main/java/org/ehcache/core/internal/util/CollectionUtil.java create mode 100644 core/src/test/java/org/ehcache/core/internal/util/CollectionUtilTest.java diff --git a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java index 760da0e2c3..7e020b40f1 100644 --- a/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java +++ b/api/src/main/java/org/ehcache/resilience/ResilienceStrategy.java @@ -252,29 +252,6 @@ public interface ResilienceStrategy { */ Map getAllFailure(Iterable keys, StoreAccessException e); - /** - * Called when a {@link Cache#getAll(java.util.Set)} fails on a cache - * with a cache loader due to an underlying store failure. - * - * @param keys the keys being retrieved - * @param loaded the values from the loader - * @param e the triggered failure - * @return the value to return from the operation - */ - Map getAllFailure(Iterable keys, Map loaded, StoreAccessException e); - - /** - * Called when a {@link Cache#getAll(java.util.Set)} fails on a cache - * with a cache loader due to an underlying store failure, and the associated - * cache write operation also failed. - * - * @param keys the keys being retrieved - * @param e the cache failure - * @param f the writer failure - * @return the value to return from the operation - */ - Map getAllFailure(Iterable keys, StoreAccessException e, BulkCacheLoadingException f); - /** * Called when a {@link Cache#putAll(java.util.Map)} fails due to an * underlying store failure. diff --git a/core/src/main/java/org/ehcache/core/Ehcache.java b/core/src/main/java/org/ehcache/core/Ehcache.java index 04ee8bdeb6..ecf6e674a9 100644 --- a/core/src/main/java/org/ehcache/core/Ehcache.java +++ b/core/src/main/java/org/ehcache/core/Ehcache.java @@ -16,9 +16,13 @@ package org.ehcache.core; +import java.util.AbstractMap; +import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; @@ -31,6 +35,7 @@ import org.ehcache.Cache; import org.ehcache.config.CacheConfiguration; import org.ehcache.core.events.CacheEventDispatcher; +import org.ehcache.core.internal.util.CollectionUtil; import org.ehcache.core.resilience.RobustResilienceStrategy; import org.ehcache.core.spi.store.Store; import org.ehcache.core.spi.store.Store.PutStatus; @@ -99,18 +104,9 @@ protected boolean doRemoveInternal(final K key) throws StoreAccessException { return store.remove(key); } - protected Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { - getAllObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNullContent(keys); - if(keys.isEmpty()) { - getAllObserver.end(GetAllOutcome.SUCCESS); - return Collections.emptyMap(); - } - - Map result = new HashMap<>(); - try { + protected Map doGetAllInternal(Set keys, boolean includeNulls) throws StoreAccessException { Map> computedMap = store.bulkComputeIfAbsent(keys, new GetAllFunction<>()); + Map result = new HashMap<>(computedMap.size()); int hits = 0; int keyCount = 0; @@ -126,15 +122,7 @@ protected Map getAllInternal(Set keys, boolean includeNulls) addBulkMethodEntriesCount(BulkOps.GET_ALL_HITS, hits); addBulkMethodEntriesCount(BulkOps.GET_ALL_MISS, keyCount - hits); - getAllObserver.end(GetAllOutcome.SUCCESS); return result; - } catch (StoreAccessException e) { - try { - return resilienceStrategy.getAllFailure(keys, e); - } finally { - getAllObserver.end(GetAllOutcome.FAILURE); - } - } } /** @@ -526,14 +514,15 @@ public static class GetAllFunction implements Function> apply(final Iterable keys) { - Map computeResult = new LinkedHashMap<>(); + int size = CollectionUtil.findBestCollectionSize(keys, 1); // in our current implementation, we have one entry all the time + + List> computeResult = new ArrayList<>(size); - // put all the entries to get ordering correct for (K key : keys) { - computeResult.put(key, null); + computeResult.add(CollectionUtil.entry(key, null)); } - return computeResult.entrySet(); + return computeResult; } } diff --git a/core/src/main/java/org/ehcache/core/EhcacheBase.java b/core/src/main/java/org/ehcache/core/EhcacheBase.java index 61288745a1..fae4344fcd 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheBase.java +++ b/core/src/main/java/org/ehcache/core/EhcacheBase.java @@ -45,6 +45,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.EnumMap; import java.util.Iterator; import java.util.LinkedHashMap; @@ -118,26 +119,29 @@ public abstract class EhcacheBase implements InternalCache { @Override public V get(K key) { getObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - try { - Store.ValueHolder valueHolder = doGet(key); + statusTransitioner.checkAvailable(); + checkNonNull(key); - // Check for expiry first - if (valueHolder == null) { - getObserver.end(GetOutcome.MISS); - return null; - } else { - getObserver.end(GetOutcome.HIT); - return valueHolder.get(); - } - } catch (StoreAccessException e) { try { - return resilienceStrategy.getFailure(key, e); - } finally { + Store.ValueHolder valueHolder = doGet(key); + + // Check for expiry first + if (valueHolder == null) { + getObserver.end(GetOutcome.MISS); + return null; + } else { + getObserver.end(GetOutcome.HIT); + return valueHolder.get(); + } + } catch (StoreAccessException e) { + V value = resilienceStrategy.getFailure(key, e); getObserver.end(GetOutcome.FAILURE); + return value; } + } catch(Exception e) { + getObserver.end(GetOutcome.FAILURE); + throw e; } } @@ -145,26 +149,29 @@ public V get(K key) { protected V getNoLoader(K key) { getObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - try { - Store.ValueHolder valueHolder = store.get(key); + statusTransitioner.checkAvailable(); + checkNonNull(key); - // Check for expiry first - if (valueHolder == null) { - getObserver.end(GetOutcome.MISS); - return null; - } else { - getObserver.end(GetOutcome.HIT); - return valueHolder.get(); - } - } catch (StoreAccessException e) { try { - return resilienceStrategy.getFailure(key, e); - } finally { + Store.ValueHolder valueHolder = store.get(key); + + // Check for expiry first + if (valueHolder == null) { + getObserver.end(GetOutcome.MISS); + return null; + } else { + getObserver.end(GetOutcome.HIT); + return valueHolder.get(); + } + } catch (StoreAccessException e) { + V value = resilienceStrategy.getFailure(key, e); getObserver.end(GetOutcome.FAILURE); + return value; } + } catch(Exception e) { + getObserver.end(GetOutcome.FAILURE); + throw e; } } @@ -174,27 +181,29 @@ protected V getNoLoader(K key) { @Override public void put(K key, V value) { putObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key, value); - try { - Store.PutStatus status = doPut(key, value); - switch (status) { - case PUT: - putObserver.end(PutOutcome.PUT); - break; - case NOOP: - putObserver.end(PutOutcome.NOOP); - break; - default: - throw new AssertionError("Invalid Status."); - } - } catch (StoreAccessException e) { + statusTransitioner.checkAvailable(); + checkNonNull(key, value); + try { + Store.PutStatus status = doPut(key, value); + switch (status) { + case PUT: + putObserver.end(PutOutcome.PUT); + break; + case NOOP: + putObserver.end(PutOutcome.NOOP); + break; + default: + throw new AssertionError("Invalid Status."); + } + } catch (StoreAccessException e) { resilienceStrategy.putFailure(key, value, e); - } finally { putObserver.end(PutOutcome.FAILURE); } + } catch(Exception e) { + putObserver.end(PutOutcome.FAILURE); + throw e; } } @@ -224,26 +233,28 @@ public void remove(K key) throws CacheWritingException { protected boolean removeInternal(final K key) { removeObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key); - - boolean removed = false; try { - removed = doRemoveInternal(key); - if (removed) { - removeObserver.end(RemoveOutcome.SUCCESS); - } else { - removeObserver.end(RemoveOutcome.NOOP); - } - } catch (StoreAccessException e) { + statusTransitioner.checkAvailable(); + checkNonNull(key); + + boolean removed = false; try { + removed = doRemoveInternal(key); + if (removed) { + removeObserver.end(RemoveOutcome.SUCCESS); + } else { + removeObserver.end(RemoveOutcome.NOOP); + } + } catch (StoreAccessException e) { resilienceStrategy.removeFailure(key, e); - } finally { removeObserver.end(RemoveOutcome.FAILURE); } - } - return removed; + return removed; + } catch(Exception e) { + removeObserver.end(RemoveOutcome.FAILURE); + throw e; + } } protected abstract boolean doRemoveInternal(final K key) throws StoreAccessException; @@ -254,13 +265,18 @@ protected boolean removeInternal(final K key) { @Override public void clear() { clearObserver.begin(); - statusTransitioner.checkAvailable(); try { - store.clear(); - clearObserver.end(ClearOutcome.SUCCESS); - } catch (StoreAccessException e) { + statusTransitioner.checkAvailable(); + try { + store.clear(); + clearObserver.end(ClearOutcome.SUCCESS); + } catch (StoreAccessException e) { + resilienceStrategy.clearFailure(e); + clearObserver.end(ClearOutcome.FAILURE); + } + } catch(Exception e) { clearObserver.end(ClearOutcome.FAILURE); - resilienceStrategy.clearFailure(e); + throw e; } } @@ -270,29 +286,32 @@ public void clear() { @Override public V putIfAbsent(final K key, final V value) { putIfAbsentObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNull(key, value); + try { + statusTransitioner.checkAvailable(); + checkNonNull(key, value); - AtomicBoolean put = new AtomicBoolean(false); + AtomicBoolean put = new AtomicBoolean(false); - try { - ValueHolder inCache = doPutIfAbsent(key, value, b -> put.set(b)); - if(put.get()) { - putIfAbsentObserver.end(PutIfAbsentOutcome.PUT); - return null; - } else if (inCache == null) { - putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return null; - } else { - putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); - return inCache.get(); - } - } catch (StoreAccessException e) { try { - return resilienceStrategy.putIfAbsentFailure(key, value, e); // FIXME: We can't know if it's absent or not - } finally { + ValueHolder inCache = doPutIfAbsent(key, value, b -> put.set(b)); + if (put.get()) { + putIfAbsentObserver.end(PutIfAbsentOutcome.PUT); + return null; + } else if (inCache == null) { + putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); + return null; + } else { + putIfAbsentObserver.end(PutIfAbsentOutcome.HIT); + return inCache.get(); + } + } catch (StoreAccessException e) { + V newValue = resilienceStrategy.putIfAbsentFailure(key, value, e); // FIXME: We can't know if it's absent or not putIfAbsentObserver.end(PutIfAbsentOutcome.FAILURE); + return newValue; } + } catch(Exception e) { + putIfAbsentObserver.end(PutIfAbsentOutcome.FAILURE); + throw e; } } @@ -315,7 +334,32 @@ public Map getAll(Set keys) throws BulkCacheLoadingException return getAllInternal(keys, true); } - protected abstract Map getAllInternal(Set keys, boolean b); + protected Map getAllInternal(Set keys, boolean includeNulls) { + getAllObserver.begin(); + try { + statusTransitioner.checkAvailable(); + checkNonNullContent(keys); + if (keys.isEmpty()) { + getAllObserver.end(GetAllOutcome.SUCCESS); + return Collections.emptyMap(); + } + + try { + Map result = doGetAllInternal(keys, includeNulls); + getAllObserver.end(GetAllOutcome.SUCCESS); + return result; + } catch (StoreAccessException e) { + Map result = resilienceStrategy.getAllFailure(keys, e); + getAllObserver.end(GetAllOutcome.FAILURE); + return result; + } + } catch(Exception e) { + getAllObserver.end(GetAllOutcome.FAILURE); + throw e; + } + } + + protected abstract Map doGetAllInternal(Set keys, boolean includeNulls) throws StoreAccessException; protected boolean newValueAlreadyExpired(K key, V oldValue, V newValue) { diff --git a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java index 82915b27e6..d7e8ef993f 100644 --- a/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java +++ b/core/src/main/java/org/ehcache/core/EhcacheWithLoaderWriter.java @@ -20,6 +20,7 @@ import org.ehcache.config.CacheConfiguration; import org.ehcache.core.events.CacheEventDispatcher; import org.ehcache.core.exceptions.StorePassThroughException; +import org.ehcache.core.internal.util.CollectionUtil; import org.ehcache.core.resilience.RobustLoaderWriterResilienceStrategy; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.spi.loaderwriter.BulkCacheWritingException; @@ -33,7 +34,6 @@ import org.ehcache.core.statistics.CacheOperationOutcomes.ConditionalRemoveOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetAllOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.GetOutcome; -import org.ehcache.core.statistics.CacheOperationOutcomes.PutIfAbsentOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.PutAllOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.PutOutcome; import org.ehcache.core.statistics.CacheOperationOutcomes.RemoveAllOutcome; @@ -41,11 +41,13 @@ import org.ehcache.core.statistics.CacheOperationOutcomes.ReplaceOutcome; import org.slf4j.Logger; +import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; +import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; @@ -153,40 +155,36 @@ protected boolean doRemoveInternal(final K key) throws StoreAccessException { return modified.get(); } - protected Map getAllInternal(Set keys, boolean includeNulls) throws BulkCacheLoadingException { - getAllObserver.begin(); - statusTransitioner.checkAvailable(); - checkNonNullContent(keys); - if(keys.isEmpty()) { - getAllObserver.end(GetAllOutcome.SUCCESS); - return Collections.emptyMap(); - } - final Map successes = new HashMap<>(); - final Map failures = new HashMap<>(); - + protected Map doGetAllInternal(Set keys, boolean includeNulls) throws StoreAccessException { + // we are not expecting failures and these two maps are only used in case of failures. So keep them small + Map successes = new HashMap<>(1); + Map failures = new HashMap<>(1); Function, Iterable>> computeFunction = keys1 -> { - Map computeResult = new LinkedHashMap<>(); - - // put all the entries to get ordering correct - for (K key : keys1) { - computeResult.put(key, null); - } - - Map loaded = Collections.emptyMap(); + Map loaded; try { - loaded = cacheLoaderWriter.loadAll(computeResult.keySet()); + loaded = cacheLoaderWriter.loadAll(keys1); } catch(BulkCacheLoadingException bcle) { + loaded = Collections.emptyMap(); collectSuccessesAndFailures(bcle, successes, failures); } catch (Exception e) { - for (K key : computeResult.keySet()) { + loaded = Collections.emptyMap(); + for (K key : keys1) { failures.put(key, e); } } + int size = CollectionUtil.findBestCollectionSize(keys1, 1); // this function is actually called with one key at the time + Map computeResult = new LinkedHashMap<>(size); + + // put all the entries to get ordering correct + for (K key : keys1) { + computeResult.put(key, null); + } + if (!loaded.isEmpty()) { - for (K key : computeResult.keySet()) { + for (K key : keys1) { V value = loaded.get(key); successes.put(key, value); computeResult.put(key, value); @@ -197,45 +195,27 @@ protected Map getAllInternal(Set keys, boolean includeNulls) }; Map result = new HashMap<>(); - try { - Map> computedMap = store.bulkComputeIfAbsent(keys, computeFunction); - - int hits = 0; - int keyCount = 0; - for (Map.Entry> entry : computedMap.entrySet()) { - keyCount++; - if (entry.getValue() != null) { - result.put(entry.getKey(), entry.getValue().get()); - hits++; - } else if (includeNulls && failures.isEmpty()) { - result.put(entry.getKey(), null); - } + Map> computedMap = store.bulkComputeIfAbsent(keys, computeFunction); + + int hits = 0; + int keyCount = 0; + for (Map.Entry> entry : computedMap.entrySet()) { + keyCount++; + if (entry.getValue() != null) { + result.put(entry.getKey(), entry.getValue().get()); + hits++; + } else if (includeNulls && failures.isEmpty()) { + result.put(entry.getKey(), null); } + } - addBulkMethodEntriesCount(BulkOps.GET_ALL_HITS, hits); - if (failures.isEmpty()) { - addBulkMethodEntriesCount(BulkOps.GET_ALL_MISS, keyCount - hits); - getAllObserver.end(GetAllOutcome.SUCCESS); - return result; - } else { - successes.putAll(result); - getAllObserver.end(GetAllOutcome.FAILURE); - throw new BulkCacheLoadingException(failures, successes); - } - } catch (StoreAccessException e) { - try { - Set toLoad = new HashSet<>(keys); - toLoad.removeAll(successes.keySet()); - toLoad.removeAll(failures.keySet()); - computeFunction.apply(toLoad); - if (failures.isEmpty()) { - return resilienceStrategy.getAllFailure(keys, successes, e); - } else { - return resilienceStrategy.getAllFailure(keys, e, new BulkCacheLoadingException(failures, successes)); - } - } finally { - getAllObserver.end(GetAllOutcome.FAILURE); - } + addBulkMethodEntriesCount(BulkOps.GET_ALL_HITS, hits); + if (failures.isEmpty()) { + addBulkMethodEntriesCount(BulkOps.GET_ALL_MISS, keyCount - hits); + return result; + } else { + successes.putAll(result); + throw new BulkCacheLoadingException(failures, successes); } } @@ -368,6 +348,7 @@ private static void collectSuccessesAndFailures(BulkCacheWritingException bc successes.addAll((Collection)bcwe.getSuccesses()); failures.putAll((Map)bcwe.getFailures()); } + @SuppressWarnings({ "unchecked" }) private void collectSuccessesAndFailures(BulkCacheLoadingException bcle, Map successes, Map failures) { successes.putAll((Map)bcle.getSuccesses()); diff --git a/core/src/main/java/org/ehcache/core/internal/util/CollectionUtil.java b/core/src/main/java/org/ehcache/core/internal/util/CollectionUtil.java new file mode 100644 index 0000000000..7b059cdbf8 --- /dev/null +++ b/core/src/main/java/org/ehcache/core/internal/util/CollectionUtil.java @@ -0,0 +1,53 @@ +/* + * Copyright Terracotta, Inc. + * + * 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 org.ehcache.core.internal.util; + +import java.util.AbstractMap; +import java.util.Collection; +import java.util.Map; + +/** + * Multiple useful methods to play with collections + */ +public final class CollectionUtil { + + private CollectionUtil() {} + + /** + * Used to create a new collection with the correct size. Given an iterable, will try to see it the iterable actually + * have a size and will return it. If the iterable has no known size, we return the best bet. + * + * @param iterable the iterable we will try to find the size of + * @param bestBet our best bet for the size if the iterable is not sizeable + * @return the size of the iterable if found or null + */ + public static int findBestCollectionSize(Iterable iterable, int bestBet) { + return (iterable instanceof Collection ? ((Collection) iterable).size() : bestBet); + } + + /** + * Return a map entry for the key and value provided. + * + * @param key the key of the entry + * @param value the value of the entry + * @param type of the key + * @param type of the value + * @return the map entry for the key and value + */ + public static Map.Entry entry(K key, V value) { + return new AbstractMap.SimpleImmutableEntry<>(key, value); + } +} diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java index 8889eb8c19..38f25904c4 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustLoaderWriterResilienceStrategy.java @@ -16,9 +16,7 @@ package org.ehcache.core.resilience; -import org.ehcache.core.exceptions.StorePassThroughException; import org.ehcache.core.spi.store.Store; -import org.ehcache.core.statistics.CacheOperationOutcomes; import org.ehcache.resilience.RethrowingStoreAccessException; import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; @@ -27,14 +25,10 @@ import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.ehcache.spi.loaderwriter.CacheWritingException; -import java.util.HashMap; import java.util.Map; import java.util.Objects; -import java.util.function.Function; import static java.util.Collections.emptyMap; -import static org.ehcache.core.exceptions.ExceptionFactory.newCacheLoadingException; -import static org.ehcache.core.exceptions.ExceptionFactory.newCacheWritingException; /** * @@ -97,6 +91,7 @@ public void clearFailure(StoreAccessException e) { public V putIfAbsentFailure(K key, V value, StoreAccessException e) { cleanup(key, e); // FIXME: This is not atomic + // FIXME: Should I care about useLoaderInAtomics? try { V loaded = loaderWriter.load(key); if(loaded != null) { @@ -167,26 +162,18 @@ public boolean replaceFailure(K key, V value, V newValue, StoreAccessException e throw f; } + @SuppressWarnings("unchecked") @Override public Map getAllFailure(Iterable keys, StoreAccessException e) { cleanup(keys, e); - HashMap result = new HashMap<>(); - for (K key : keys) { - result.put(key, null); - } - return result; - } - @Override - public Map getAllFailure(Iterable keys, Map loaded, StoreAccessException e) { - cleanup(keys, e); - return loaded; - } - - @Override - public Map getAllFailure(Iterable keys, StoreAccessException e, BulkCacheLoadingException f) { - cleanup(keys, e); - throw f; + try { + return loaderWriter.loadAll((Iterable)keys); // FIXME: bad typing that we should fix + } catch(BulkCacheLoadingException e1) { + throw e1; + } catch (Exception e1) { + throw new CacheLoadingException(e1); + } } @Override diff --git a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java index ee13eb96d0..5c82e5a327 100644 --- a/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java +++ b/core/src/main/java/org/ehcache/core/resilience/RobustResilienceStrategy.java @@ -20,6 +20,7 @@ import java.util.Map; import java.util.Objects; +import org.ehcache.core.internal.util.CollectionUtil; import org.ehcache.core.spi.store.Store; import org.ehcache.resilience.RethrowingStoreAccessException; import org.ehcache.resilience.StoreAccessException; @@ -132,25 +133,15 @@ public boolean replaceFailure(K key, V value, V newValue, StoreAccessException e @Override public Map getAllFailure(Iterable keys, StoreAccessException e) { cleanup(keys, e); - HashMap result = new HashMap<>(); + + int size = CollectionUtil.findBestCollectionSize(keys, 16); // 16 is the HashMap default + HashMap result = new HashMap<>(size); for (K key : keys) { result.put(key, null); } return result; } - @Override - public Map getAllFailure(Iterable keys, Map loaded, StoreAccessException e) { - cleanup(keys, e); - return loaded; - } - - @Override - public Map getAllFailure(Iterable keys, StoreAccessException e, BulkCacheLoadingException f) { - cleanup(keys, e); - throw f; - } - @Override public void putAllFailure(Map entries, StoreAccessException e) { cleanup(entries.keySet(), e); diff --git a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java index 5b20a8ba5d..f1dc16cdd6 100644 --- a/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java +++ b/core/src/test/java/org/ehcache/core/EhcacheWithLoaderWriterBasicGetAllTest.java @@ -24,10 +24,10 @@ import org.ehcache.Status; import org.ehcache.core.spi.store.Store; import org.ehcache.core.statistics.CacheOperationOutcomes; -import org.ehcache.resilience.ResilienceStrategy; import org.ehcache.spi.loaderwriter.BulkCacheLoadingException; import org.ehcache.resilience.StoreAccessException; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; +import org.ehcache.spi.loaderwriter.CacheLoadingException; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.ArgumentCaptor; @@ -92,24 +92,6 @@ public class EhcacheWithLoaderWriterBasicGetAllTest extends EhcacheBasicCrudBase @Captor private ArgumentCaptor> loadAllCaptor; - /** - * A Mockito {@code ArgumentCaptor} for the {@code Set} argument to the - * {@link ResilienceStrategy#getAllFailure(Iterable, Map, StoreAccessException) - * ResilienceStrategy.getAllFailure(Iterable, Map, StoreAccessException)} method. - */ - @Captor - private ArgumentCaptor> getAllFailureMapCaptor; - - /** - * A Mockito {@code ArgumentCaptor} for the - * {@link BulkCacheLoadingException BulkCacheLoadingException} - * provided to the - * {@link ResilienceStrategy#getAllFailure(Iterable, StoreAccessException, BulkCacheLoadingException) - * ResilienceStrategy.getAllFailure(Iterable, StoreAccessException, BulkCacheLoadingException)} method. - */ - @Captor - private ArgumentCaptor bulkExceptionCaptor; - /** * Tests {@link EhcacheWithLoaderWriter#getAll(Set)} for *