Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java multithreading and global variables

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();
            }

      }
  }
like image 791
lulu88 Avatar asked May 29 '13 08:05

lulu88


2 Answers

If I understand correctly, you should probably look at the final modifier:

private final String s;

This ensures that s cannot be modified, thus your threads won't be able to change its value.

Also make sure that your threads do not attempt to modify values they shoudl not, copy them instead.

like image 160
Djon Avatar answered Oct 21 '22 03:10

Djon


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.

like image 38
koljaTM Avatar answered Oct 21 '22 05:10

koljaTM