@@ -642,7 +642,6 @@ private void onNewContext(SearchContext context) {
642642 boolean success = false ;
643643 try {
644644 if (context .scrollContext () != null ) {
645- openScrollContexts .incrementAndGet ();
646645 context .indexShard ().getSearchOperationListener ().onNewScrollContext (context );
647646 }
648647 context .indexShard ().getSearchOperationListener ().onNewContext (context );
@@ -661,14 +660,15 @@ private void onNewContext(SearchContext context) {
661660 final SearchContext createContext (SearchRewriteContext rewriteContext ) throws IOException {
662661 final DefaultSearchContext context = createSearchContext (rewriteContext , defaultSearchTimeout );
663662 try {
664- if (rewriteContext .request != null && openScrollContexts .get () >= maxOpenScrollContext ) {
665- throw new ElasticsearchException (
666- "Trying to create too many scroll contexts. Must be less than or equal to: [" +
667- maxOpenScrollContext + "]. " + "This limit can be set by changing the ["
668- + MAX_OPEN_SCROLL_CONTEXT .getKey () + "] setting." );
669- }
670663 final ShardSearchRequest request = rewriteContext .request ;
671664 if (request .scroll () != null ) {
665+ context .addReleasable (openScrollContexts ::decrementAndGet , Lifetime .CONTEXT );
666+ if (openScrollContexts .incrementAndGet () > maxOpenScrollContext ) {
667+ throw new ElasticsearchException (
668+ "Trying to create too many scroll contexts. Must be less than or equal to: [" +
669+ maxOpenScrollContext + "]. " + "This limit can be set by changing the ["
670+ + MAX_OPEN_SCROLL_CONTEXT .getKey () + "] setting." );
671+ }
672672 context .scrollContext (new ScrollContext ());
673673 context .scrollContext ().scroll = request .scroll ();
674674 }
@@ -768,7 +768,6 @@ private void onFreeContext(SearchContext context) {
768768 assert activeContexts .containsKey (context .id ().getId ()) == false ;
769769 context .indexShard ().getSearchOperationListener ().onFreeContext (context );
770770 if (context .scrollContext () != null ) {
771- openScrollContexts .decrementAndGet ();
772771 context .indexShard ().getSearchOperationListener ().onFreeScrollContext (context );
773772 }
774773 }
0 commit comments