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

Similar Messages

  • When a static method is accessed concurrently

    When a static method is accessed by many objects symultaneously(concurrently),
    What is happened in the static method.
    Are the stacks for that method maded seperately and
    each stack doesn't influence other stacks?
    thank you in advance.

    The static objects or methods concept is clear, one
    instance for all objects.No. One instance for the class.
    , and every
    one know that, static methods is slower than
    nonstatic, Since when? I've certainly never heard that before... Do you have a reference I can look at?
    and this is as i thought because static
    methods are syncronized by default.Absoloutely not!
    All synchronization locks on an object. When you synchronize an instance method, it locks on the implicit "this"; When you synchronize a static method, it locks on the class's associated Class object.
    So two synchronized static methods in the same class can not be called at the same time, but synchronized instance methods that access static variables can all access those variables at the same time and potentially cause threading problems. In this situation you can declare the static fields volatile or wrap synchronized blocks around all code that accesses them, and synchronize on the same object (perhaps the Class object associated with the current class would be appropriate, but that reallt depends on the rest of your design).

  • Concurrent invocations of static method

    Hello.
    I have a static utility class that provides static utility methods. Some methods can take a while to complete. Question - is static method executed by one thread at a time? or there maybe multiple threads executing static methods simultaneously? (Note: methods are NOT synchronized)
    Thank you

    However, I remember reading that threads operate on
    local copies of shared data which is written to the
    main memory at some point of time. Does it refer to
    primitive types only?No, it refers to all local variables, including any method parameters. But you don't ever pass an object - you pass a reference to an object. Thus the reference is local, but any changes made to the object's state will be visible outside of the method.
    Also, it is allowable for threads to maintain local copies of variables - they don't have to; and if they do, they are allowed to write to and read from main memory at any time they like - synchronization forces a minimum number of points at which they must read and write to and from main memory, but they are free to do so at any other time as well.

  • 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 or not static method

    I have a simple class, ClassA, with no shared class variables, and has only one static method only:
    class ClassA {
    public static void doIO (args) {
    try {
    //very time consuming I/O task
    catach (Exceptions e) { 
    //try to resolve the problem
    This doIO method will be called simultaneously from different objects.
    My questions are:
    1) Would this static method approach cause any robustness, efficiency problem? Or, should I change the method into a non-static method, and create a new instance of ClassA every time?
    2) If there are 20 threads call ClassA.doIO(args) at the same time, would the method be executed in parallel or queued?
    Many thanks.
    java9394

    Using a static method makes this implementation as efficient as possible. Since the class has no instance variables, there is no benefit, to either making it non-static, or creating multiple instances. If you have 20 threads calling it, they will run concurrently. So, if you do not like this behavior, the method can be declared both static, and synchronized.

  • Are DLL methods called as instance or static methods from Java ?

    Hi,
    I have only a small question.
    When I call a C++ DLL method from Java using JNI, do I instantiate it like an object method or is it called as a static method ?
    I am asking you this because I will use servlets (Java 1.2.2) to call a DLL. These servlets may run concurrently in any moment, and I pass some data to this DLL. I want to know if there is any possibility of this data becoming corrupt, because of one concurrent servlet rewriting the data another servlet has passed.
    Thanks and regards.

    The question is not specific enough.
    Methods in C/C++ can be qualified with the following forms:
    -global (C/C++)
    -static member(C++ class method)
    -instance member(C++ class method)
    Since you didn't provide your code I couldn't possible determine which of the above you are using, but presumably you know.
    On the other hand a java native method is either static or non-static depending on how you defined it in the class. Once again without the code there is no way to say and presumably you already know this.
    The context of the methods is the same context that a similar servlet method has. But naturally in C/C++ is is easy to circumvent the context - for example by using a global variable.
    Data in C/C++ can always become corrupt and in the vast (all?) cases it is because something is wrong in the C/C++ code. Like a pointer that is not initialized, or a pointer used after it is free'd. Or writing past the end of a buffer, or writing before the beginning of a buffer.

  • Synchronized static method -is there a problem?

    Hi.
    I'm facing a problem. I have a common java class that is used by many applications. Class is in a jar file and is in server's shared library. And every applications in the server used it.
    Methods are declared static but not synchronized static. Class itself is not static. I have found that sometimes right after server is restarted and applications are using this class, method return values are mixed up or method behaviour is strange. I havent able to repeat this problem when testing with just one application.
    Is the problem static method and when using under one classloader (in shared lib) probelm occurs? So if i declare it static synchronized, does that solve my problem?

    Ok. But is it still risk to use static classes or
    static methods/fields in class that are shared with
    multiple applications ie. in servers shared library?That's a big fat YES.
    I suspect that you might benefit from investing a couple of hours in the "concurrency" tutorial
    http://java.sun.com/docs/books/tutorial/essential/concurrency/

  • Compilation error while calling static method from another class

    Hi,
    I am new to Java Programming. I have written two class files Dummy1 and Dummy2.java in the same package Test.
    In Dummy1.java I have declared a static final variable and a static method as you can see it below.
    package Test;
    import java.io.*;
    public class Dummy1
    public static final int var1= 10;
    public static int varDisp(int var2)
    return(var1+var2);
    This is program is compiling fine.
    I have called the static method varDisp from the class Dummy2 and it is as follows
    package Test;
    import java.io.*;
    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    and when i compile Dummy2.java, there is a compilation error <identifier > expected.
    Please help me in this program.

    public class Dummy2
    public int var3=15;
    public int test=0;
    test+=Dummy1.varDisp(var3);
    }test+=Dummy1.varDisplay(var3);
    must be in a method, it cannot just be out somewhere in the class!

  • Help needed for building report with execution method Java Concurrent prog

    Hi,
    I have saw a report like this:
    The report has executable "XML Publisher Data Template Executable", short name as "XDODTEXE", application "XML Publisher",execution method "Java Concurrent program". Also the report has a XML publisher Data Template and Data definition and in the data definition a .xml file is attached.
    I could not understand what is the data source?
    Could anyone help me on how to build or update this type of report?
    Is there any link or help docs which has proper step by step procedure to build this type of xml publisher report?
    Please help.
    Thanks.

    The xml file which is attached to the data definition is the data source and it has sql queries and structure of xml file.
    Check this out for step-by-step guidance.
    http://www.oracle.com/technetwork/middleware/bi-publisher/overview/xmlebsrep-132947.pdf
    http://apps2fusion.com/at/ps/51-prabhakar/262-xml-publisher-and-data-template-sql-query-to-develop-bi-publisher-reports
    For more on data templates refer user guide
    http://download.oracle.com/docs/cd/E10415_01/doc/bi.1013/e12187/T421739T434255.htm

  • Using a non-static vector in a generic class with static methods

    I have a little problem with a class (the code is shown underneath). The problem is the Assign method. This method should return a clone (an exact copy) of the set given as an argument. When making a new instance of a GenericSet (with the Initialize method) within the Assign method, the variables of the original set and the clone have both a reference to the same vector, while there exists two instances of GenericSet. My question is how to refer the clone GenericSet's argument to a new vector instead of the existing vector of the original GenericSet. I hope you can help me. Thanks
    package genericset;
    import java.util.*;
    public class GenericSet<E>{
    private Vector v;
    public GenericSet(Vector vec) {
    v = vec;
    private <T extends Comparable> Item<T> get(int index) {
    return (Item<T>) v.get(index);
    public static <T extends Comparable> GenericSet<T> initialize() {
    return new GenericSet<T>(new Vector());
    public Vector getVector() {
    return v;
    public static <T extends Comparable> GenericSet<T> insert (GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (!member(g,i))
    v.addElement(i);
    return g;
    public static <T extends Comparable> GenericSet<T> delete(GenericSet<T> z, Item<T> i){
    GenericSet<T> g = assign(z);
    Vector v = g.getVector();
    if (member(g,i))
    v.remove(i);
    return g;
    public static <T extends Comparable> boolean member(GenericSet<T> z, Item<T> i) {
    Vector v = z.getVector();
    return v.contains(i);
    public static <T extends Comparable> boolean equal(GenericSet<T> z1, GenericSet<T> z2) {
    Vector v1 = z1.getVector();
    Vector v2 = z2.getVector();
    if((v1 == null) && (v2 != null))
    return false;
    return v1.equals(v2);
    public static <T extends Comparable> boolean empty(GenericSet<T> z) {
    return (cardinality(z) == 0);
    public static <T extends Comparable> GenericSet<T> union(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = assign(z1);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> intersection(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> difference(GenericSet<T> z1, GenericSet<T> z2) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    insert(g, elem);
    for(int i=0; i<cardinality(z2); i++) {
    Item<T> elem = z2.get(i);
    if(!member(z1, elem))
    insert(g, elem);
    return g;
    public static <T extends Comparable> GenericSet<T> assign(GenericSet<T> z) {
    GenericSet<T> g = initialize();
    for(int i=0; i<cardinality(z); i++) {
    Item<T> elem = z.get(i);
    insert(g, elem);
    return g;
    public static <T extends Comparable> boolean subset(GenericSet<T> z1, GenericSet<T> z2) {
    for(int i=0; i<cardinality(z1); i++) {
    Item<T> elem = z1.get(i);
    if(!member(z2, elem))
    return false;
    return true;
    public static <T extends Comparable> int cardinality(GenericSet<T> z){
    Vector v = z.getVector();
    return v.size();
    }

    The issue is not "reference a non-static interface", but simply that you cannot reference a non-static field in a static method - what value of the field ed would the static method use? Seems to me your findEditorData should look something like this:   public static EditorBean findEditorData( String username, EditorBean editorData )
          return editorData.ed.findEditor( username );
       }

  • Using HttpServletRequest object to share variables between static methods.

    Does anyone know of the overhead/performance implications of using the HttpServletRequest object to share variables between a static method and the calling code?
    First, let me explain why I am doing it.
    I have some pagination code that I would like to share across multiple servlets. So I pulled the pagination code out, and created a static method that these servlets could all use for their pagination.
    public class Pagination {
         public static void setPagination (HttpServletRequest request, Config conf, int totalRows) {
              int page = 0;
              if (request.getParameter("page") != null) {
                   page = new Integer(request.getParameter("page")).intValue();
              int articlesPerPage = conf.getArticlesPerPage();
              int pageBoundary = conf.getPageBoundary();
                int numOfPages = totalRows / articlesPerPage;  
                // Checks if the page variable is empty (not set)
                if (page == 0 || (page > numOfPages && (totalRows % articlesPerPage) == 0 && page < numOfPages + 1)) {    
                 page = 1;  // If it is empty, we're on page 1
              // Ex: (2 * 25) - 25 = 25 <- data starts at 25
             int startRow = page * articlesPerPage - (articlesPerPage);
             int endRow = startRow + (articlesPerPage);           
             // Set array of page numbers.
             int minDisplayPage = page - pageBoundary;
             if (minDisplayPage < 1) {
                  minDisplayPage = 1;     
             int maxDisplayPage = page + pageBoundary;
             if (maxDisplayPage > numOfPages) {
                  maxDisplayPage = numOfPages;     
             int arraySize = (maxDisplayPage - minDisplayPage) + 1;
             // Check if there is a remainder page (partially filled page).
             if ((totalRows % articlesPerPage) != 0) arraySize++;
             // Set array to correct size.
             int[] pages = new int[arraySize];
             // Fill the array.
             for (int i = 1; i <= pages.length; i++) {
                  pages[i - 1] = i;
             // Set pageNext and pagePrev variables.
             if (page != 1) {
                  int pagePrev = page - 1;
                  request.setAttribute("pagePrev", pagePrev);
             if ((totalRows - (articlesPerPage * page)) > 0) {
                 int pageNext = page + 1;
                 request.setAttribute("pageNext", pageNext);
             // These will be used by calling code for SQL query.
             request.setAttribute("startRow", startRow);
             request.setAttribute("endRow", endRow);
             // These will be used in JSP page.
             request.setAttribute("totalRows", totalRows);
             request.setAttribute("numOfPages", numOfPages);
             request.setAttribute("page", page);
             request.setAttribute("pages", pages);          
    }I need two parameters from this method (startrow and endrow) so I can perform my SQL queries. Since this is a multithreaded app, I do not want to use class variables that I will later retrieve through methods.
    So my solution was to just set the two parameters in the request and grab them later with the calling code like this:
    // Set pagination
    Pagination.setPagination(request, conf, tl.getTotalRows());
    // Grab variables set into request by static method
    int startRow = new Integer(request.getAttribute("startRow").toString());
    int endRow = new Integer(request.getAttribute("endRow").toString());
    // Use startRow and endRow for SQL query below...Does anyone see any problem with this from a resource/performance standpoint? Any idea on what the overhead is in using the HttpServletRequest object like this to pass variables around?
    Thanks for any thoughts.

    You could either
    - create instance vars in both controllers and set them accordingly to point to the same object (from the App Delegate) OR
    - create an instance variable on the App Delegate and access it from within the view controllers
    Hope this helps!

  • Can you set a global EntityResolver (via system property, or static method)

    I'm trying to set a customized EntityResolver (telling the xml parser where to look for XML schema files).
    Usually, you'd use the standard syntax - somehting like:
    SaxParser parser=new SaxParser();
    parser.parser.setEntityResolver(myResolver);
    However, I was wondering whether you can set a "global" EntityResolver, to be used as default for all parsers ?
    Maybe this can be done through some system property, or a static method somewhere in the parsing XML ?
    (BTW, I need it because I'm using some third-party API, that encapsulates a SaxParser, but won't let me access it, so I can't configure it directly).
    thanks.

    I don't think you can.
    What is possible is to set content on the folder resource itself; that would be returned instead of the page you mentioned.

  • How to call a static method from an event handler

    Hi,
       I'm trying to call a static method of class I designed.  But I don't know how to do it.  This method will be called from an event handler of a web dynpro for Abap application.
    Can somebody help me?
    Thx in advance.
    Hamza.

    To clearly specify the problem.
    I have a big part code that I use many times in my applications. So I decided to put it in a static method to reuse the code.  but my method calls functions module of HR module.  but just after the declaration ( at the first line of the call function) it thows an exception.  So I can't call my method.

  • How to call a static method in a class if I have just the object?

    Hello. I have an abstract class A where I have a static method blah(). I have 2 classes that extend class A called B and C. In both classes I override method blah(). I have an array with objects of type B and C.
    For every instance object of the array, I'm trying to call the static method in the corresponding class. For objects of type B I want to call blah() method in B class and for objects of type C I want to call blah() method in C class. I know it's possible to call a static method with the name of the object, too, but for some reason (?) it calls blah() method in class A if I try this.
    So my question is: how do I code this? I guess I need to cast to the class name and then call the method with the class name, but I couldn't do it. I tried to use getClass() method to get the class name and it works, but I didn't know what to do from here...
    So any help would be appreciated. Thank you.

    As somebody already said, to get the behavior you
    want, make the methods non-static.You all asked me why I need that method to be
    static... I'm not surprised to hear this question
    because I asked all my friends before posting here,
    and all of them asked me this... It's because some
    complicated reasons, I doubt it.
    the application I'm writing is
    quite big...Irrelevant.
    Umm... So what you're saying is there is no way to do
    this with that method being static? The behavior you describe cannot be obtained with only static methods in Java. You'd have to explicitly determine the class and then explicitly call the correct class' method.

  • Calling a method from a static method

    hello all,
    I'm calling a non-static method from a static method (from the main method). To overcome this i can make the method i am calling static but is there another way to get this to work without making the method that is being called static?
    all replies welcome, thanks

    When you call a non-static method, you are saying you are calling a method on an object. The object is an instance of the class in which the method is defined. It is a non-static method, because the instance holds data in it's instance variables that is needed to perform the method. Therefore to call this kind of method, you need to get (or create an instance of the class. Assuming the two methods are in the same class, you could do
    public class Foo
         public static void main(String[] args)
                Foo f = new Foo();
                f.callNonStaticMethod();
    }for instance.

Maybe you are looking for