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

Similar Messages

  • Do the Interface contains static components like static methods and attribu

    Do the Interface contains static components like static methods and attributes ?

    >
    You have to supply a bit more detail: is that Lotus
    Notes API a Java API?Hmm, It's Java interface to Lotus Notes API
    Does it use JNI? Perhaps it is used somewhere underneath, I do not know for sure, but I think so
    Possibly the Lotus Notes
    implementation keeps a
    reference to those arrays, who knows?
    Maybe, but I'd be really suprised if it did. I derive this thread from Lotus Notes class and provide my own "worker method", overriding Lotus API abstract one, where I reference arrays. Arrays are specific to my program and since they are private fields in thread's class Lotus Notes layer does not have any way of referencing them, nor any reason for this matter
    For starters: if you zero out (set to null) your
    references to those arrays
    in your threads when the threads finish, there might
    surface a useful
    indication that you can blame Lotus Notes for this
    Well, I've become deeply suspect of whether these Notes' threads do really finish :-) My method finishes for sure, but it is just a part of run() method of Lotus Notes thread. Anyway, you can always safely blame Lotus Notes for almost anything :-)

  • 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".

  • 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 variables doubts

    i have a doubt
    i have the following method
    private static void checkActionType(String action) {
    if (action.startsWith(" a")) {
    ++totalAddedActions;
    } else if (action.startsWith(" c")) {
    ++totalChangedFolders;
    } else if (action.startsWith(" p")) {
    ++totalPersonalizedActions;
    } else if (action.startsWith(" r")) {
    ++totalRemovedActions;
    } else if (action.startsWith(" v")) {
    ++totalViewedActions;
    } else if (action.startsWith(" u")) {
    ++totalUpdateActions;
    to use it, i need to declare my int variables static, because im calling this method from another static method that is called by main method.
    but this can cause me problems ?
    if i have two instances of this class running, my statics int will show the right value?
    there is a better approach?

    Here is my class, i want some advices to know if i am doing right, because everything is a little new for me.
    My class, read a log file and based upon a regular expression, it can retrieve a general statistic or a personal statistic.
    package br.com.organox.aggregator;
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.Vector;
    import org.apache.oro.text.regex.*;
    public class LogFileReader {
    private static Pattern regexpPattern;
    private static PatternMatcher patternMatcher;
    private static PatternCompiler patternCompiler;
    private static PatternMatcherInput patternInput;
    private static MatchResult matchResult;
    private static final String patternString = "^[^\']+User\\s+\'([^\']+)\'[^\']+session\\s+\'([^\']+)\'\\s+(\\S+)";
    // Integers used to store number of user, sessions and specific actions
    private static int totalUsers;
    private static int totalSessions;
    private static int totalAddedActions;
    private static int totalChangedFolders;
    private static int totalPersonalizedActions;
    private static int totalRemovedActions;
    private static int totalUpdateActions;
    private static int totalViewedActions;
    public static void main(String[] args) {
    if (args.length == 0) {
    System.out.println("No file name was specified");
    printClassUsage();
    } else if (args.length == 1) {
    printGeneralData(args[0]);
    } else if (args.length == 2) {
    System.out.println("You must set file name, data value and data type in order to " +
    "this class run properly");
    printClassUsage();
    } else {
    printSelectedData(args[0],args[1],args[2]);
    public static void printGeneralData(String fileName) {
    String data = "";
    //Users and the Session Vector are used to avoid count repeated values.
    Vector usersVector = new Vector();
    Vector sessionVector = new Vector();
    patternCompiler = new Perl5Compiler();
    patternMatcher = new Perl5Matcher();
    try {
    regexpPattern = patternCompiler.compile(patternString);
    } catch (MalformedPatternException mpe) {
    System.out.println("Error Compiling Pattern");
    System.out.println(mpe.getMessage());
    try {
    FileReader fileRead = new FileReader(fileName);
    BufferedReader buffRead = new BufferedReader(fileRead);
    while ((data = buffRead.readLine())!= null) {
    patternInput = new PatternMatcherInput(data);
    while(patternMatcher.contains(patternInput,regexpPattern)) {
    matchResult = patternMatcher.getMatch();
    // Avoid to insert repeated data in user and session Vectors
    if (usersVector.lastIndexOf(matchResult.group(1)) == -1) {
    usersVector.add(matchResult.group(1));
    if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
    sessionVector.add(matchResult.group(2));
    increaseActionType(matchResult.group(3));
    for (int i=0;i<usersVector.size();i++) {
    totalUsers++;
    for (int i=0;i<sessionVector.size();i++) {
    totalSessions++;
    fileRead.close();
    buffRead.close();
    } catch (IOException ioe) {
    System.out.println("An I/O error occurred while getting log file data");
    ioe.printStackTrace();
    System.out.println("Users logged : " + totalUsers);
    System.out.println("Sessions opened : " + totalSessions);
    System.out.println("Added contents : " + totalAddedActions);
    System.out.println("Changed folders : " + totalChangedFolders);
    System.out.println("Personalized contents : " + totalPersonalizedActions);
    System.out.println("Removed contents : " + totalRemovedActions);
    System.out.println("Viewed Contents : " + totalViewedActions);
    System.out.println("Updated contents : " + totalUpdateActions);
    public static void printSelectedData(String fileName,String value,String valueType) {
    String data = "";
    String user = "";
    //Flag used to print the right result on screen
    String printFlag = "";
    Vector sessionVector = new Vector();
    Vector userVector = new Vector();
    Vector actionVector = new Vector();
    patternCompiler = new Perl5Compiler();
    patternMatcher = new Perl5Matcher();
    try {
    regexpPattern = patternCompiler.compile(patternString);
    } catch (MalformedPatternException mpe) {
    System.out.println("Error Compiling Pattern");
    System.out.println(mpe.getMessage());
    try {
    FileReader fileRead = new FileReader(fileName);
    BufferedReader buffRead = new BufferedReader(fileRead);
    while ((data = buffRead.readLine())!= null) {
    patternInput = new PatternMatcherInput(data);
    while(patternMatcher.contains(patternInput,regexpPattern)) {
    matchResult = patternMatcher.getMatch();
    if (valueType.equalsIgnoreCase("-user")) {
    printFlag = "userPrint";
    if ((matchResult.group(1).equalsIgnoreCase(value))) {
    userVector.add(matchResult.group(1));
    // avoid insert a repeated value inside session vector.
    if (sessionVector.lastIndexOf(matchResult.group(2)) == -1) {
    sessionVector.add(matchResult.group(2));
    increaseActionType(matchResult.group(3));
    if (userVector.size() == 0) {
    printFlag = "userPrintError";
    } else if (valueType.equalsIgnoreCase("-session")) {
    printFlag = "sessionPrint";
    if ((matchResult.group(2).equalsIgnoreCase(value))) {
    user = matchResult.group(1);
    sessionVector.add(matchResult.group(2));
    increaseActionType(matchResult.group(3));
    if (sessionVector.size() == 0) {
    printFlag = "sessionPrintError";
    } else if (valueType.equalsIgnoreCase("-action")) {
    printFlag = "actionPrint";
    if ((matchResult.group(3).equalsIgnoreCase(value))) {
    if (userVector.lastIndexOf(matchResult.group(1)) == -1) {
    userVector.add(matchResult.group(1));
    actionVector.add(matchResult.group(3));
    if (actionVector.size() == 0) {
    printFlag = "actionPrintError";
    fileRead.close();
    buffRead.close();
    } catch (IOException ioe) {
    System.out.println("An I/O error occurred while getting log file data");
    ioe.printStackTrace();
    if (printFlag.equals("userPrint")) {
    for (int i=0;i<sessionVector.size();i++) {
    totalSessions++;
    System.out.println("Sessions opened by user " + value + " : " + totalSessions);
    System.out.println("Added contents by user " + value + " : " + totalAddedActions);
    System.out.println("Changed folders by user " + value + " : " + totalChangedFolders);
    System.out.println("Personalized contents by user " + value + " : " + totalPersonalizedActions);
    System.out.println("Removed contents by user " + value + " : " + totalRemovedActions);
    System.out.println("Viewed contents by user " + value + " : " + totalViewedActions);
    System.out.println("Updated contents by user " + value + " : " + totalUpdateActions);
    } else if (printFlag.equals("userPrintError")) {
    System.out.println("This user " + value + " was not found on log file");
    } else if (printFlag.equals("sessionPrint")){
    System.out.println("Session " + value + " was opened by user " + user);
    System.out.println("Added contents by session " + value + " : " + totalAddedActions);
    System.out.println("Changed folders by session " + value + " : " + totalChangedFolders);
    System.out.println("Personalized contents by session " + value + " : " + totalPersonalizedActions);
    System.out.println("Removed contents by session " + value + " : " + totalRemovedActions);
    System.out.println("Viewed Contents by session " + value + " : " + totalViewedActions);
    System.out.println("Updated contents by session " + value + " : " + totalUpdateActions);
    } else if (printFlag.equals("sessionPrintError")){
    System.out.println("This session " + value + " was not found on log file");
    } else if (printFlag.equals("actionPrint")){
    System.out.println("Action " + value + " was performed " + actionVector.size() +
    " times for " + userVector.size() + " different user(s)");
    } else if (printFlag.equals("actionPrintError")){
    System.out.println("This action " + value + " was not found on log file");
    } else {
    System.out.println("Wrong search type!");
    System.out.println("Accepted types are: ");
    System.out.println("-user -> Search for a specified user");
    System.out.println("-session -> Search for a specified session");
    System.out.println("-action -> Search for a specified action");
    private static void increaseActionType(String action) {
    if (action.startsWith("a")) {
    ++totalAddedActions;
    } else if (action.startsWith("c")) {
    ++totalChangedFolders;
    } else if (action.startsWith("p")) {
    ++totalPersonalizedActions;
    } else if (action.startsWith("r")) {
    ++totalRemovedActions;
    } else if (action.startsWith("v")) {
    ++totalViewedActions;
    } else if (action.startsWith("u")) {
    ++totalUpdateActions;
    }

  • Static method and exception

    I have file which is reading from file and deleting it.
    delete is done by static method.
    now i need to do like this if file is empty it should throw exception and delte the file.
    so i added else like this
    else{
    throw new empty("Empty");
    but it is only thorowing exception not deleting file.as that static code is unreachable after throwing exception.
    any idea

    Hi zodok now this is original file just go through else statement in bold
    containing boolean a=deleteFile(fileName);
    package com.dhl.auditdatamgr.utils;
    import java.io.BufferedInputStream;
    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.StringTokenizer;
    import java.util.regex.Pattern;
    import com.dhl.auditdatamgr.business.DetailedFacilityAuditData;
    import com.dhl.auditdatamgr.exceptions.FileFormatException;
    import com.dhl.auditdatamgr.exceptions.SystemException;
    import com.dhl.auditdatamgr.exceptions.EmptyFileException;
    import com.dhl.auditdatamgr.utils.db.DataUtil;
    * @author mahiseth
    public class AuditFileParser
          * Constructor
         protected AuditFileParser()
              super();
         public static List parseFile(String fileName, String regex)
              throws IllegalArgumentException, FileNotFoundException, FileFormatException,SystemException, EmptyFileException
              DataUtil.enforceNotNullOrEmpty(fileName);
              DataUtil.enforceNotNullOrEmpty(regex);
              List rowList = new ArrayList();
              BufferedReader br = null;
              try
                   br = new BufferedReader(
                                                 new FileReader(new File(fileName)));
                   String line = null;
                   DetailedFacilityAuditData detailedAuditData = null;
                   Integer huExpected = null;
                   Integer huMissing = null;
                   Integer huExtra = null;
                   Integer shipmentExpected = null;
                   Integer shipmentMissing = null;
                   Integer shipmentExtra = null;
                   Integer pieceIdsExpected = null;
                   Integer pieceIdsMissing = null;
                   Integer pieceIdsExtra = null;
                   Pattern p = Pattern.compile(regex);
                   //while((line = br.readLine()) != null)
                   if ((line = br.readLine()) != null){
                        //System.out.println("Line: " + line);
                        //Pattern p = Pattern.compile("[\\p{Punct}&&[|]]");
                        String [] lineItems = p.split(line.trim());
                        if (lineItems.length != 18){
                                                 System.out.println("line = >>" + line + "<<");
                                                    System.out.println("lineItems.length = " + lineItems.length);
                                                    System.out.println("lineItems = " + java.util.Arrays.asList(lineItems));
                        detailedAuditData = new DetailedFacilityAuditData();
                        DataUtil.enforceNotNullOrEmpty(lineItems[0]);     
                        DataUtil.enforceNotNullOrEmpty(lineItems[5]);
                        DataUtil.enforceNotNullOrEmpty(lineItems[6]);     
                        DataUtil.enforceNotNullOrEmpty(lineItems[3]);          
                        detailedAuditData.setHuid(lineItems[0]);
                        detailedAuditData.setAuditAtServiceArea(lineItems[5]);
                        detailedAuditData.setAuditAtFacility(lineItems[6]);
                        detailedAuditData.setAuditTime(DataUtil.convertToTimestamp(lineItems[3]));
                        detailedAuditData.setHuType(lineItems[4]);
                        detailedAuditData.setBuiltAtServiceArea(lineItems[1]);
                        detailedAuditData.setBuiltAtFacility(lineItems[2]);
                        if(lineItems[9] != null && !lineItems[9].equals(""))
                             huExpected = new Integer(Integer.parseInt(lineItems[9]));
                             detailedAuditData.setHuExpected(huExpected);
                        if(lineItems[12] != null && !lineItems[12].equals(""))
                             huMissing = new Integer(Integer.parseInt(lineItems[12]));
                             detailedAuditData.setHuMissing(huMissing);
                        if(lineItems[13] != null && !lineItems[13].equals(""))
                             huExtra = new Integer(Integer.parseInt(lineItems[13]));
                             detailedAuditData.setHuExtra(huExtra);
                        if(lineItems[7] != null && !lineItems[7].equals(""))
                             System.out.println("Shipment expected is: " + lineItems[7]);
                             shipmentExpected = new Integer(Integer.parseInt(lineItems[7]));
                             detailedAuditData.setShipmentExpected(shipmentExpected);
                        if(lineItems[10] != null && !lineItems[10].equals(""))
                             shipmentMissing = new Integer(Integer.parseInt(lineItems[10]));
                             detailedAuditData.setShipmentMissing(shipmentMissing);
                        if(lineItems[11] != null && !lineItems[11].equals(""))
                             shipmentExtra = new Integer(Integer.parseInt(lineItems[11]));
                             detailedAuditData.setShipmentExtra(shipmentExtra);
                        if(lineItems[8] != null && !lineItems[8].equals(""))
                             pieceIdsExpected = new Integer(Integer.parseInt(lineItems[8]));
                             detailedAuditData.setPieceIdsExpected(pieceIdsExpected);
                        if(lineItems[14] != null && !lineItems[14].equals(""))
                             pieceIdsMissing = new Integer(Integer.parseInt(lineItems[14]));
                             detailedAuditData.setPieceIdsMissing(pieceIdsMissing);
                        if(lineItems[15] != null && !lineItems[15].equals(""))
                             pieceIdsExtra = new Integer(Integer.parseInt(lineItems[15]));
                             detailedAuditData.setPieceIdsExtra(pieceIdsExtra);
                        detailedAuditData.setAuditor(lineItems[16]);
                        detailedAuditData.setAuditDate(DataUtil.convertToDate(lineItems[17]));
                        rowList.add(detailedAuditData);
              } else{
                   System.out.println("file");
                   boolean a=deleteFile(fileName);
                   System.out.println(a);
                   throw new EmptyFileException("File is Empty");
              catch (IOException e)
                   throw new SystemException("An error occurred while trying to read the audit data file. " ,e);
                   //e.printStackTrace();
              } catch (ParseException e)
                   throw new FileFormatException("An error occurred while parsing the audit data file. " ,e);
                   //e.printStackTrace();
              catch (ArrayIndexOutOfBoundsException ae)
                   throw new FileFormatException("A required field is missing. " ,ae);
              finally
                    try
                        br.close();
                   } catch (IOException e1)
                        e1.printStackTrace();
              return rowList;
          * @param fileName - File name or directory to be deleted
          * @return true if and only if the file is successfully deleted, false otherwise
          * @throws IllegalArgumentException
         public static boolean deleteFile(String fileName)
              throws IllegalArgumentException
              DataUtil.enforceNotNullOrEmpty(fileName);
              File f = new File(fileName);
              boolean deleteStatus = false;
              deleteStatus = f.delete();
              return deleteStatus;
    }

  • How to stop an execution from a method and thread?

    1,
    public void method(){
    if( something is true)
    //I want to stop this method
    //or if something is false, go on
    blablablablabla
    }Does any one know how to solve the above??
    2,
    Thread t = new Thread(){
    public void run(){
    if( something is true)
    //I want to stop and kill this Thread
    //or if something is false, go on
    blablablablabla
    }Again, how do I solve the above??
    I know this is very simple, but I just hit a wall when I encounter this on making a program for my project.
    please help
    thanks alot

    warnerja, for the method, I have tried "return" but
    it does not work... will it work on the run method of
    thread object??
    Secondly, doesn't "break" keyword only stops the
    execution of a loop/condition, but not the method's
    scope??yes. break breaks the loop. I thought your method doesnt have any other code except the condition.
    use return with thread.

  • Why global var can be initialized with a static method and not by other static global var declared after its usage

    Take this:
    class test
    static int i=j;
    static int j=10;
    this will give illegal forward reference ....
    but this will compile successfully ..
    class test
    static int i=test1();
    static test1()
    return 20;
    plz assume we have main method in both cases ..
    java would be loading all static members first and would be assigning default values .. and then will be running all the initializers from to bottom ..
    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Plz help.
    Thanks
    Abhishek Roshan

    Why second case is a compile success and not first .. as in second also test1 method is declared after its usage ..
    Because the implementors of Java intentionally chose to do it that way.
    There are TWO stages to the process: preparation (which occurs first) and initialization.
    See the Java Language Spec section 12.4.1 'When Initialization Occurs
    The intent is that a class or interface type has a set of initializers that put it in a consistent state, and that this state is the first state that is observed by other classes. The static initializers and class variable initializers are executed in textual order, and may not refer to class variables declared in the class whose declarations appear textually after the use, even though these class variables are in scope (§8.3.2.3). This restriction is designed to detect, at compile time, most circular or otherwise malformed initializations.
    Note the clause beginning 'may not refer to class variables'. And the authors give the reason for that restriction in the last sentence: detect circular initializations.
    Then if you check that referenced section 8.3.2.3 you will find this
    http://docs.oracle.com/javase/specs/jls/se7/html/jls-8.html#jls-8.3.2.3
    8.3.2.3. Restrictions on the use of Fields during Initialization
    The declaration of a member needs to appear textually before it is used only if the member is an instance (respectively static) field of a class or interface C and all of the following conditions hold:
      The usage occurs in an instance (respectively static) variable initializer of C or in an instance (respectively static) initializer of C.
      The usage is not on the left hand side of an assignment.
      The usage is via a simple name.
      C is the innermost class or interface enclosing the usage.
    When a method is used (your example 2) no circular initialization can occur because methods are not 'initialized'.

  • Difference between calling static method and not static method?

    Hi,
    Suppose i want to write a util method, and many class might call this method. what is better? writing the method as static method or not static method. what is the difference. what is the advantace in what case?

    writing the method as static method or not static
    method. what is the difference.The difference is the one between static and non-static. Any tutorial or the JLs will clarify the difference, no need to repeat it here.
    what is the advantace in what case?It's usually not like you have much of a choice. If you need access to an instance's attributes, you can't make it static. Otherwise, make it static.

  • Static methods and how to access

    Hi,
    This seems like a silly quesion but i am trying to access a static method but it tells me that i cant.
    The method i am calling from is not static
    Thanks

    syntax: class name dot static method name (assuming the method is accessible): StaticMethodClassName.aStaticMethod();
    can't reference a class member (variable, object, method, ...) from a static method because a static method is not a class member (it is simply a method whose scope is confined to that of the class in which it is defined).
    example:
    class Foo
    int i;
    public static void hasSyntaxErr() // this method is not a member of Foo
    i = 0; // not allowed because i is a member of Foo
    class Fooo
    void testStatic() { Foo.hasSyntaxErr(); }
    }

  • Synchronized methods and thread locking

    Hi can someone please explain the difference between these two examples in the context of object locking
    public void method1(){
        synchronized(this){
    }And
    StringBuffer aStringBufferObject = new StringBuffer("A");
    public void method2(){
        synchronized(aStringBufferObject){
    }I know the first example will obtain a lock on the this instance and the second will obtain a lock of the aStringBufferObject instance. But i dont really understand what the effect or the difference of teh two is.
    For example, in the second example, will threads still be able to execute the code inside the synchronized block because the lock is not related to the 'this' instance?
    I know that synchronizing a method or a block of code prevents multiple threads to access that block/method at the same time but what is the purpose of specifying the object to lock on and what is the difference in the way the object is specified as in teh above examples.
    Thanks
    Edited by: ziggy on Jul 24, 2011 3:23 PM

    Shortly put, the synchronized(object) doesn't lock the object reference in any way. It locks the code inside the synchronized's brackets, so that code can run it only when they have locked object (or in truth, when they have acquired object's monitor).
    Since only one thread at a time can lock an object (obtain an object's monitor), this means that 2 threads executing blocks that synchronize on the same object can't run at the same time, ensuring thread safety (among other things).

  • Static and non-static variables and methods

    Hi all,
    There's an excellent thread that outlines very clearly the differences between static and non-static:
    http://forum.java.sun.com/thread.jsp?forum=54&thread=374018
    But I have to admit, that it still hasn't helped me solve my problem. There's obviously something I haven't yet grasped and if anyone could make it clear to me I would be most grateful.
    Bascially, I've got a servlet that instatiates a message system (ie starts it running), or, according to the action passed to it from the form, stops the message system, queries its status (ie finds out if its actually running or not) and, from time to time, writes the message system's progress to the browser.
    My skeleton code then looks like this:
    public class IMS extends HttpServlet
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
            doPost(request, response);
       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
          //get the various parameters...
             if (user.equalsIgnoreCase(username) && pass.equalsIgnoreCase(password))
                if(action.equalsIgnoreCase("start"))
                    try
                        IMSRequest imsRequest = new IMSRequest();
                        imsRequest.startIMS(response);
                    catch(IOException ex)
                    catch(ClassNotFoundException ex)
                else if(action.equalsIgnoreCase("stop"))
                    try
                        StopIMS stopIMS = new StopIMS();
                        stopIMS.stop(response);
                    catch(IOException ex)
                 else if(action.equalsIgnoreCase("status"))
                    try
                        ViewStatus status = new ViewStatus();
                        status.view(response);
                    catch(IOException ex)
             else
                response.sendRedirect ("/IMS/wrongPassword.html");
    public class IMSRequest
    //a whole load of other variables   
      public  PrintWriter    out;
        public  int                 messageNumber;
        public  int                 n;
        public  boolean         status = false;  //surely this is a static variable?
        public  String            messageData = ""; // and perhaps this too?
        public IMSRequest()
        public void startIMS(HttpServletResponse response) throws IOException, ClassNotFoundException
            try
                response.setContentType("text/html");
                out = response.getWriter();
                for(n = 1 ; ; n++ )
                    getMessageInstance();
                    File file = new File("/Users/damian/Desktop/Test/stop_IMS");
                    if (n == 1 && file.exists())
                        file.delete();
                    else if (file.exists())
                        throw new ServletException();
                    try
                        databaseConnect();
                   catch (ClassNotFoundException e)
    //here I start to get compile problems, saying I can't access non-static methods from inside a static method               
                   out.println(FrontPage.displayHeader()); 
                    out.println("</BODY>\n</HTML>");
                    out.close();
                    Thread.sleep(1000);
            catch (Exception e)
        }OK, so, specifially, my problem is this:
    Do I assume that when I instantiate the object imsRequest thus;
    IMSRequest imsRequest = new IMSRequest();
    imsRequest.startIMS(response); I am no longer in a static method? That's what I thought. But the problem is that, in the class, IMSRequest I start to get compile problems saying that I can't access non-static variables from a static method, and so on and so on.
    I know I can cheat by changing these to static variables, but there are some specific variables that just shouldn't be static. It seems that something has escaped me. Can anyone point out what it is?
    Many thanks for your time and I will gladly post more code/explain my problem in more detail, if it helps you to explain it to me.
    Damian

    Can I just ask you one more question though?Okay, but I warn you: it's 1:00 a.m., I've been doing almost nothing but Java for about 18 hours, and I don't do servlets, so don't take any of this as gospel.
    If, however, from another class (FrontPage for
    example), I call ((new.IMSRequest().writeHTML) or
    something like that, then I'm creating a new instance
    of IMSRequest (right?)That's what new does, yes.
    and therefore I am never going
    to see the information I need from my original
    IMSRequest instance. Am I right on this?I don't know. That's up to you. What do you do with the existing IMS request when you create the new FrontPage? Is there another reference to it somewhere? I don't know enough about your design or the goal of your software to really answer.
    On the other hand, IMSRequest is designed to run
    continuously (prehaps for hours), so I don't really
    want to just print out a continuous stream of stuff to
    the browser. How can I though, every so often, call
    the status of this instance of this servlet?One possibility is to pass the existing IMSRequest to the FrontPage and have it use that one, rather than creating its own. Or is that not what you're asking? Again, I don't have enough details (or maybe just not enough functioning brain cells) to see how it all fits together.
    One thing that puzzles me here: It seems to me that FP uses IMSReq, but IMSReq also uses FP. Is that the case? Those two way dependencies can make things ugly in a hurry, and are often a sign of bad design. It may be perfectly valid for what you're doing, but you may want to look at it closely and see if there's a better way.

  • Trying to understand Static methods

    Hi all,
    I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time.
    I am looking at a piece of code that had me thinking for a bit. I cant post the code itself but here is an example of how the code is structured
    The first class declares a couple of non static arrays and makes them available via the getters and setters. It also has one method that calls a static method in another class.
    package com.tests.statictest;
    import java.util.ArrayList;
    public class ClassA{
         ArrayList arrayList1 = new ArrayList();
         ArrayList arrayList2 = new ArrayList();
         public ClassA(){
              arrayList1.add("TEST1");
              arrayList1.add("TEST2");
              arrayList2.add("Test3");
              arrayList2.add("Test4");
         ArrayList getArrayList1(){
              return arrayList1;
         ArrayList getArrayList2(){
              return arrayList2;
         ArrayList getJoinedArrayList(){
              return ClassB.joinArrays(arrayList1,arrayList2);
    }The second class contains the static method that is called by the above class to join the two arrays. This class is used by many other classes
    package com.tests.statictest;
    import java.util.ArrayList;
    public class ClassB{
         public static ArrayList joinArrays(ArrayList list1, ArrayList list2){
              ArrayList list3 = new ArrayList();
              list1.addAll(list2);
              return list1;
    }And here is my test class
    package com.tests.statictest;
    public class ClassC{
          public static void main(String args[]){
               ClassA classA = new ClassA();
              System.out.println(classA.getArrayList1());
              System.out.println(classA.getArrayList2());
              System.out.println(classA.getJoinedArrayList());
         }The output to the above program is shown below
    [TEST1, TEST2]
    [Test3, Test4]
    [TEST1, TEST2, Test3, Test4]My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time? Woulnt the static method in ClassB corrupt the data?

    ziggy wrote:
    Hi all,
    I am trying to learn a little bit about static methods and hope that someone here can help me understand it better. My understanding of static methods is that they exist only once (More like global methods). This tells me that usage of static methods should be used with care as they are likely to cause problems in cases where multiple users try to access a static object at the same time. There is no such thing as a "static object" in Java. The word "static" simply means "belonging to a class as a whole, rather than an individual instance."
    My question for the above is that i am wondering if the above is safe. Can you think of situations where the above is not recommended. What exactly would happen if ten instances of ClassA threads are executed at the same time?ClassA isn't a thread, so it can't be "executed", per se.
    Woulnt the static method in ClassB corrupt the data?"Staticness" doesn't have anything to do with it; the issue at hand is operations on a shared data structure, which is a concern whether you're dealing with static or non-static members. There is nothing inherent in ClassB that will "corrupt" anything, however.
    ~

  • Singleton bottleneck with static methods?

    A discussion came up at work today. If a class is created as a Singleton and only provides static methods and only final static data members (just for storing read only info like a connection string), will this create a bottleneck? Someone was suggesting that sharing the Singleton would cause each thread accessing the code to have to obtain the monitor on the class before being able to execute the method. Is this the case? None of the methods are synchronized, but they all perform atomic functionality. Anyone have any input on this?

    Currenlty, it is implemented as a Singleton, part of
    the discussion was moving everything into static
    methods. Aside from that, the question is still
    whether having a single location to run methods from
    will become a bottleneckWho came up with the idea that this would create some sort of bottleneck? Never pay attention to them again.
    Static methods are (slightly) faster than ordinary instance methods because there is no virtual method lookup. The only way there would be some sort of performance implication is if the methods are synchronized. In that case performance will be essentially the same as synchronized instance methods of a singleton.

  • 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

Maybe you are looking for

  • 'Calendar UI' which will display current month's calendar in one line

    Hi Experts, I have to create a calendar in following way. Here I have to display calendar of current month for the employee. The entire month detail has to appear in one line. In fact it is needed for Leave Overview iView. Manager needs to view the L

  • Movies on NAS no longer showing on ATV

    I am new to this forum and need your help. I have had my ATV running for 6 months with no problems until a recent sw update. The problem I am experiencing is that I can longer see Movies that are not synced directly onto the ATV. I have about 100 mov

  • Apps user name missing from login

    Hi: I'm using iStudio and trying to create a Common Data Type based on an Oracle Applications table. When the login window appears, the username field is blank and grayed-out, and I can not enter any value, including the username "APPS". When I enter

  • Question on a Group By/Having SQL Query

    I have a table which lists Users and their Status (Created, Approved, Deleted, etc.) Each status has a timestamp. USER_ID | STATUS | TIMESTAMP mike | Created | 12:00 mike | Entered | 1:00 mike | Approved | 3:00 mike | Deleted | 4:00 john | Created |

  • Store user data row in modle session

    All, My use case is after successful login, i get a row in the VO. i don't want to store separate attributes in the model layer session and HTTP Session. How can i store the entire Row in the session and how do i access it. In my model layer i can do