1

If multiple threads are triggered does String variable (status) need to be synchronized?

class Request{
  String status;
  ....// Some other variables used in thread
}

class Test{

      public static void main(String[] args){
      Requesr r = new Request();
      List<Future> list= new ArrayList<Future>();
      ExecutorService pool= Executors.newFixedThreadPool(10);
       for(String input : inputList){
         if(!"failed."equals(r.status)){
           RequestHandler request = new RequestHandler(input,r);
           Future f = pool.submit(request);
           list.add(f);
         }else{
            //fail the job and return;
        }
      }
    for (Future fTemp : list) {
       if (fTemp.get() == null) {
          // Task completed
        }
     }
   }
 }

class RequestHandler extends Runnable{
         Map<String,String> input;
         Requesr r;
         RequestHandler(Map<String,String> input, Request r ){
           this.input=input;
           this.r = r;
         }
        @Override
         public void run() {
         if(!"failed".equals(r.status)){
           try{
             //some logic
           }catch(Exception e){
             r.Status = "failed";//status is assigned a value only here
           }
         }
       }
    }

Does status need to be synchronized for it to be visible in the Test class for loop and in other threads? As mentioned below in comments I will use Future objects and cancel the running threads.

My doubt is whether above code works without synchronization logic. If it doesn't how can we add synchronization logic in this case?

12
  • Please, show how you start your thread. Given the code above you might never see status value changed if you start your thread after the for loop or even before it with or without using synchronization. Commented Dec 26, 2017 at 19:47
  • 1
    A variable is never synchronized. The code you posted wouldn't compile, so it's basically impossible to answer the question. Post code that compiles and runs. Commented Dec 26, 2017 at 19:47
  • Is there a good reason not to use an ExecutorService here, and just cancel the outstanding futures when you encounter an error? Commented Dec 26, 2017 at 20:03
  • related questions: stackoverflow.com/questions/4756536/… stackoverflow.com/questions/5307003/…, stackoverflow.com/questions/15196355/… Commented Dec 27, 2017 at 2:06
  • This code doesn't make sense. Why would you expect the status to be updated before you've finished submitting the tasks? Commented Dec 27, 2017 at 3:10

1 Answer 1

0

The variable should probably be declared volatile. Else it may happen that a thread updates the value to "failed", but the main thread never sees this update. The reasons are explained here: http://etutorials.org/Programming/Java+performance+tuning/Chapter+10.+Threading/10.6+Atomic+Access+and+Assignment/

It's possible (depending on what the triggering code does) that this is unnecessary, but it's not worth taking the risk.

Sign up to request clarification or add additional context in comments.

4 Comments

Read a little further: Note that I'm talking about using synchronization for thread-safety here, not synchronization for visibility of updates and accesses of variables. That's very possibly an issue here.
Sure. If one of the threads sets status = "failed", there's no guarantee the main thread will see the update without some form of synchronization.
I will set status to volatile. Do I need synchronization for getter setter methods. volatile String status; public void setStatus(String status){ this.status = status } public String getStatus(){ return status; }
According to the linked article using volatile should be enough, no need to add synchronized anywhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.