The following short code can help demonstrate my problem:
In the implementation of the Red call there is memory allocation at the begining:
out = new DataOutputStream (Socket.getOutputStream ());
Blue function implementation includes writing into thread.out:
something like:
out.writeInt(...);
implemented in run function of course.
I thought that because I has started the thread with the allocation right on the begining (red) and before reaching the blue command in which the write to out is taking place,
the program will work correctly, but I got a NullPointerException because for some reason the allocation in the red happed after trying to write on out which has null before allocation.
somebody told me that with the running of some threads simultaneous ,you can never know what part of code of which thread will come first.
what i did to resolve the exception was adding the same allocation to the function in blue.
then it was working
1. If I can't guess what comes before , how I decide where to perform the actual allocation, when the two places in code need to write to the same variable.
2. Is there other way to solve this kind of problems, i don't feel it was a good solution.
3. Do you think I need to use synchronize command to prevent both places( red and blue) to write at the same time to the same variable, or it can never happend?
{color:#ff0000}{color:#000000}I really don't get all this points.
{color}
{color:#000000}
{color}
Thread.start ();{color}
if (WaitingThread == null) / / checking if the current thread is the first which connected the to server
(
WaitingThread = thread;
{color:#000080}Thread.askToFillUpParameters ();{color}
)
...