Multithreading java, variable count not matching, use of callable and runnable

  Kiến thức lập trình

Below is the sample code, the count value is not matching sometimes when x.var value is “menu” and I am appending value of count in my data. In most of the cases the value is same, but sometimes the value seems to be mismatching. Is there any issue with code

public class FileCreator implements Runnable
{
  List<FileWriter>l;

  method1(){
   l.parallelStream()
                .forEach(x -> x.addData("record_type", null, msg));
   // create object of type filewriter and add to list 
   }

 

}

public class FileWriter implements Callable<Void> 
{
 private final BlockingQueue<WriterData> queue = new LinkedBlockingQueue<>();
 private final OutputCreator outputcreator;
  addData(RecordType a,A b,Message c))
   {
     queue.add(new writerData(a,b,c));
    }
   void call()
   {
      // takes data from queue and process it. basically writes to the output file 
      outputcreator.create(x);//where x is obtained from queue 
      
    }
}

public void OutputCreator{
  StringWriter w = new StringWriter();
  BeanWriter beanWriter = factory.createWriter("XYZ", w);
  private AtomicInteger count = new AtomicInteger(1);
  void create(D x)
  {
    count++;
    if(x.var=="menu")
      x.data+=String.valueOf(count); 
    write(x.data);
  }
  string update(string data)
 {
   data+=String.valueOf(count);
 }

}


// the write method is overloaded like this in its respective class
write(Data d)
{
 putinfile(update(d));
 
}

The count value should be same when I am appending it to data 2 times when x.var==”menu”

LEAVE A COMMENT