Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Question about running two threads which need to write on the same output

807580Mar 14 2010 — edited Mar 14 2010
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} 
)
...
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 11 2010
Added on Mar 14 2010
2 comments
114 views