0

I have two Objects that implement the Runnable interface.

Lets say i have Thread_1 and Thread_2 objects.

Thread_1 has global variable myVariable; and method myMethod() which uses the myVariable variable.

Thread_2 has variable of type Thread_1

So here is the scenario:

Both threads: Thread_1 and Thread_2 are running.

if Thread_1 is currently using myMethod() (which uses myVariable) and at the same time Thread_2 is using Thread_1's myVariable throught Thread_1 (without calling the myMethod() method ) should i synchronize the myVaribale variable or not?

Joro Seksa
  • 1,525
  • 3
  • 18
  • 44

4 Answers4

1

You should synchronize if use means writing to memory. You may want to consider atomics, too.

Also, you should not put your variables and methods in Threads. Subsclass Thread only if you want to add thread-specific features and leave the rest to Runnables or any other classes that compose your system.

Ralf H
  • 1,392
  • 1
  • 9
  • 17
1

if Thread_1 is currently using myMethod() (which uses myVariable) and at the same time Thread_2 is using Thread_1's myVariable --> so they both use it? One directly and one through a method?

In this case the variable is shared among threads, you need to make sure that reads/writes occur atomic. Either make is volatile, or make an AtomicXXX class of it, or use explicit locks.

P.S. One thread is a member of another Thread? Interesting design

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • 3
    @JoroSeksa it would probably make more sense if you told us WHAT are you trying to do. – Eugene Apr 19 '13 at 13:15
  • I am developing message exchange system but in my case i send and receive messages throught defferent objects. One of the objects is Client socket and the other one is a Server Socket. The server socket uses the client socket to send periodical pings:) – Joro Seksa Apr 19 '13 at 13:18
1

"should i synchronize the myVaribale variable or not?"

It realy depends on what are trying to archive with your code and the type of the variable (if its a class or a primitive type). Synchronization must be threat as a local and especific problem, most of the time you dont have a standard procedure to use.

What I can tell you is that this global variable, myVariable, should be volatile, to ensure that both threads can see all modifications.

Jose Renato
  • 705
  • 5
  • 18
0

It doesn't matter how you are accessing myVariable. As long as you are accessing it(any variable) from more than one thread you have to make sure its thread safe,simple. You can use volatile, AtomicReference, lock or synchronize, any of these approach based on what you are trying to achieve.

Mak
  • 596
  • 5
  • 10