Static method,new thread performance question

Hey guys i just have two questions about two methods used in many controllers/servlets in my app:
1-what is the difference between calling a static method in a util class or a non static method (like methods dealing with dates i.e getting current time,converting between timezones), which is better ? 2-what is the difference between calling a method(contain too many logic like sending emails) in the controller directly or running this method in a different thread ?

cs.student wrote:
Hey guys i just have two questions about two methods used in many controllers/servlets in my app:
1-what is the difference between calling a static method in a util class or a non static method (like methods dealing with dates i.e getting current time,converting between timezones), which is better ?Depends on the design. It's impossible to say straight why one way would be better than another. Programming isn't that straight forward.
2-what is the difference between calling a method(contain too many logic like sending emails) in the controller directly or running this method in a different thread ?Threads can be run at the same time. So what you're asking is "what's the difference between doing one thing after another and doing two things at the same time".

Similar Messages

  • Instance methods faster than sync. static methods in threaded env?

    consider the following please:
    (-) i have "lots" of instances of a single Runnable class running concurrently..
    (-) each instance uses a common method: "exponential smoothing" and they do a lot of smoothing.
    so:
    (option #1): include a "smooth()" instance method in the Runnable class.
    (option #2): include a "smooth()" synchronized static method in the Runnable class.
    (option #3): create a MathUtility class, and have "smooth()" as an instance method in this class.
    (option #4): make "smooth()" a synchronized static method in the MathUtility class.
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??
    well, i can't image there would be a measurable difference so maybe i should not post.
    but, if there is a flaw in my thinking, please let me know.
    thanks.

    kogose wrote:
    from OOP point of view, i think i should externalize "smooth()" to a MathUtility class, and then make
    is "synchronized static".From an OOP point of view you should probably have a class that represents the data that provides a (non-static) smooth() method that either modifies the data or returns a new smoothed data object (depending on whether you want your data objects to be immutable or not).
    but then from a performance point of view....
    would not it be optimal to make "smooth()" an instance method in MathUtility and then have each
    instance of the Runnable create its own MathUtility instance so that each thread has its own copy
    of the "smooth()" method??No, methods are not "copied" for each instance. That just doesn't happen.
    well, i can't image there would be a measurable difference so maybe i should not post.If you don't know, then you should probably try it.
    but, if there is a flaw in my thinking, please let me know.The flaw in your thinking is that you can think that you can intuitively grasp the difference in performance of a change at that level.
    I have yet to meet anyone who can reliably do that.
    Performance optimization is not an intuitive task at that level and you should never do performance optimizations without proving that they are improvements for your particular use case.
    First part: Is the smooth() method really thread-unsafe? Does it use some shared state? My guess would be that it uses only local state and therefore doesn't need any synchronization at all. That would also be the fastest alternative, most likely.

  • Static method and threads?

    I have a question regarding "static". for example, I have the following code
    class Test{
    public int i=0;
    public static calculateInt(){
    ....some operations on i;
    if two processes attempt to call Test.calculateInt() at the same time. What will the effects be? shall these two calls be implemented totally independent? each call holds it own "i" for calculation. OR there will be operation conflicit on i.
    what if I change "public i" to :private i", the same effects?

    You can't operate on i in a static method, since i is an instance variable.
    If you make i static, then you can operate on it in a static method. In that case, all threads will share a single i--there's only one i for the whole class, and threads don't change that. Making it private won't change that.
    If you make the method into an instance (non-static) method, then any threads operating on the same instance will share the same i, regardless of whether it's public or private. Different threads operating on different instances will each have their own i.
    Java's Thread Tutorial
    JavaWorld: Introduction to Java threads
    IBM: Introduction to Java threads
    Google: java+threads+tutorial
    Also check out http://java.sun.com/j2se/1.4.2/docs/api/java/lang/ThreadLocal.html

  • Equivalent to [i]this[/i] and [i]getClass()[/i] inside a static method

    All business objects of my application (Customer, Car, etc.) extend a root class (RootObject) which performs retrieving operations. Such operations are delegated to a static Loader that calls the respective method according to the type of the business object (loadAllCustomers for Customers, loadAllCars for Cars, etc). The problem is that I am unable to know which class is calling RootObject.loadAll() (a Customer or a Car) because both this and getClass() cannot be used inside static methods.
    So, my question is : how can I determine which class is extending RootObject from inside its static loadAll() method ? It is either a Customer or a Car, but I cannot figure out how to get such information.
    public class Customer extends RootObject { /*...*/ }
    public class Car extends RootObject { /*...*/ }
    public class RootObject {
      protected static Loader loader = new Loader();
      public static RootObject[] loadAll() {
        return loader.loadAll(getClass());  // does not compile
    public class Loader {
      public RootObject[] loadAll(Class classe) {
        if (classe == Customer.class) return loadAllCustomers();
        if (classe == Car.class) return loadAllCars();
        return null;
    public static void main(String args[]) {
      Car cars[] = (Car[]) Car.loadAll();
      System.out.println("number of cars = " + cars.length);
    }Thank you.

    Thank you guys.
    We are trying to simulate an object-oriented database
    on top of a relational one (or a file, or whatever).Sounds like you really want ORM, like Hibernate or TopLink.
    Then, to retrieve a given car, we could be able to do
    Car car = new Car();
    car.setId("C1");
    car.load();Instead, to retrieve a list of cars, I think it is
    more intuitive to use a class method instead of an
    instance one because we'll return a list, not a
    single object :
    Car cars[] = (Car[]) Car.loadAll();instead of
    Car car = new Car();
    Car cars[] = (Car[]) car.loadAll();  // a little odd,
    isn't it ?Then, it is a design choice to make loadAll()
    a static method.Sounds to me like you're trying to create objects that know how to persist themselves. That's one way to do it.
    Another would be to separate the persistence code into a separate, interface-based class called a Data Access Object (DAO) or Repository that would handle this for you:
    public interface CarRepository
        List<Car> find();
        Car find(Long id);
        void save(Car c);
        void update(Car c);
        delete(Car c);
    }Now you can have different implementations for this interface, depending on how to wanted to tackle persistence. If it happens to be relational, all the SQL code is hidden from clients in the interface implementation.
    %

  • Static methods in concurrency

    I have a static method which takes a few String and double parameters and contains only local variables. When it is called by multiple threads there seems to be an exception thrown intermittenly. I got a little paranoid and so I've changed it to an instance method, and now the problem seems to disappear.
    Is this just a coincidence? Is my static method intrinsically thread-safe? Or are there any concurrency issues with static methods that I'm not aware of?
    Any reply is much appreciated!

    public static net.opengis.sos.v_1_0_0.InsertObservationResponse insertObservation(String serverURL, String AssignedSensorId, String dataType, String timeFrom, String timeTo, String srsName, double x, double y, long numElement, String dataString) throws MalformedURLException, IOException, JAXBException, ParserConfigurationException {
            OutputStream out = null;
            InputStream in = null;
            try {
                URL url = new URL(serverURL);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setRequestProperty("Content-type", "text/xml, application/xml");
                out = connection.getOutputStream();
                JAXBContext jaxbContext = JAXBContext.newInstance("net.opengis.sos.v_1_0_0:net.opengis.ows.v_1_1_0:net.opengis.sos.v_1_0_0.filter.v_1_1_0:net.opengis.sensorml.v_1_0_1:net.opengis.swe.v_1_0_1:net.opengis.om.v_1_0_0:net.opengis.gml.v_3_1_1:net.opengis.sampling.v_1_0_0");
                /////////////////////////////////request
                Marshaller marshaller = jaxbContext.createMarshaller();
                marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
                //////////////////////////////////////object factories
                net.opengis.gml.v_3_1_1.ObjectFactory gmlOF = new net.opengis.gml.v_3_1_1.ObjectFactory();
                net.opengis.swe.v_1_0_1.ObjectFactory sweOF = new net.opengis.swe.v_1_0_1.ObjectFactory();
                net.opengis.sampling.v_1_0_0.ObjectFactory saOF = new net.opengis.sampling.v_1_0_0.ObjectFactory();
                ////////////////////////////////////////////////////////////////////////////////////////////////getObservation request
                net.opengis.sos.v_1_0_0.InsertObservation insertObservation = new net.opengis.sos.v_1_0_0.InsertObservation();
                insertObservation.setAssignedSensorId(AssignedSensorId);
                net.opengis.om.v_1_0_0.ObservationType observation = new net.opengis.om.v_1_0_0.ObservationType();
                ///////////////////////////////om:samplingTime
                //begin position
                net.opengis.gml.v_3_1_1.TimePositionType beginTimePosition = new net.opengis.gml.v_3_1_1.TimePositionType();
                beginTimePosition.getValue().add(timeFrom);
                //end position
                net.opengis.gml.v_3_1_1.TimePositionType endTimePosition = new net.opengis.gml.v_3_1_1.TimePositionType();
                endTimePosition.getValue().add(timeTo);
                //time period
                net.opengis.gml.v_3_1_1.TimePeriodType timePeriod = new net.opengis.gml.v_3_1_1.TimePeriodType();
                timePeriod.setBeginPosition(beginTimePosition);
                timePeriod.setEndPosition(endTimePosition);
                net.opengis.swe.v_1_0_1.TimeObjectPropertyType timeObjectPropertyType = new net.opengis.swe.v_1_0_1.TimeObjectPropertyType();
                timeObjectPropertyType.setTimeObject(gmlOF.createTimePeriod(timePeriod));
    //            timeObjectPropertyType.setTimeObject(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.TimePeriodType.class, timePeriod));
                observation.setSamplingTime(timeObjectPropertyType);
                /////////////////////////////////om:procedure
                net.opengis.om.v_1_0_0.ProcessPropertyType processPropertyType = new net.opengis.om.v_1_0_0.ProcessPropertyType();
                processPropertyType.setHref(AssignedSensorId);
                observation.setProcedure(processPropertyType);
                /////////////////////////////////om:observedProperty
                net.opengis.swe.v_1_0_1.CompositePhenomenonType compositePhenomenonType = new net.opengis.swe.v_1_0_1.CompositePhenomenonType();
                compositePhenomenonType.setId("cpid0");
                compositePhenomenonType.setDimension(BigInteger.ONE);
                net.opengis.gml.v_3_1_1.CodeType codeType = new net.opengis.gml.v_3_1_1.CodeType();
                codeType.setValue("resultComponents");
                compositePhenomenonType.getName().add(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.CodeType.class, codeType));
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType phenomenonPropertyType1 = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                phenomenonPropertyType1.setHref("urn:ogc:data:time:iso8601");
                compositePhenomenonType.getComponent().add(phenomenonPropertyType1);
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType phenomenonPropertyType2 = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                phenomenonPropertyType2.setHref("Abfluss");
                compositePhenomenonType.getComponent().add(phenomenonPropertyType2);
                net.opengis.swe.v_1_0_1.PhenomenonPropertyType observedProperty = new net.opengis.swe.v_1_0_1.PhenomenonPropertyType();
                observedProperty.setPhenomenon(sweOF.createCompositePhenomenon(compositePhenomenonType));
                observation.setObservedProperty(observedProperty);
                ////////////////////////////////om:featureOfInterest
                net.opengis.sampling.v_1_0_0.SamplingPointType samplingPoint = new net.opengis.sampling.v_1_0_0.SamplingPointType();
                samplingPoint.setId(AssignedSensorId);
                net.opengis.gml.v_3_1_1.CodeType saName = new net.opengis.gml.v_3_1_1.CodeType();
                saName.setValue(AssignedSensorId);
                samplingPoint.getName().add(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.CodeType.class, saName));
                //samplingPoint.getSampledFeature().add(gmlOF.createFeaturePropertyType());
                net.opengis.gml.v_3_1_1.DirectPositionType pos = new net.opengis.gml.v_3_1_1.DirectPositionType();
                pos.setSrsName(srsName/*"urn:ogc:def:crs:EPSG:4326"*/);
                pos.getValue().add(x);
                pos.getValue().add(y);
                net.opengis.gml.v_3_1_1.PointType point = new net.opengis.gml.v_3_1_1.PointType();
                point.setPos(pos);
                net.opengis.gml.v_3_1_1.PointPropertyType pointProperty = new net.opengis.gml.v_3_1_1.PointPropertyType();
                pointProperty.setPoint(point);
                samplingPoint.setPosition(pointProperty);
                net.opengis.gml.v_3_1_1.FeaturePropertyType featureMember = new net.opengis.gml.v_3_1_1.FeaturePropertyType();
                featureMember.setFeature(saOF.createSamplingPoint(samplingPoint));
                net.opengis.gml.v_3_1_1.FeatureCollectionType featureCollectionType = new net.opengis.gml.v_3_1_1.FeatureCollectionType();
                featureCollectionType.getFeatureMember().add(featureMember);
                net.opengis.gml.v_3_1_1.FeaturePropertyType featureOfInterest = new net.opengis.gml.v_3_1_1.FeaturePropertyType();
                featureOfInterest.setFeature(gmlOF.createFeatureCollection(featureCollectionType));
    //            featureOfInterest.setFeature(new JAXBElement(new QName("http://www.opengis.net/gml", "name"), net.opengis.gml.v_3_1_1.FeatureCollectionType.class, featureCollectionType));
                observation.setFeatureOfInterest(featureOfInterest);
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                factory.setNamespaceAware(true);
                DocumentBuilder builder = factory.newDocumentBuilder();
                Document doc = builder.newDocument();
                final String sweNS = "http://www.opengis.net/swe/1.0.1";
                Element dataArray = doc.createElementNS(sweNS, "swe:DataArray");
                Element elementCount = doc.createElementNS(sweNS, "swe:elementCount");
                Element count = doc.createElementNS(sweNS, "swe:Count");
                Element value = doc.createElementNS(sweNS, "swe:value");
                dataArray.appendChild(elementCount).appendChild(count).appendChild(value).appendChild(doc.createTextNode(String.valueOf(numElement)));
                Element elementType = doc.createElementNS(sweNS, "swe:elementType");
                elementType.setAttribute("name", "Components");
                Element simpleDataRecord = doc.createElementNS(sweNS, "swe:SimpleDataRecord");
                Element timeField = doc.createElementNS(sweNS, "swe:field");
                timeField.setAttribute("name", "Time");
                Element time = doc.createElementNS(sweNS, "swe:Time");
                time.setAttribute("definition", "urn:ogc:data:time:iso8601");
                Element featureField = doc.createElementNS(sweNS, "swe:field");
                featureField.setAttribute("name", "feature");
                Element text = doc.createElementNS(sweNS, "swe:Text");
                text.setAttribute("definition", "urn:ogc:data:feature");
                Element dataField = doc.createElementNS(sweNS, "swe:field");
                dataField.setAttribute("name", dataType);
                Element quantity = doc.createElementNS(sweNS, "swe:Quantity");
                quantity.setAttribute("definition", dataType);
                Element uom = doc.createElementNS(sweNS, "swe:uom");
                uom.setAttribute("code", "m3 per s");
                simpleDataRecord.appendChild(timeField).appendChild(time);
                simpleDataRecord.appendChild(featureField).appendChild(text);
                simpleDataRecord.appendChild(dataField).appendChild(quantity).appendChild(uom);
                dataArray.appendChild(elementType).appendChild(simpleDataRecord);
                Element encoding = doc.createElementNS(sweNS, "swe:encoding");
                Element textBlock = doc.createElementNS(sweNS, "swe:TextBlock");
                textBlock.setAttribute("decimalSeparator", ".");
                textBlock.setAttribute("tokenSeparator", ",");
                textBlock.setAttribute("blockSeparator", ";");
                dataArray.appendChild(encoding).appendChild(textBlock);
                Element sweValues = doc.createElementNS(sweNS, "swe:values");
                dataArray.appendChild(sweValues).appendChild((doc.createTextNode(dataString)));
                Element result = doc.createElementNS("http://www.opengis.net/om/1.0", "om:result");
                result.appendChild(dataArray);
                observation.setResult(result);
                insertObservation.setObservation(observation);
                //handle "ogc" namespace bug
                NamespacePrefixMapper mapper = new PreferredMapper();
                marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", mapper);
                marshaller.marshal(insertObservation, System.out);
                marshaller.marshal(insertObservation, out);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                in = connection.getInputStream();
                Object response = unmarshaller.unmarshal(new StreamSource(in));
                if (response instanceof net.opengis.sos.v_1_0_0.InsertObservationResponse) {
                    return (net.opengis.sos.v_1_0_0.InsertObservationResponse) response;
                } else if (response instanceof net.opengis.ows.v_1_1_0.ExceptionReport) {
                    net.opengis.ows.v_1_1_0.ExceptionReport exceptionReport = (net.opengis.ows.v_1_1_0.ExceptionReport) response;
                    StringBuilder strBuilder = new StringBuilder();
                    for (net.opengis.ows.v_1_1_0.ExceptionType ex : exceptionReport.getException()) {
                        StringBuilder tempBuilder = new StringBuilder(ex.getExceptionCode() + ": ");
                        for (String temp : exceptionReport.getException().get(0).getExceptionText()) {
                            tempBuilder.append(temp + "\n");
                        strBuilder.append(tempBuilder.toString() + "\n");
                    throw new IllegalArgumentException(strBuilder.toString());
                } else {
                    throw new IllegalStateException("Unrecognizeable response type!");
            } finally {
                if (out != null) {
                    out.close();
                if (in != null) {
                    in.close();
        }Edited by: 808239 on 10-Feb-2011 02:44

  • How are static methods handled in a multithreaded application?

    hi
    i have a class Drawer with a static method public static draw(Graphics g). now assume there are more thrads callin at the same time Drawer.draw(g). What happens? have some threads to wait until the others have finished calling the method, or can static methods be multithreaded, (can they perform simultaniously)?
    thanks, jo

    ups, i am not drawing on the screen, but in every thread i am drawing a Image. this means before i call the static method in every thread there will be created a BufferedImage and then i pass the Graphics from this images to the static method. also in this case the method performs simultaniously? every thread has its own image and graphics, so the static method should be perform at the same time, isn't it?

  • OOPs Concept ! - Why Static Methods can't be redefined in its subclass ?

    Dear Experts ,
    I had searched the SDN , but unable to find out the satisfactorily answers ..
    Can anybody let me know the reason for the following Confusion in Oops Concept
    Question 1: As we know , We can Inherit the Static Methods in the Sub Class , But we can't redefine it in the base class  or       Sub Class  ?
    Question 2 : Why can't Static Method be Abstract ?
    Question 3 : Can a Class be Abstract or Final Both, If yes, then why ?
    Thanks in Advance
    Saurabh Goel

    As per the above discussion two of your doubts have already been clarified  so I am taking only third one.
    A class cannot never be Abstract and final both coz Abstract signifies that the implementation of the class has not been defined completelyi.e. may be some methods have been defined but few methods are still missing implementation. 'Final' is used for those classes/methods which cannot be redefined  means the complete implementation of the method has been defined no one can implement further logic under the same method.
    If you are saying your method is Final then it cannot be overridden and Abstract implies that method implementation is yet to be defined which can only be implemented if that class/method is not 'Final'. So both the terms are contradictory.
    Hope it clarifies!!!
    Thanks,
    Vishesh

  • Static methods in multi-thread environment.

    Sorry for this silly question, but I have no clue...
    If you're using classes with static methods in a application server environment, would that imply all threads use that same 'one in the jvm' method and would there be a possibility for performance loss?
    Is calling another static method from a static method a good idea in a multi-thread environment, with respect to performance? Somehow I seem to get this java.lang.NoClassDefFoundError. Any ideas? The classes are in the same package. I only get these kind of problems calling static methods from static methods in a multi-thread environmnent. The static methods are pure utility functions and of course do not use class state.
    Thanks for your help.

    Sorry for this question, wasn't thinking straight. I have the answer, won't post question on multiple forums.

  • Threading with static methods

    If I have a multithreading capabilities in my program, then I invoke a static method that writes timestamp to a file. What will happen? will all threads use this same static method? or will the program crash?

    static or otherwise isn't the issue. The issue is that it's not a good idea to have two threads trying to write to the same file at the same time.
    To prevent this you need to have each thread reserve the file until it's done it's thing. If you put the synchronized keyword on the method declaration you lock any all synchronized statis methods in the class, which is probably not idea. Probably better to use some comon object as the montor e.g.
    static File timeStamp = new File("timestamp.txt");
    public static void setTimeStamp() throws IOException {
         synchronized(timeStamp) {
              Writer out = new FileWriter(timeStamp);
              out.close();
         }

  • Namespace, static method questions

    The really useful script here is
    Sephiroth's
    Actionscript 3 PHP Unserializer. I have used the old AS2
    version many times and it's totally rad. With it you can create
    really complex data objects in php,
    serialize() them, and then
    unserialize them with this code in Flash. It dramatically reduces
    the amount of code you have to write to share complex data between
    PHP and Flash.
    The problem I'm having is that the new Actionscript 3 version
    was apparently written for Flex. When I try to use it in flash, I
    get an error:
    1004: Namespace was not found or is not a compile-time
    constant.. This error refers to this line of code:
    use namespace mx_internal;
    I know next to nothing about namespaces in Flash, but best I
    can tell, that namespace constant is apparently to be found in
    mx.core.
    At any rate, if I remove all references to mx_internal
    namespace and mx.core, I can get the script working. This brings me
    to my first questions:
    QUESTION 1: What does the use of that namespace stuff
    accomplish?
    QUESTION 2: Am I likely to suffer any unpredictable consequences
    by removing that namespace stuff?
    Also, I get an error (1061: Call to a possibly undefined
    method serialize through a reference with static type
    org.sepy.io:Serializer.) when I try to call the static methods of
    the Serialize class by instantiating it and calling the methods via
    the instance like this:
    var oSerializer:Serializer = new Serializer();
    var str = oSerializer.serialize(obj);
    That's my third question:
    QUESTION 3: Is it impossible to call a static method of a class
    from an instance of the class? Do we have to reference the class
    name instead?
    Any help would be much appreciated

    nikkj wrote:
    static methods are really class messages, that is, methods that act upon an entire classification of objects not just one instance. it is an elegant means by which to send messages to all instances or rather the class itself
    Static method calls are determined at compile time,not at run time, so it is not possible for the invocation to be polymorphic.(i.e can't be overridden)
    Because the language is defined that way - via the JLS.
    There is no technological reason that precludes a language from doing it. Smalltalk does exactly that.

  • Static methods in multi-threaded environment

    Hi,
    I am wondering what happens when several threads try to access the same static method ?
    The static method is not synchronized.
    Will this create any performance issues ?
    The actual scenario is of a J2EE server, where several Session Bean instances try to access a static method in a utility class. Will some session beans have to wait till others are being serviced ?
    thnx n regards
    s giri

    thanx for replying.
    yes. the operations are thread-safe. we do not change the state of any object.
    but we make an rmi call to another application thru this static method.
    is it ok?
    Currently, my session bean has too many private methods - each calling the other application. Due to some quality metrics (a class must be restricted to 700 lines) we have to consider moving these private methods into some Helper class in the form of "public static methods". We have made many utility methods as static, but have some reservations abt doing a similar thing for these methods that call other application.
    regards
    Shivraman

  • Do static methods perform better

    Sometimes, especially when refactoring (specifically when doing extract method), I create a method in a class to perform some helpful task or to neatly tuck a chunk of ugly code away somewhere that it can be easily referred to from the "actual" code. This new method doesn't actually directly cause a state change in the object, it just accepts a parameter and returns a value, or similar. In nearly every case this method is private (since it only helps out the class in which it appears).
    I can easily declare these helper methods static, or leave them unstatic. What I'm wondering is if there's any best practice in doing one or the other, whether for performance reasons or otherwise. I'd tend not to make them static because it might imply that the method should be called from a static context or something, but I wondered what others suggest in this regard.
    Thanks.

    I agree with you Dubwai, and in practice will probably
    not use static unless I mean it. But, since the
    methods don't really act on any of the class's
    instance members, I'm also not entirely convinced that
    this does go against the "design" -- because
    whether the method is static or not, it has the exact
    same effect.
    In fact, marking it static might even help make
    it obvious that this method performs no side-effects
    on instance members.
    But again, I think I'll just leave them nonstatic.I'm not saying that you shouldn't make things static. Quite the contrary. I'm saying that things should be static if they are static, meaning they don't change polymorphically or per instance. If this is so, the method should definitely be static.
    Not using instance members is a neccesary condition of being a static method but it is not nearly sufficient. Making a method static means throwing polymorphism out if the door. A method may do nothing but return a static final value but still need to be an instance method if a subclass needs to return a different static final value. If you make a method static and then need to refactor, it can be difficult or impossible to do so, as pointed out above. If you are calling static methods as if they are instance methods, that indicates to me that they probably should just be instance methods.

  • Are static methods in Java thread safe?

    Are static methods in Java thread safe?
    thanks,
    suresh

    if static method use the instance variable
    You mean member variable, where member variables are either class variables (static) or instance variables (non-static).
    then you have to make it thread safe using
    synchronization Not necessarily. Depends on requirements and usage context.
    else in case of local var. it
    is thread safe. Not necessarily. That local variable could refer to an object that's visible to multiple threads.
    Statements like "Local variables are threadsafe but member variables aren't" are an oversimplification.
    Something is threadsafe if it cannot be made to behave incorrectly simply by running it in a multithreaded context. Determining that can be very difficult.

  • I cannot find the new thread button to ask a question

    I just installed Firefox and need help but but cannot get to the New Thread button option to ask a question.
    How do I get there?

    Through the back door?
    You just asked a question so you can let us know what's up with Firefox.
    For future reference, you can ask a new thread at support.mozilla.org/questions/new and simply go through the prompts.
    Also, if you lost a thread you were on, you can go to your profile and see your questions and answers by clicking your username at the top of any support.mozilla.org page. Your account is located at https://support.mozilla.org/en-US/user/1082275

  • Thread Safety : Marking arguments of  static method as final

    Hi,
    I have a class with static method. This class will be hit by several threads and I need to make the code thread safe. If I declare the arguments of this method as "final", will it guratnee that these variables cannot be changed by another thread calling this method?
    Thanks in advance,
    Rtameh

    No, the only condtion where parameters or local variables might be shared with another thread is if you create a local class which uses them, and the compiler won't allow you to do that if they aren't final.
    Local variables are always thread-safe.

Maybe you are looking for