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.

Similar Messages

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

  • 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/

  • Should this statement be within synchronized block

    I am trying to generate an unique ID as follows:
    uniqueID = String.valueOf( System.currentTimeMillis() + (long) Math.random() )
    Is this statement thread-safe? Should this statement be enclosed within a 'synchronized' block?
    Thanks

    >
    Sorry I missed the issue with casting to a long. That
    certainly makes it easy to get duplicates.
    The problem with (long) Math.random is that you get always 0
    public class LongTest {
         * @param args
        public static void main(String[] args) {
            int failed = 0;
            for (int i = 0; i < 1000000; i++) {
                if (((long) Math.random()) > 0) {
                    failed++;
            System.out.println(failed);
    With the bug in place, and a single-thread, the code
    requires that calls to this piece of code occur
    further apart than the resolution of
    currentTimeMillis() - which as I said is often as
    coarse as 10ms (but can be 15ms on some Windows
    platforms). If you now throw multiple threads in then
    the chances of duplicates is very real.Yes, since with that call you use only System.currentTimeMillis() that, as you said, is coarse grained
    >
    There are easier ways to get unique IDs - just see
    java.util.UUID. Or just use an atomic counter.Yes.

  • 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

  • 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

  • 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() {
    }

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

  • Is this thread safe?

    I've got a HttpServletRequest instance variable in my servlet that I use in my model to retrieve parameters. The servlet looks like:
    public class MyServlet extends HttpServlet implements Controller {
      HttpServletRequest req;
      public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
      public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        processRequest(req, resp);
      public void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.req = req;
        MyModel model = new MyModel(this);
        model.retrieve();
      public String getParameter(String parameter) {
        return req.getParameter(parameter);
    }The Controller interface has only one method - public String getParameter(String parameter)
    In MyModel because I pass an instance of Controller into the constructor I can do - controller.getParameter(parameter);
    Is what I'm doing thread safe?

    Actually, a static nested class is more appropriate than an inner class as there is no implicit outer-class reference to maintain:
    public class MyServlet extends HttpServlet {
        public void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            processRequest(req, resp);
        public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            processRequest(req, resp);
        public void processRequest(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {
            MyModel model = new MyModel(new MyController(req));
            model.retrieve();
        private static class MyController implements Controller {
            private HttpServletRequest req;
            MyController(HttpServletRequest req) {
                this.req = req;
            public String getParameter(String parameter) {
                return req.getParameter(parameter);
    }This code is now thread safe because there is a different instance of MyController per thread. Note that if an instance of MyController is accessed by multiple threads, then its thread safety is dependent upon the thread safety of HttpServletRequest. However, based on the sort of thing I assume you are trying to do, I doubt you will be sharing instances between threads.

  • Native library NOT thread safe - how to use it via JNI?

    Hello,
    has anybody ever tried to use a native library from JNI, when the library is not thread safe?
    The library (Windows DLL) was up to now used in an MFC App and thus was only used by one user - that meant one thread - at a time.
    Now we would like to use the library like a "server": many Java clients connect the same time to the library via JNI. That would mean each client makes its calls to the library in its own thread. Because the library is not thread safe, this would cause problems.
    Now we discussed to load the library several times - separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this way?
    Are there other ways to use the library, though it is not thread safe?
    Any ideas welcome.
    Thanks for any contributions to the discussion, Ina

    (1)
    has anybody ever tried to use a native library from
    JNI, when the library (Windows DLL) is not thread safe?
    Now we want many Java clients.
    That would mean each client makes its calls
    to the library in its own thread. Because the library
    is not thread safe, this would cause problems.Right. And therefore you have to encapsulate the DLL behind a properly synchronized interface class.
    Now the details of how you have to do that depends: (a) does the DLL contain state information other than TLS? (b) do you know which methods are not thread-safe?
    Depending on (a), (b) two extremes are both possible:
    One extreme would be to get an instance of the interface to the DLL from a factory method you'll have to write, where the factory method will block until it can give you "the DLL". Every client thread would obtain "the DLL", then use it, then release it. That would make the whole thing a "client-driven" "dedicated" server. If a client forgets to release the DLL, everybody else is going to be locked out. :-(
    The other extreme would be just to mirror the DLL methods, and mark the relevant ones as synchronized. That should be doable if (a) is false, and (b) is true.
    (2)
    Now we discussed to load the library several times -
    separately for each client (for each thread).
    Is this possible at all? How can we do that?
    And do you think we can solve the problem in this
    way?The DLL is going to be mapped into the process address space on first usage. More Java threads just means adding more references to the same DLL instance.
    That would not result in thread-safe behavior.

  • Is Persistence context thread safe?  nop

    In my code, i have a servlet , 2 stateless session beans:
    in the servlet, i use jndi to find a stateless bean (A) and invoke a method methodA in A:
    (Stateless bean A):
    @EJB
    StatelessBeanB beanB;
    methodA(obj) {
    beanB.save(obj);
    (Stateless bean B, where container inject a persistence context):
    @PersistenceContext private EntityManager em;
    save(obj) {
    em.persist(obj);
    it is said entity manager is not thread safe, so it should not be an instance variable. But in the code above, the variable "em" is an instance variable of stateless bean B, Does it make sense to put it there using pc annotation? is it then thread safe when it is injected (manager) by container?
    since i think B is a stateless session bean, so each request will share the instance variable of B class which is not a thread safe way.
    So , could you please give me any guide on this problem? make me clear.
    any is appreciated. thank you
    and what if i change stateless bean B to
    (Stateless bean B, where container inject a persistence context):
    @PersistenceUnit private EntityManagerFactory emf;
    save(obj) {
    em = emf.creatEntityManager()
    //begin tran
    em.persist(obj);
    // commit tran
    //close em
    the problem is i have several stateless beans like B, if each one has a emf injected, is there any problem ?

    Hi Jacky,
    An EntityManager object is not thread-safe. However, that's not a problem when accessing an EntityManager from EJB bean instance state. The EJB container guarantees that no more than one thread has access to a particular bean instance at any given time. In the case of stateless session beans, the container uses as many distinct bean instances as there are concurrent requests.
    Storing an EntityManager object in servlet instance state would be a problem, since in the servlet programming model any number of concurrent threads share the same servlet instance.
    --ken                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Thread safe ?

    Hi
    This code is currently running on my companys server in a java class implementing the singleton pattern:
    public static ShoppingAssistant getInstance() {
        if (instance == null) {
            synchronized (ShoppingAssistant.class) {
                instance = new ShoppingAssistant();
        return instance;
    }1 Is there really a need for synchronizing the method?
    2 If you choose to synchronize it. Why not just synchronize the whole method?
    3 Is this method really thread safe? Is I see it a thread A could be preempted after checking the instance and seing that it is null. Thereafter another thread B could get to run, also see that instance is null and go on and create the instance. Thereafter B modifies some of the instance�s instance variables. After that B is preempted and A gets to run. A, thinking instance is null, goes on and create a new instance of the class and assigns it to instance, thus owerwriting the old instance and creating a faulty state.
    By altering the code like this I think that problem is solved although the code will probably run slower. Is that correct?
    public static ShoppingAssistant getInstance() {
        synchronized (ShoppingAssistant.class) {
            if (instance == null) {
                instance = new ShoppingAssistant();
    }Regards, Mattias

    public class Singleton {
    private static final instance = newSingleton();
    public static Singleton getInstance() {
    return instance;
    }This seems like it's so obviously the standard
    solution, why do
    people keep trying to give lazy solutions? Do they
    expect it to be
    more efficient that this?I can see one possible performance gains with a lazy solution:
    If you use something else in that class (besides getInstance()), but don't use getInstance, then you don't take the performance hit of instantiating the thing.
    Of course, this is dubious at best because how often do you have other static methods in your singleton class? And not use the instance? And have construction be so expensive that a single unnecessary one has a noticeably detrimental impact on your app's performance?

  • Thread safe doubt

    Hi every1
    My question:
    Multiple threads enter the method att()...i want to count how much time does attacher.attach() method takes for every thread that comes in...i think the code below works... but if i declared the timeTakenForAttach as global variable..someone told me its not thread safe...can some1 please explain me the meaning of all this OR can i declare timeTakenForAttach as global and it won't be a problem..
    class A{
      long totalAttachSetupMillis=0L;
      public void att() {
          long start = System.currentTimeMillis();
                   attacher.attach();
          long timeTakenForAttach = System.currentTimeMillis() - start;
           recordAttachSuccess (timeTakenForAttach);
       public synchronized void recordAttachSuccess(long timeForAttach){
                totalAttachSetupMillis += timeForAttach;
    }Thankyou..

    javanewbie83 wrote:
    I have to sychronize record sucess as different threads would enter att() and enter record success method and simultaneously update, so i will end up getting a wrong value.Let me give you a more detailed explanation of why NOT having it synchronized would not work.
    First of all, let's take a look at the statement of concern:
    totalAttachSetupMillis += timeForAttach;For the purposes of synchronization, however, we need to look at it like this:
    int temp = totalAttachSetupMillis + timeForAttach; //call this LINE A
    totalAttachSetupMillis = temp; //call this LINE BNow, lets say we had threads named 1 and 2. If you didn't sychronize the method, you could possibly have this execution flow:
    //initial values: totalAttachSetupMillis = 0, timeForAttack(1) = 20, timeForAttack(2) = 30.  Total should be 50
    1A //temp(1) = 0 + 20 = 20
    2A //temp(2) = 0 + 30 = 30 (remember totalAttachSetupMillis isn't set until B)
    2B //totalAttachSetupMillis = temp(2) = 30
    1B //totalAttachSetupMillis = temp(1) = 20 (instead of 50)In other words, total disaster could possibly ensue. Which is why you wanted to synchronize it. Ed's explanation of your other question was right on the money, though.

Maybe you are looking for