Is this method thread safe?

Hi Guys
I have the following code:
public class MyClass extends HttpServlet {
     HttpSession session;
     public doGet(HttpServletRequest request, HttpServletResponse response)
                                  throws IOException, ServletException                              
          session = request.getSession(false);
          List<AClass> htransactions = (List<AClass>)session.getAttribute("AClass");
               //do stuff here
}What I want to know is that if the HttpSession session is declared as a instance variable, does this make it non thread safe? Or is using such a way of for a session fine?
.

Steve declared a thumb-rule.
Bear Bibeault
sheriff & author
Member # 24697
posted Yesterday 9:17 PM
Yes, variables created inside methods are safe because each thread will get their own copies. Instance variables are unsafe because they are shared across all threads.
Keep this in memory, hope this was a perfect clarification...you can declare now on the answer.

Similar Messages

  • Are Static methods Thread safe?

    Hello All
    I have a static method that takes a integer and returns a mathematically processed result.
    Since this method is frequently required, I have placed it in a common class and declared it as static.
    I want to know whether this method is thread safe?

    There's nothing special about static methods, with regard to thread safety. If they access shared objects, then such access will usually need to be controlled by synchronisation; this might be on the object being accessed, some higher-level object or a special object allocated purely as a lock. The only way that you might think of them as special is that there's no instance of the Class on which you can synchronise.
    You can declare a static method as synchronised. If you do, it will be synchronised on the single Class object of the class in which it is declared. This means that only one thread can be executing any part of the method at any one time. However, I understand that the Java Runtime itself sometimes synchronises on this Class object for its own reasons, therefore you might sometimes find a synchronised static method blocks when no other thread is executing it. Usually better, therefore, to explicitly synchronise on some object or other, than to use synchronised static methods.

  • Is this statement thread safe?

    Please tell whether the following statement is thread safe.
    counter++;
    (whether it is necessary to place it inside synchronized??)
    thanks,
    hawkins

    I believe the operation you describe is atomic so is "synchronized" if you prefer.
    That doesn't mean that your method will be thread-safe, though. An individual operation does no damage on its own - it's only when something else happens that thread-safety becomes an issue.
    If your question is "will my counter increase by 2 if two threads call counter++ at the same time?" then the answer is "yes".
    Thread-safety concerns the order in which operations happen across multiple threads, not whether they happen.
    If you're still not sure then please post up some context about what you're trying to do and perhaps some code to indicate where you think there may be a risk with concurrent access.

  • Are the service(), doPost() and doGet() methods THREAD-SAFE?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. If they are not thread safe, How to make them thread-safe?

    Please Let Me know If service(), doPost() and doGet() are Thread-safe. They are not.
    If they are not thread safe, How to make them thread-safe?The best way is to avoid writing code that depends on a servlet's thread safety; i.e., no servlet instance variables - keep everything local to the method. Else, you'll want to learn about synchronization.
    [JavaWorld article - Write thread-safe servlets|http://www.javaworld.com/javaworld/jw-07-2004/jw-0712-threadsafe.html].
    ~

  • Is ServletContext methods thread-safe?

    Just read servlet spec again, I know for shared data which is used by
              servlet must be thread-safe. But how about setAttribute/getAttribute methods
              on ServletContext and Session object? Are they thread-safe? or I have to
              synchronize the access to these methods?
              Any help is appreciated.
              

    hi Antalas,
    for Tomcat,it is not thread safe.but for WebSphere it is.for more info click on the following link :
    http://www.webagesolutions.com/knowledgebase/waskb/waskb026/index.html.
    [email protected]

  • Is this code thread safe?

    I've been seeing some information that makes me think that some servlet code I have that I thought was thread-safe actually isn't. I have a servlet that takes a POST request and calls a stored procedure on a database to do some inserts.
    public void doPost(HttpServletRequest request, HttpServletResponse response)
      // Check validity of request then proceed.
      if (valid) { postPayment(request); }
    synchronized private void postPayment(HttpServletRequest request)
      /* Take some parameters from the request and call the stored procedure */
    }What I'm attempting to do is ensure that 2 requests with the same data don't attempt to insert to the database at the same time. Have I accomplished that or do I need a different approach?

    Meatwad wrote:
    What if I had a static synchronized java bean that a member variable of the servlet class?As stated in my previous post:
    even that wouldn't be enough if there's more than one server running your app.and
    Since it database operations that you want to make atomic, the right place to ensure that is in the database.and
    The database is the only place where you're guaranteed a shared point of access to the resources you're trying to protect, so that's the appropriate (only) place to provide that protection.For an academic exercise with a single server, and if no other servlet or app is modifying the relevant tables, your approach is probably sufficient. But when all is said and done, a database transaction is the appropriate way to ensure exclusivity and atomicity of database operations.
    EDIT: Now, when you say "java bean", if you in fact are referring to an EJB, then I think they have their own tools and idioms for exclusivity and atomicity that encompass Java level syncing and DB transactions. I'm don't know anything about that though.
    Edited by: jverd on Jun 22, 2011 10:23 AM

  • Is this program thread safe?

    This program does not throw any exception or error.
    But sec Property is binding with secRotate's angleProperty and secRotate angleProperty is added to secHand's Transforms. This means that secProperty eventually affects Graphics.
    Do I have to call Platform.runLater() ?
    h2. Clock
    public class Clock extends Application {
         private Calendar calendar = Calendar.getInstance();
         private IntegerProperty sec = new SimpleIntegerProperty();
         @Override
         public void start(Stage primaryStage) throws Exception {
              Group root = new Group();
              Circle outer = new Circle(100, 100, 100, Color.DARKBLUE);
              Circle inner = new Circle(100, 100, 90, Color.web("EFEFEF"));
              Line secHand = new Line(100, 100, 100, 20);
              secHand.setStroke(Color.RED);
              root.getChildren().addAll(outer, inner, secHand);
              Rotate secRotate = new Rotate(0, 100, 100);
              secRotate.angleProperty().bind( sec.divide(60.0).multiply(360.0) );
              Thread thread = new Thread(new Runnable() {
                   public void run() {
                        while (true) {
                             setTime();
                             try {
                                  TimeUnit.SECONDS.sleep(1);
                             } catch (InterruptedException e) {
                                  e.printStackTrace();
              },"Clock Thread : NOT ON JavaFX Application Thread");
              thread.setDaemon(true);
              thread.start();
              secHand.getTransforms().add(secRotate);
              Scene scene = new Scene(root, 200, 200);
              primaryStage.setScene(scene);
              primaryStage.show();
         public void setTime() {
              System.out.println(Thread.currentThread().getName());
              calendar.setTimeInMillis(System.currentTimeMillis());
              sec.set( calendar.get(Calendar.SECOND ));
         public static void main(String[] args) {
              launch(args);
    }

    So, basically JavaFX doesn't tell me if I wrongly access nodes in another thread?Sometimes it does, sometimes it doesn't.
    Here is an example of what happens when the system detects an operation off the JavaFX Application Thread which should only happen on the JavaFX Application Thread (it throws an exception)
    // output:
    // java.lang.IllegalStateException: Not on FX application thread; currentThread = JavaFX-Launcher
    // and a stack trace for each illegal access.
    import javafx.application.Application;
    import javafx.scene.control.*;
    import javafx.scene.web.WebView;
    import javafx.stage.Stage;
    // demonstrates RT-17716: Some controls can only be created on the FX application thread
    public class InitThreadTest extends Application {
      public static void main(String[] args) { Application.launch(args); }
      @Override public void init() throws Exception {
        new Button();
        try { new WebView(); } catch (Exception e) { e.printStackTrace(); }
        try { new Tooltip(); } catch (Exception e) { e.printStackTrace(); }
        try { new ContextMenu(); } catch (Exception e) { e.printStackTrace(); }
      @Override public void start(Stage s) { System.exit(0); }
    }There may be plans to add more checks in more places, but I don't think there will ever be full coverage due to potential issues with performance, cluttering up the codebase, determining all the edge cases etc.
    do I have to call timeline.play() "in Java FX Application thread" if timeline has a KeyValue which is associated with Nodes property ?This is a very interesting question.
    No, you don't have to call timeline.play() on the JavaFX Application Thread.
    Irrespective of what thread the timeline was created in and play called from, the keyframe callback (and I would also surmise KeyValue manipulation) only happens on the Java FX Application thread.
    // output:
    // Main thread: Thread[main,5,main]
    // Init thread: Thread[JavaFX-Launcher,5,main]
    // FX thread: Thread[JavaFX Application Thread,5,main]
    // My thread: Thread[Thread-3,5,main]
    // Init launched timeline callback thread: Thread[JavaFX Application Thread,5,main]
    // My thread launched timeline callback thread: Thread[JavaFX Application Thread,5,main]
    import javafx.animation.*;
    import javafx.application.*;
    import javafx.event.*;
    import javafx.stage.Stage;
    import javafx.util.Duration;
    public class TimelineThreadTest extends Application {
      public static void main(String[] args) throws InterruptedException {
        System.out.println("Main thread: " + Thread.currentThread());
        Application.launch();
      @Override public void init() throws Exception {
        System.out.println("Init thread: " + Thread.currentThread());
        // print the timeline callback thread name after a second.
        Timeline t = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            System.out.println("Init launched timeline callback thread: " + Thread.currentThread());
        t.play();
      @Override public void start(final Stage stage) throws Exception {
        System.out.println("FX thread: " + Thread.currentThread());
        stage.setWidth(5); stage.setHeight(5);
        stage.show();
        // create a new thread test timeline processing.
        new Thread() {
          @Override public void run() {
            System.out.println("My thread: " + Thread.currentThread());
            Timeline t = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
              @Override public void handle(ActionEvent actionEvent) {
                System.out.println("My thread launched timeline callback thread: " + Thread.currentThread());
            t.play();
            try { Thread.sleep(2000); } catch (InterruptedException e) { /** no action required */ }
            Platform.runLater(new Runnable() { @Override public void run() { stage.close(); } });
        }.start();
    }Note that the callback to the FX application thread can only be setup and occur once the JavaFX system has been launched.
    This means Timelines are not useful outside of an FX application (e.g. for simulations or in a headless testing system) - which is unfortunate.
    // output:
    // My thread: Thread[Thread-0,5,main]
    // Timeline is never executed even though play is called on it.
    import javafx.animation.*;
    import javafx.event.*;
    import javafx.util.Duration;
    public class TimelineMainTest {
      public static void main(String[] args) throws InterruptedException {
        // print the timeline callback thread name after a second.
        Timeline t = new Timeline(new KeyFrame(Duration.seconds(1), new EventHandler<ActionEvent>() {
          @Override public void handle(ActionEvent actionEvent) {
            System.out.println("Timeline thread: " + Thread.currentThread());
        t.play();
        // create a new thread to wait a couple of seconds and prevent the main thread from shutting
        // down until we are sure the timeline thread has been given a chance to take action.
        new Thread() {
          @Override public void run() {
            try { Thread.sleep(2000); } catch (InterruptedException e) { /** no action required */ }
            System.out.println("My thread: " + Thread.currentThread());
        }.start();
    }

  • How can I make this function thread safe?

    delete this post please. accidental.

    is your function calling itself in its execution? that's why
    your array
    is being re-created with each call...
    sounds like you should be using a conditional loop... maybe
    something like:
    <cfset var functionItemID = arguments.itemID />
    <cfset var bcArray = arraynew(1)>
    <cfloop
    condition="application.tags.hasParent(functionItemID,arguments.itemDeleted,arguments.itemS tate)
    is true">
    <cfset
    arrayAppend(bcArray,application.tags.getItemField(functionItemID,"item_id"))
    />
    <cfset functionItemID =
    application.tags.getParent(functionItemID,arguments.itemDeleted,arguments.itemState)
    />
    </cfloop>
    <cfreturn bcArray />
    [NOTE: absolutely untested]
    Azadi Saryev
    Sabai-dee.com
    http://www.sabai-dee.com/

  • Jpanel setBackground color thread safe?

    is this method thread safe?
    meaning do i have to use Invoke on the dispatch thread everytime or
    it doesn't really matter

    is this method thread safe?
    meaning do i have to use Invoke on the dispatch
    thread everytime or
    it doesn't really matterThat's not what thread safe means, but yes, you should be able to call it from any thread.

  • How to make a global scope component to be thread safe?

    One of my global component preserves states in its member variables, I am afraid that it's might messed up in multi-threading conditions, so how to make a nucleus global component to be thread safe?
    Edited by: user13344577 on Jul 14, 2011 9:45 AM

    Hi,
    Just to help integrate Shaik's and my own seemingly contradictory replies:
    If the member variables in your global component actually need to be globally available, so that multiple threads/sessions need to seem the same data, then you need to use synchronization or some scheme to make this data thread-safe when updating it. If the member variables are non-global data and are simply for convenience of having data available for multiple method calls or something like that, then you should do as I said (don't use synchronization) and use one of my suggestions to avoid this.
    I have seen customers frequently do what I replied about and store non-global data in a global component, and Shaik simply interpreted what "user13344577" is trying to do differently. Clarification is needed to know which of our answers better applies.
    Thanks.
    Nick Glover
    Oracle Support for ATG Products

  • Thread Safe Testing

    I havn't written much mult-threaded code but I realise it's important when many web round-trips are required.
    How do I design, test and verify that I have a thread-safe application? I don't like relying on the testing statistics of chance unless the odds of failure are 0.0001%!
    Is there a correct way to verify a thread-safe application?

    I agree it is a lofty, though sadly in all probability too time consuming, goal to achieve. However, there are a few pitfalls to watch out for that should get most of the common, pernicious thread safety issues:
    Synchronize data that must be shared. This will involved performance bottle-necks. If the data is read-mostly, consider a Singleton cache. Though pitfalls will always remain here. Data sharing among threads, IMO, is the single greatest issue.
    Use static methods and instances wisely. If an object has instance variables that are used from method to method call (either within the class or from the caller), then state exists for that object. It is inherently a candidate to look at in terms of thead-safety. This class should be created for each logical unit of work that depends on its state. So, do not reuse these classes among threads (or at least provide an init() or reset() method to clear the state). The same applies to static methods. You can safely use a static method from multiple threads if it does not modify other static variables (e.g., changing the state of a static variable).
    Within the Collections API, pay attention to which types are synchronized and which are not. The Javadocs will specify.
    Try to write methods thread-safe. Have them only use the arguments provided in the method's signature.
    Watch for relatively simple race conditions that can easily be spotted.
    static private Singleton INSTANCE;
    private Singleton() {
        super();
        // Now I will fetch values from a database, perhaps taking seconds
    static final public Singleton getInstance() {
          if (INSTANCE == null) {
             INSTANCE = new Singleton();  // what if this takes some time, e.g. database query to get cache values?
          return INSTANCE;
    }Not good. Here's a possible refactoring:
    private static final Singleton INSTANCE;  // bonus, we can now make it final
    static {
       INSTANCE = new SIngleton();  // Occurs only when class is loaded, atomic
    public static final Singleton getInstance() {
      return INSTANCE;  // no race condition
    }The above would be even more applicable and pronounced if you offered a static refresh() method on the instance, say to refresh its cache of data from a database.
    Seems easy, right? The rub is that you need to verify that a given method does not call other methods that are not thread-safe. If every class you design follows the above precepts, then you will probably only be chasing down rarer thread-safety issues.
    - Saish

  • Java.lang.reflect.Constructor thread safe ?

    When you have a Constructor object in Java.
    Is calling the newInstance method on the same Constructor object from multiple threads safe.
    Or is this not thread safe leading to wrongly constructed objects?

    ejp wrote:
    And as Constructors are immutable, it's hard to see how it's going to get altered.Constructors are basically immutable, but they have at least one state which can make the difference between newInstance working or failing.
    As you can see in the following example, setAccessible() is not something you would want to set to different values in different threads.
    import java.lang.reflect.Constructor;
    public class Main {
        public static void main(String... args) throws Exception {
            Constructor cons = Private.class.getDeclaredConstructor();
            cons.setAccessible(false);
            try {
                System.out.println("cons.isAccessible()= " + cons.isAccessible());
                cons.newInstance();
                throw new AssertionError("IllegalAccessException expected");
            } catch (IllegalAccessException expected) {
                // ignored
            cons.setAccessible(true);
            System.out.println("cons.isAccessible()= " + cons.isAccessible());
            cons.newInstance();
    class Private {
        private Private() {
    }

  • Trying to understand "thread-safe" w/ swing components

    The other day there was a big hullabaloo about some code I posted because I was calling JLabel.setText from a thread that wasn't the ui thread. On the other hand, this thread was the only thread making changes to the JLabel. My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?
    Second question - JLabel.setText() is essentially setting data in the model for JLabel, which then gets picked up and displayed the next time the GUI thread paints it. So if it's not safe to update a JLabel's model, I assume its never safe to update any data that also is being displayed visually. So for instance, if I was showing some database table data in a JTable, I should do the update in the UI thread - probably not. But what is the distinction?
    Third question - what swing components and what operations need to be run on the UI thread to call your program "thread-safe". Validate? setSize()? setLocation()? add? remove? Is there anything that can be called on swing components from a non-ui thread?
    Edited by: tjacobs01 on Nov 2, 2008 8:29 PM

    tjacobs01 wrote:
    My understanding is that in any kind of multi-threaded system, if you just have 1 writer / changer, then no matter how many readers there are, this is thread-safe. So why what I was doing not thread safe?This is not true. As I mentioned in that hullabaloo thread, the Java Memory Model allows threads to cache values of variables they use. This means that values written by one thread are not guaranteed to ever be visible to other threads, unless you use proper synchronization.
    Take the following example:
    import java.util.concurrent.TimeUnit;
    public class ThreadExample {
        static class Foo {
            private String value = "A";
            public String getValue() {
                return value;
            public void setValue(String value) {
                this.value = value;
        public static void main(String[] args) {
            final Foo foo = new Foo();
            Thread writer = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.SECONDS.sleep(1);
                        foo.setValue("B");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            Thread reader = new Thread() {
                @Override
                public void run() {
                    try {
                        TimeUnit.MINUTES.sleep(1);
                        System.out.println(foo.getValue());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
            writer.start();
            reader.start();
    }Here two different threads both access the same Foo instance, which is initialized with a value of "A". One thread, the writer, sleeps one second, and then sets foo's value to "B". The other thread, the reader, sleeps one minute (to avoid race conditions) and then prints foo's value to System.out. It may seem obvious that the reader thread will read the value "B", but this is in fact not guaranteed to be true. The reader thread may never see the value that was written by the writer thread, so it may very well read the old value "A".
    (If you run the code you will probably see "B" printed out, but again, this is not guaranteed behavior.)
    A simple way to fix this is to synchronize access to the mutable state that the two threads share. For example, change the class Foo to
        static class Foo {
            private String value = "A";
            public synchronized String getValue() {
                return value;
            public synchronized void setValue(String value) {
                this.value = value;
        }It's for this same reason that you often see the use of a volatile boolean as a control flag for stopping threads, rather than a plain old boolean. The use of volatile guarantees that the thread you want to stop actually sees the new value of the flag once it has been set by another thread.
    Here is an article that touches some of this stuff:
    [http://www.ibm.com/developerworks/java/library/j-jtp02244.html]
    I also highly recommend the book "Java Concurrency in Practice" (one of the authors of which, David Holmes, sometime hangs out on the Concurrency forum here, I believe).
    Edited by: Torgil on Nov 2, 2008 9:01 PM

  • ..this method should be invoked from the event-dispatching thread?

    I see this (the title that is) in every single Java demo/example program on this (Sun's) site. However, I just tend to
    public static void main(String[] args){
       new whateverTheClassIsCalled();
    }And I've seen this approach on other sites and other example programs.
    So what exactly is better about this;
        public static void main(String[] args) {
            //Schedule a job for the event-dispatching thread:
            //creating and showing this application's GUI.
            javax.swing.SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    createAndShowGUI();
        }where createAndShowGUI() sets and packs the frame. I just do all this in the class constructor (when it's a JFrame!)
    So what does all this thread dispatching stuff mean, why should I use it etc etc.
    tia.

    Is it just me? For some reason it rubs me the wrong way that swing isn't thread safe. From what I've read, my understanding is that its safe to modify swing components from other threads as long as they haven't asked to be painted. If you don't do paint(), pack() or setVisible(true) until the end of your initialization, you will be safe.
    The reason for not being thread safe is almost certainly performance. Swing is slow enough as it is. Since the vast majority of Swing activity takes place in response to events and thus is on the EDT, there usually isn't a problem.
    This is a serious nuisance in network and database programs where multiple threads are used. I end up using invokeLater a lot in those cases, but never for initialization. Sun has only started to recomment that recently.
    Note that the fireXXX methods do not put the event on the EDT, these simply create Event objects and send them to Listeners. If they are executed off the EDT the Listeners will get called off the EDT.

  • How can I get to know if a method is threads-safe?

    Hi, there.
    How can I get to know if a method is threads-safe?
    For example, in two different threads, is System.out.print() method safe or not?And where can I find the information with regard to this?
    thanks very much.

    System.out is a PrintStream object. None of the methods there use the synchronized modifier, but if you look in the source code, you will find out it is thread-safe, because it will use synchronized blocks whenever it writes some text.
    The source code is in the src.jar file which you can extract.
    I didn't find any comments about that PrintStream is thread-safe in the API.

Maybe you are looking for

  • External requirement from non SAP system created in SRM 7.0 Extended Classi

    Hello SRM Gurus: Has anyone created an external requirement using XI ExternalRequirement_Create_In (http://sap.com/xi/EBP).  We are getting a E001 "No company code could be determined for backend  for product##".  I traced the error to FM 'BAPI_SCEC_

  • How can I change all the recipients in a PRE-PREPARED list from 'to' to 'bcc'?

    I know if I type in the first recipient and hit 'bcc', the next one automatically changes if I'm composing a multiple-recipient email from scratch. However, I already have a pre-prepared sub-list in my Contacts folder. If I click on 'Write', all the

  • Newbie just switched over to mac

    i just got my 1.83 mbp and connected my external hdd to it. everything seems to be fine except for a folder which contains a bunch of music videos. for some reason on the mbp it shows the folder to have nothing on it. when i stick the hdd back onto m

  • Bios A6380VMS.370 or A6380VMS.374 ?

    What is the difference ? I want to upgrade my K7T266 Pro (MS-6380) Thanks Hans

  • Class object

    Hi, I have a question about the class Class. Assume that I have written a program containing 3 classes (say 1.java, 2.java, 3.java). Now, when the program is compiled, we get 3 classes namely 1.class, 2.class and 3.class. Are these the classes that a