Monday, November 25, 2013

I have a Java class that starts up 2 separate threads. The first thread starts up fine and all the variables are correct.
When I start the second thread the global variables from thread one changes to the values set in thread 2.
I have tried adding synchronized blocks where the global variables are updated, but this did not work.
Is there a way to solve this issue? I want each thread to start up and use its own values without interference in other thread values.
EDIT:
Snippet of my Thread class:
  public abstract class ConsumerIF implements Runnable {

      public static Element root = null;
      public static String name = null;
      public static String type = null;
      public static String location = null;

      public final synchronized void reconfigure() throws FatalDistributionException {


            Document doc = builder.build(new StringReader(xmlCollector));
            root = doc.getRootElement();
            Element nameElement = root.getChild("name");
            Element typeElement = root.getChild("type");
            Element locationElement = root.getChild("location");
            Element scheduleElement = root.getChild("schedule");

            if (nameElement != null && typeElement != null && locationElement != null){
                name = nameElement.getTextTrim();
                type = typeElement.getTextTrim();
                location = locationElement.getTextTrim();
            }

      }
  }
share|improve this question
2 
i. e. remove any static that you may have used –  no_answer_not_upvoted May 29 at 8:18
1 
Pasting your code would be helpful –  Mifeet May 29 at 8:19
1 
Static variables are shared between all instances of your 'ConsumerIF ' –  Robe Elckers May 29 at 8:28
add comment

5 Answers

Static variables are shared between all Threads, thats what makes them static. If you want to use different values, either use ThreadLocals or (much better), use different objects with non-static variables in the differrent threads. Without further code it's difficult to say more though.
share|improve this answer
 
Thank you! I removed all static variables and it worked :) –  lulu88 May 29 at 8:46
add comment
Synchronisation merely controls the threads' access to the shared state.
If you want separate state per thread then you need to either declare different instances of that information (e.g. classes) per thread. e.g. simply instantiate a new object in each Thread's run()method, or perform a copy of the structure in question (e.g. a deep copy of a collection)
An alternative is to investigate ThreadLocal, in which each Thread will have a different copy of a nominated resource.
share|improve this answer
add comment

No comments: