Currently I have an object which I receive from a server, this contains two co-ordinates to be drawn to a canvas, which I can currently do in another class with hard coded co-ordinates.
My problem is that I cannot work out how to send the object (which is within a thread) to the second drawing class to be drawn.
An object is never within a thread. The best you can hope for is that only one thread references the object, and constant vigilance is required to keep it that way. Objects accessed by only one thread do not require anywhere near the thought and care that objects accessed by more than one thread do. But it’s real hard to keep objects on one thread, and you can’t do that here in any case.
Your object from the server can be referenced from a public, static field in any class, and so be made available anywhere in your program (and to any thread). There has to be a more elegant way to make it available where needed–to encapsulate it properly–but this will do as a fallback solution.
Then you have to take care of multi-threaded access. It sounds like your object can be made immutable. This just means that once you make it “public” by assigning it to it’s referencing field, you never change it again (even if it is theoretically possible to do so). This makes things simpler and faster. Create your received object and, when it is fully assembled, place it in its field. Make sure that field is marked
volatileso any changes will be immediately seen elsewhere.Now your drawing class merely needs to look at the object when it needs it. However, before using it you want to copy the object to a local variable. The local variable will continue to point to the same object throughout the drawing process. The volatile field may change at any instant, continually refering to new or different objects. Using the local variable, your X and Y coordinates will always be consistent, if out-of-date. (Everything’s a bit out-of-date in a multi-threading system.) If you used the field, you could get the X from one object sent from the server and the Y from another. (The real fun with multi-threading comes when
X * X, where the X is an integer, gives a value of 35–same X from two different objects. That and whenif (aA != null) aA.doSomething()throws a null pointer exception. Using local variables prevents all this.)For now I think you can avoid synchronization and wait states. You might want to make your coordinate object truly immutable (with
finalfields) so other programmers (or even you after 6 months of doing other work) don’t change the code to modify the object on the fly. (If they/you do, they/you will need synchronization.)