java - Does a modern JVM optimize read only collection allocations -


i little curious following optimization possibility not sure how verify myself, maybe knows answers.

we have lot of similar code in our application. statefull handler (saga) started message (mystartingmessage) , can later continued other message (mycotinuemessage). because there multiple instances of statefullhandler's want check if continue message should handled given instance. therefor set state in handler , when message received check every handler instance if state in message matches handler state, message handled handler instance.

in example shown below framework extract matchers , check if of matches received continue message instance.

because handled thousands of such messages per second curious if jvm optimize instance allocations (after time) not create new instance every time.

    class statefullhandler implements messagehandler {      public void handle(final mystartingmessage m) {         m.setstate(m.getuserid()); // used matchers     }      public void handle(final mycontinuemessage m) {         // handle     }      // returned queries , never modified     public collection<messagematcher> matchers() {         // message handled instance if state matches         // new operator optimized 'away' after time??         return immutableset.of(messagematcher.for(mycontinuemessage.class, msg -> msg.getuserid()));      } } 

without optimization effectivly need write this:

class statefullhandler implements messagehandler {      private static final matchers = immutableset.of(         messagematcher.for(mycontinuemessage.class, msg -> msg.getuserid()));           public void handle(final mystartingmessage m) {             m.setstate(m.getuserid()); // used matchers         }          public void handle(final mycontinuemessage m) {             // handle         }          public collection<messagematcher> matchers() {             return matchers;         }     } 

jvm cannot reuse old object instance if explicitly used new keyword, because violate java language specification. first, when create objects a , b via new it's guaranteed a == b return false. second, it's guaranteed can synchronize on a , b independently without waiting each other. jvm reuse old objects, not guaranteed. jvm cannot reuse them simplest cases new integer(1).

in cases can rely on caching performed third-party libraries, in particular case guava's immutableset.of reuses existing object empty set. in case having static field seems best solution.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -