2

I'm working on a TCP socket right now. I derive my server class from Thread.

public class TCPServer extends Thread {

  public static int SERVERPORT = 54321;
....
<code>
}

When I use this class, it will open several threads. My question is, does each thread have its own static variable SERVERPORT? Because it seems like if I edit this variable, it does not have effect in others.

My solution to this problem would be to create another class, say "GlobalVariables" and give this class access to it.

Guntram
  • 414
  • 2
  • 5
  • 18
  • If you want each thread to have its own instance of a variable consider `ThreadLocal`: http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html. Note that deriving from `Thread` is not considered optimal - http://stackoverflow.com/questions/541487/implements-runnable-vs-extends-thread – Steve Townsend Mar 14 '13 at 13:21

1 Answers1

6

My question is, does each thread have its own static variable SERVERPORT?

No, it does not. The variable is shared by all threads in the process.

I missed removing the final :D The variable I have is of type static boolean

Even though the variable is shared, when you modify it in one thread, the change won't necessarily become visible to other threads until some later, unspecified, time.

You need to take steps to ensure visibility. Depending on what your code is doing, this can include:

  1. explicit synchronization;
  2. using a volatile boolean;
  3. using AtomicBoolean.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Yes, you are right @NPE, this is just an example and I missed removing the final :D The variable I have is of type static boolean But your reply was the answer to my question anyway, therefore thank you :) – Guntram Mar 14 '13 at 11:57
  • It turned out that it was another problem! I was implementing your code and it all seemed to work well, still it didn't work out! But now I was able to track down the problem which occured in my socket... But that's another issue I guess! Anyway, thanks for helping me out! – Guntram Mar 14 '13 at 17:39