Strategy Pattern and HotSpot optimization

I wonder whether using the Strategy Pattern affects HotSpot optimizations such as inlining. Assume for a non trivial operation that has to be done often there exist two alternatives which are frequently exchanged (i.e. the flag in the example changes its value frequently). Originally code looked like this:if ( caseSensitive ) {
   caseSensitiveComparison( strA, strB );
else {
   caseInsensitiveComparison( strA, strB );
}Assume both methods are private then that code can be inlined quite easily by the HotSpot engine.
If we now delegate to a StringComparator (defined as interface and implemented by two singletons) we getcomparator.compareStrings( strA, strB );Is the VM still able to inline this? Or is it likely that overall performance degrades since the virtual call is not optimized away?
Any ideas?
Thanks!
robert
For further info on the Strategy Pattern see here
http://c2.com/cgi/wiki?StrategyPattern

That's true, but OTOH he describes a realistic (?)
scenario in the first paragraph that explains inlining
could occur.That's good news.
However, what I found more valuable is his statement,
that a virtual call is not necessarily worse than a
local conditional (branch prediction hassles).Just to be clear, I'm not advocating the use of if instead of Strategy in some hope that it will result in inlining. Personally, I feel that the whole idea that OO slows things down is overblown. While it may add complications and more instructions at a microscopic level, OO often simplfies and reduces actions at a macroscopic level.
I'm more interested in knowning what are the inlining requirements and triggers. Along the lines of the understanding why it's sometimes bad practice to use + for String concatenation, I'd like to know if there are simple things that can be done to improve performance with out changing the overall design.
If anyone has any information on this it would be much appreciated.

Similar Messages

  • Strategy Pattern Q

    Hi,
    I've been reading about the Strategy Pattern and I would liek to implement into one of my own small projects.
    I have an application called WatchDog, this application checks some directories (provided as parameter) and puts every item in a directory in an appropriate mysql table.
    I have this section in my code:
    private void insertFile(File aFile, String arg) {
              if (arg.equals("/EBooks"))
                   qry.InsertEbook(aFile);
              else if (arg.equals("/MP3"))
                   qry.insertMP3(aFile);
                    else if (arg.equals("/Videos"))
                   qry.insertVideo(aFile);
         }this looks like a perfect candidate for Strategy Pattern to me?
    But I'm struggling with the design.
    The concept is an insert query, or simpler a query right?
    The strategy interface is DataType (EBooks, MP3, Videos, ...)
    And Ebook, MP3, Video are ConcreteStrategy classes then???
    Can anybody give some clarification on this one pls?
    grtz

    Not necessarily the Strategy Pattern proper or the best possible solution but you could do something like this:
    interface FileHandler
       public void handle(File file);
    }And then in in another class:
    private Map<String, FileHandler> handlers = new HashMap<String, FileHandler>();
    // fill the map with a handler for each directory
    private void insertFile(File aFile, String arg) {
       handlers.get(arg).handle(aFile);
    }

  • Can delegate and strategy patterns coexist ?

    Say I have an interface for persistence call that PersistenceInterface.
    Now for MySQL I created MySQLPersistenceClass and for DB2 I created one more class DB2PersistenceClass.
    Now to proceed with my busines slogic I have a class BusinessLogicHandler class.
    BusinessLogicHandler has a class member say persistenceObject of type PersistenceInterface. Now certainly I'm switching the persistence based on the actual implementation so I say Im using STRATEGY pattern here
    But for create operation from business layer i.e. BusinessLogicHandler.create directly invokes persistenceObject.create in this case can I say that Im using DELEGATE pattern also
    So can I say the set of classes and interface = DELEGATE + STRATEGY ?
    Thanks a lot

    Can someone please answer this ?yes
    can I say the set of classes and interface = DELEGATE + STRATEGY ?yes
    Can delegate and strategy patterns coexist ?yes
    I'd say it would be odd to use Strategy not as a delegate.

  • How to implement Strategy pattern in ABAP Objects?

    Hello,
    I have a problem where I need to implement different algorithms, depending on the type of input. Example: I have to calculate a Present Value, sometimes with payments in advance, sometimes payment in arrear.
    From documentation and to enhance my ABAP Objects skills, I would like to implement the strategy pattern. It sounds the right solution for the problem.
    Hence I need some help in implementing this pattern in OO. I have some basic OO skills, but still learning.
    Has somebody already implemented this pattern in ABAP OO and can give me some input. Or is there any documentation how to implement it?
    Thanks and regards,
    Tapio

    Keshav has already outlined required logic, so let me fulfill his answer with a snippet
    An Interface
    INTERFACE lif_payment.
      METHODS pay CHANGING c_val TYPE p.
    ENDINTERFACE.
    Payment implementations
    CLASS lcl_payment_1 DEFINITION.
      PUBLIC SECTION.
      INTERFACES lif_payment.
      ALIASES pay for lif_payment~pay.
    ENDCLASS.                 
    CLASS lcl_payment_2 DEFINITION.
      PUBLIC SECTION.
      INTERFACES lif_payment.
      ALIASES pay for lif_payment~pay.
    ENDCLASS.                   
    CLASS lcl_payment_1 IMPLEMENTATION.
      METHOD pay.
        "do something with c_val i.e.
        c_val = c_val - 10.
      ENDMETHOD.                   
    ENDCLASS.                  
    CLASS lcl_payment_2 IMPLEMENTATION.
      METHOD pay.
        "do something else with c_val i.e.
        c_val = c_val + 10.
      ENDMETHOD.  
    Main class which uses strategy pattern
    CLASS lcl_main DEFINITION.
      PUBLIC SECTION.
        "during main object creation you pass which payment you want to use for this object
        METHODS constructor IMPORTING ir_payment TYPE REF TO lif_payment.
        "later on you can change this dynamicaly
        METHODS set_payment IMPORTING ir_payment TYPE REF TO lif_payment.
        METHODS show_payment_val.
        METHODS pay.
      PRIVATE SECTION.
        DATA payment_value TYPE p.
        "reference to your interface whcih you will be working with
        "polimorphically
        DATA mr_payment TYPE REF TO lif_payment.
    ENDCLASS.                  
    CLASS lcl_main IMPLEMENTATION.
      METHOD constructor.
        IF ir_payment IS BOUND.
          me->mr_payment = ir_payment.
        ENDIF.
      ENDMETHOD.                  
      METHOD set_payment.
        IF ir_payment IS BOUND.
          me->mr_payment = ir_payment.
        ENDIF.
      ENDMETHOD.                  
      METHOD show_payment_val.
        WRITE /: 'Payment value is now ', me->payment_value.
      ENDMETHOD.                  
      "hide fact that you are using composition to access pay method
      METHOD pay.
        mr_payment->pay( CHANGING c_val = payment_value ).
      ENDMETHOD.                   ENDCLASS.                  
    Client application
    PARAMETERS pa_pay TYPE c. "1 - first payment, 2 - second
    DATA gr_main TYPE REF TO lcl_main.
    DATA gr_payment TYPE REF TO lif_payment.
    START-OF-SELECTION.
      "client application (which uses stategy pattern)
      CASE pa_pay.
        WHEN 1.
          "create first type of payment
          CREATE OBJECT gr_payment TYPE lcl_payment_1.
        WHEN 2.
          "create second type of payment
          CREATE OBJECT gr_payment TYPE lcl_payment_2.
      ENDCASE.
      "pass payment type to main object
      CREATE OBJECT gr_main
        EXPORTING
          ir_payment = gr_payment.
      gr_main->show_payment_val( ).
      "now client doesn't know which object it is working with
      gr_main->pay( ).
      gr_main->show_payment_val( ).
      "you can also use set_payment method to set payment type dynamically
      "client would see no change
      if pa_pay = 1.
        "now create different payment to set it dynamically
        CREATE OBJECT gr_payment TYPE lcl_payment_2.
        gr_main->set_payment( gr_payment ).
        gr_main->pay( ).
        gr_main->show_payment_val( ).
      endif.
    Regads
    Marcin

  • Strategy Pattern, Am i on the right Track?

    The question:
    Design a small, prototype, application, which creates, stores and amends warehouse records. This may have little more than a StockItem class.
    Using each of the patterns Strategy, Decorator, Adaptor and in turn provide three different adaptations to your prototype application which will enable a user to view the warehouse records in at least three different ways, e.g. by location, alphabetically, by value, by quantity in stock, as continuous plain text, as formatted text, in a list pane, as a printout etc
    My Code
    package warehouse;
    public class StockItem
        private int id;
        private String describtion;
        private double price;
        private int  quantity;
        private String location;
        ViewByLocationBehavior locationVar;
        public StockItem()
        public void setId(int id)
            this.id=id;
        public int getId()
            return id;
        public void setDescribtion(String describtion)
            this.describtion=describtion;
        public String getDescribtion()
            return describtion;
         public void setPrice(double price)
            this.price=price;
        public double getPrice()
            return price;
        public void setQuantity(int quantity)
            this.quantity=quantity;
        public int getQuantity()
            return quantity;
        public void setLocation(String location)
            this.location=location;
        public String getLocation()
            return location;
        public void setViewByLocationBehavior(ViewByLocationBehavior locationVar )
            this.locationVar=locationVar;
       public void displayByLocation()
        locationVar.displayByLocation();
        public String toString()
            return String.format("%d %S %f %d %S",id ,describtion,price,quantity,location);
    }The interface
    package warehouse;
    public interface ViewByLocationBehavior
        void displayByLocation();
    }Concrete classes arepackage warehouse;
    public class PlainText extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display PlainText");
    package warehouse;
    public class FormattedText extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display Formatted Text ");
    package warehouse;
    public class ListPane extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display ListPane");
    package warehouse;
    public class PrintOut extends StockItem implements ViewByLocationBehavior
        public void displayByLocation()
            System.out.println("Display PrintOut ");
    package warehouse;
    public class StockTest
        public static void main(String args[])
            StockItem obj = new StockItem();
            obj.setViewByLocationBehavior(new PlainText());
            obj.displayByLocation();
            System.out.println(obj.toString());
    }But my questions is Am i on the right track applying the Strategy pattern?
    Because next i will make the other Interfaces: View by alphabetically, by value, by quantity, and their Concrete Classes are
    Display as continuous plain text, formatted text, in a list pane, and printout.
    Each interface have four concrete classes
    Need your comments Please?

    But my questions is Am i on the right track applying
    the Strategy pattern?Your assignment explicitly calls for the strategy pattern:
    "> Using each of the patterns Strategy, Decorator,
    Adaptor and in turn provide three different
    adaptations to your prototype application which will
    enable a user to view the warehouse records in at
    least three different ways, e.g. by location,
    alphabetically, by value, by quantity in stock, as
    continuous plain text, as formatted text, in a list
    pane, as a printout etc"I'm not sure I care for that interface much. I would have expected something more like this (I'm not 100% sure about the parameter that I'd pass, if any):
    public interface StockItemFilter
        List<StockItem> filter(List<StockItem> unfilteredStockItems);
    }Now you'll pass in an unfiltered List of StockItems and return the List of appropriate StockItems filtered alphabetically, by location, etc. If you want to combine the fetching of StockItems with filtering, replace the unfiltered List with some Criterion.
    Your ViewByLocationBehavior doesn't seem to accept any input or return anything. What good is it?
    %

  • Strategy pattern question.

    Can the following scenario be called strategy pattern?
    public class StrategyExecutor {
         public static void main(String[] args) {
              Strategy[] strategies = {new FirstImpl(), new SecondImpl()};
              for(int i = 0; i < strategies.length; i++){
                   System.out.print("Strategy ["+ i +"] ");
                   strategies.solve();
    public interface Strategy {
         public void solve();
    public abstract class AbstractClass implements Strategy{
         public void solve(){
              int result = getFirstParam()+getSecondParam();
              System.out.println(" Result "+result);
         protected abstract int getSecondParam();
         protected abstract int getFirstParam();
    public class FirstImpl extends AbstractClass {
         protected int getSecondParam() {          
              return 22;
         protected int getFirstParam() {          
              return 11;
    public class SecondImpl extends AbstractClass {
         protected int getSecondParam() {
              return 44;
         protected int getFirstParam() {          
              return 33;

    To be a perfect fit for Strategy pattern, if the abtract class which has the template to solve() is not there and the actual algorithm is down in the FIrstImpl, SecondImpl then its a true strategy?
    Design point of view it can be a strategy pattern..
    but If you see from the the context and the programs
    objective, It is not strategy pattern

  • Dangerous Hotspot Optimizations

    Hi,
    I was reading "Taming Java Threads" and came across the following interesting example of Hotspot Optimization causing unexpected behaviour:
    public class Class1 {
        private boolean condition = false;
        public void setTrue(){
            condition = true;
        private synchronized void testCondition(){
            condition = false;
            //Another thread could call setTrue() here
            if(condition){
                //This may never execute tho!
    }I seems that Hotspot sees the boolean as being false, and will compile the method without the statements inside the condition - i.e. it takes no consideration that another thread may change the value of the condition.
    Obviously you could just synchronize the setTrue() method, but this shouldn't really be necessary as boolena assignment is an atomic operation.
    The author suggested using the volatile keyword for the boolean, but having read many posts on this forum I believe the implementation of volatile in the JVM is less than satisfactory.
    All in all it seems very suspect on the part of the HotSpot compiler...

    I seems that Hotspot sees the boolean as being false,
    and will compile the method without the statements
    inside the condition - i.e. it takes no consideration
    that another thread may change the value of the
    condition.This is not an example of HotSpot causing unexpected behaviour; It is an example of badly synchronized code. Whether or not you are using HotSpot, a change to the value of condition by another thread at the point you indicate may not be seen. So if HotSpot decides that it should always not be seen, it is not doing anything unexpected.
    Obviously you could just synchronize the setTrue()
    method, but this shouldn't really be necessary as
    boolena assignment is an atomic operation.Yes, it is necessary if you want all threads to see the most up-to-date value. It doesn't matter that boolean assignment is atomic - what's importnant is the order in which threads update and flush their local caches from and to main memory.
    For a full understanding of this, read chapter 17 of the JLS (it isn't very long)
    The author suggested using the volatile keyword
    for the boolean, but having read many posts on this
    forum I believe the implementation of volatile in the
    JVM is less than satisfactory.As far as I am aware, the problems with existing implementations of volatile are only concerned with long and double variables. There is no reason to expect that volatile boolean variables should not behave properly.
    >
    All in all it seems very suspect on the part of the
    HotSpot compiler...I see no problem with it. The correct thing to do here is either declare the variable volatile, or synchronize (on the same monitor) all code that reads or writes that variable.

  • Filemonitor - Strategy pattern?

    Hi all.
    I have an application that I think needs to use the strategy pattern but I'm not sure.
    I'm fairly new to design patterns but I would like to be able to use the right one and as yet I can't see which one to use and where.
    My first instance of the application places a listener on a file in the local file system and when the modified date of that file changes it notifies the application that the file has changed.
    Fairly simple.
    I have a need now to monitor files not only on the local file system but also on a ftp server.
    I thought of adding this into the class but then I thought "what would happen if I wanted to monitor a file in a database, on a remote system, somewhere I hadn't thought of, etc".
    So a design pattern was needed... but which one.
    I thought the Strategy pattern looked best from my reading but I'm not sure. I don't want to use the wrong pattern and end up having a more complicated design than I started with.
    I hope someone can help. If I haven't put enough information here then I do apologize and will put more if requested.
    Thanks in advance.
    All the best,
    Tony

    As of my knowledge ,startegy pattern would best fit.
    You can have an abstract strategy class
    public abstarct FileMontor {
    abstract void checkFile(Object file);
    public class LocalFileMonitor extends FileMonitor
    //Override the method checkFile(Object file) and write code
    public class DBFileMonitor
    //Override the method checkFile(Object file) and write code
    //In the same fashio we can keep on creating the strategies.
    But now the problem is who decides which strategy to use at what point of time, is there a way i can register the various strategies ...
    So you should have register cum controller class, where you can register all ur strategies.. and it should have intelligenece to choose the strategy at runtime from the input it is receving at runtime.

  • I am using the pattern stamp tool. when i select my pattern it adds a hatching to teh source pattern and copies that hatching to the destination image

    I am using the pattern stamp tool. when i select my pattern it adds a hatching to the source pattern and copies that hatching to the destination image

    Please post screenshots to illustrate what you are talking about.

  • Object Oriented Patterns and Visio

    Visio question:
    Does anyone know if there are established shapes for each (or any) of the object oriented patterns? If not, is anyone working on that or interested in that?
    Since they all have names (Momento, Proxy, Iterator, Mediator, Observer, etc.) it seems like they ought to each have their own shape. Since Object Oriented is all about communication of intent, each pattern having its own recognizable shape would go a long way toward a more meaningful communication through diagram. Also, if they each had their own shape, then the super-patterns (based on commonly grouped patterns and interactions) could also be easily represented.
    Blaine

    I'm kind of making an assumption here and if it's in error then feel free to disregard the rest of this post.
    Assumption that you're thinking terms of shapes for representing in UML the various patterns. Everything you need is right there in front of you already regardless of whether you use Visio, Rational, Poseidon or some other UML tool.
    Patterns are not individual constructs. One does not make a Mediator class. One makes a Java class that is an implementation of the Mediator pattern. As such you would see in the static class diagram the same grouping of classes for an X Mediator as you would for Y Mediator. That is the image you're looking for. It's not a single widget that you drag onto the screen, it's in the pattern itself.
    If, however, you're talking about something like a graphical representation to give to managers that says "Here be Momento patterns", then I would postulate that you're trying to communicate information that they don't need nor should they concern themselves with. Patterns are an implementation issue. They deal with, "How" we will solve a problem, not what problem will we solve. Mangaers, IMNSHO, need only concern themselves with what problems we will solve, not how they will be solved.
    Just my 2 krupplenicks on the subject, your milage may of course vary.
    PS.

  • Pattern and Matcher of Regular Expressions

    Hello All,
    MTMISRVLGLIRDQAISTTFGANAVTDAFWVAFRIPNFLRRLFAEGSFATAFVPVFTEVK
    ETRPHADLRELMARVSGTLGGMLLLITALGLIFTPQLAAVFSDGAATNPEKYGLLVDLLR
    LTFPFLLFVSLTALAGGALNSFQRFAIPALTPVILNLCMIAGALWLAPRLEVPILALGWA
    VLVAGALQLLFQLPALKGIDLLTLPRWGWNHPDVRKVLTLMIPTLFGSSIAQINLMLDTV
    IAARLADGSQSWLSLADRFLELPLGVFGVALGTVILPALARHHVKTDRSAFSGALDWGFR
    TTLLIAMPAMLGLLLLAEPLVATLFQYRQFTAFDTRMTAMSVYGLSFGLPAYAMLKVLLP
    I need some help with the regular expressions in java.
    I have encountered a problem on how to retrieve two strings with Pattern and Matcher.
    I have written this code to match one substring"MTMISRVLGLIRDQ", but I want to match multiple substrings in a string.
    Pattern findstring = Pattern.compile("MTMISRVLGLIRDQ");
    Matcher m = findstring.matcher(S);
    while (m.find())
    outputStream.println("Selected Sequence \"" + m.group() +
    "\" starting at index " + m.start() +
    " and ending at index " m.end() ".");
    Any help would be appreciated.

    Double post: http://forum.java.sun.com/thread.jspa?threadID=726158&tstart=0

  • What's the difference between JRE and HotSpot

    What's the difference between JRE and HotSpot?
    Where can i find HotSpot for Solaris?
    tks!

    The difference between the two is explained at:
    http://www.sun.ca/software/communitysource/hotspot/
    and
    http://www.sun.ca/software/communitysource/hotspot/faq.html
    It's included in the J2SE v1.3.1 release.

  • Why no answer from Sony to LED and Hotspot still Broken?

    Why in the world after I got suckered in to updating to ICS again (587), is LED notification for missed SMS and hotspot still not working?
    Why has no one with some official stature with Sony Mobile not posted a discussion to explain what the heck is going on?
    Is the group in Sweden that bad?
    Maybe that is why the office is being closed and the mobile group moved to Japan.  The mobile group obviously needs better management.
    Bob H
    ST18a  Ray
    AT&T
    USA

    Mambodoodle,
    Have you called Sony Tech Support to open a case?
    I have done so with each release of ICS, as I had to send my phone in for re-install of Ginberbread.
    I wonder if the call-in database would have more impact vs. this online forum.
    I COMPLETELY agree with you that they should at least acknowledge the situation here on the forum by someone fairly high up on the product team.
    Good luck,
    Bob H
    ST18a  Ray
    AT&T
    USA

  • Difference between Proxy pattern and Business Delegate pattern

    Hi All,
    Can any one please tell me what is the difference between Proxy pattern and Business Delegate pattern.
    Thanks in advance.
    Basak

    The books they were first reported in, and the expressed intent, I guess. Arguably, the Business Delegate pattern is a special case Proxy, with more specific details about what resource is being proxied

  • DAO pattern and Java Persistence API

    Hi
    This is a question for anyone who might be familiar with the standard DAO design pattern and the Java Persistence API (JPA - part of EJB3). I'm new to this technology, so apologies for any terminology aberrations.
    I am developing the overall architecture for an enterprise system. I intend to use the DAO pattern as the conceptual basis for all data access - this data will reside in a number of forms (e.g. RDBMS, flat file). In the specific case of the RDBMS, I intend to use JPA. My understanding of JPA is that it does/can support the DAO concept, but I'm struggling to get my head around how the two ideas (can be made to) relate to each other.
    For example, the DAO pattern is all about how business objects, data access objects, data transfer objects, data sources, etc relate to each other; JPA is all about entities and persistence units/contexts relate to each other. Further, JPA uses ORM, which is not a DAO concept.
    So, to summarise - can DAO and JPA work together and if so how?
    Thanks
    P.S. Please let me know if you think this topic would be more visible in another forum (e.g. EJB).

    Thanks, duffymo, that makes sense. However ... having read through numerous threads in which you voice your opinion of the DAO World According to Sun, I'd be interested to know your thoughts on the following ...
    Basically, I'm in the process of proposing an enterprise system architecture, which will use DAO as the primary persistence abstraction, and DAO + JPA in the particular case of persistence to a RDBMS. In doing so, I'd like to illustrate the various elements of the DAO pattern, a la the standard class diagram that relates BusinessObject / DataAccessObject / DataSource / TransferObject (http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html). With reference to this model, I know that you have a view on the concept of TransferObject (aka ValueObject?) - how would you depict the DAO pattern in its most generic form? Or is the concept of a generic DAO pattern compromised by the specific implementation that is used (in this case JPA)?

Maybe you are looking for