简体   繁体   中英

Concurrent access of String variable in java

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM