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 volatile so 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 when if (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 final fields) 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.)
A Handler is one good way to transfer messages and data from a communications worker thread to the UI thread.
It would be more ideal if you included the basic outline of your code in your question. However, I would assume that what you basically have is a custom View (which you refer to as your "drawing class") which forms part of an overall layout that's set as the content view for your Activity. I then assume you have a communications worker thread, which might be contained within that same Activity class (or perhaps in a separate Service class - but for now I'll assume the simplest case). For your communications worker thread to update your View, the View needs to be updated on the UI thread. Therefore you would instantiate a Handler object that will run on the UI thread (perhaps in onCreate()) which updates the View based on the content of messages. Your worker thread then sends messages to that Handler.
Related
I'm making a real time multiplayer game server in Java. I'm storing all data for matches in memory in a HashMap with "match" objects. Each match object contains information about the game and game state for all players (anywhere from 2-5 in one match). The server will pass the same match object for each user's connection to the server.
What I'm a little concerned about is making this thread safe. Connections could be made to different threads in the server, all of which need to access the same match.
The problem with that is there would be a lot of variables/lists in the object, all of which would need to be synchronized. Some of them may need to be used to perform calculations that affect each other, meaning I would need nested synchronized blocks, which I don't want.
Is synchronized blocks for every variable in the match object my only solution, or can I do something else?
I know SQLite has an in memory mode, but the problem I found was this:
Quote from their website:
SQLite supports an unlimited number of simultaneous readers, but it will only allow one writer at any instant in time. For many situations, this is not a problem. Writer queue up. Each application does its database work quickly and moves on, and no lock lasts for more than a few dozen milliseconds. But there are some applications that require more concurrency, and those applications may need to seek a different solution
A few dozen milliseconds? That's a long time. Would that be fast enough, or is there another in memory database that would be suited for real time games?
Your architecture is off in this case. You want a set of data to be modified and updated by several threads at once, which might be possible, but is extremely difficult to get right and fast at the same time.
It would be much easier if you change the architecture like follows:
There is one thread that has exclusive access to a single match object. A thread could handle multiple match objects, but a single match object will only be handled/guarded by a single thread. Now if any external effect wants to change any values, it needs to make a "change request", but cannot change it immediately on it's own. And once the change has been implemented and the values updated, the thread guarding the match object will send out an update to the clients.
So lets say a player scores a goal, then the client thread calls a function
void clientScoredGoal(Client client) {
actionQueue.put(new GoalScoredEvent(client));
}
Where actionQueue is i.E. a BlockingQueue.
The thread handling the match objects is listening on this queue via actionQueue.take() and reacts as soon as a new action has been found. It will then apply the change, updated internal values if neccessary, and then distributes an update package (a "change request" to clients if you want).
Also in general synchronized should be considered bad practice in Java. There are certain situations where it is a good way to handle synchronization, but in like 99% of all cases using features from the Concurrent package will be by far the better solution. Notice the complete lack of synchronized in the example code above, yet it is perfectly thread-safe.
the question is very generic. It is difficult to give specific advice.
I'm making a real time multiplayer game server in Java. I'm storing all data for matches in memory in a HashMap with "match" objects.
If you want to store "match" objects in a Map and then have multiple threads requesting/adding/removing objects from the map, then you have to use a "ConcurrentHashMap".
What I'm a little concerned about is making this thread safe. Connections could be made to different threads in the server, all of which need to access the same match.
The safest and easiest way to have multithreading is to make each "match" an immutable object, then there is no need to synchronize.
If "match" information is mutable and accessed simultaneously by many threads, then you will have to synchronize. But in this case, the "mutable state" is contained within a "match", so only the class "match" will need to use synchronization.
I would need nested synchronized blocks, which I don't want.
I haven't ever seen the need to have nested synchronized blocks. perhaps you should refactor your solution before you try to make it thread safe.
Is synchronized blocks for every variable in the match object my only solution, or can I do something else? I know SQLite has an in memory mode
If you have objects with mutable state that are accessed by multiple threads, then you need to make them thread safe. there is no other way (notice that I didn't say that "synchronized blocks" is the only option. there are different ways to achieve thread safety). Using an in memory database is not the solution to your thread safety problem.
The advantage of using an in memory database is in speeding up the access to information (as you don't have to access a regular database with information stored in an HDD), but with the penalty that now your application needs more RAM.
By the way, even faster than using an in memory database would be to keep all the information that you need within objects in your program (which has the same limitation of requiring more RAM).
I have a producer consumer like pattern where some threads are creating data and periodically passing putting chunks of that data to be consumed by some other threads.
Keeping the Java Memory Model in mind, how do i ensure that the data passed to the consumer thread has full 'visibility'?
I know there are data structures in java.util.concurrent like ConcurrentLinkedQueue that are built specifically for this, but I want to do this as low level as possible without utilizing those and have full transparency on what is going on under the covers to ensure the memory visibility part.
If you want "low level" then look into volatile and synchronized.
To transfer data, you need a field somewhere available to all threads. In your case it really needs to be some sort of collection to handle multiple entries. If you made the field final, referencing, say, a ConcurrentLinkedQueue, you'd pretty much be done. The field could be made public and everyone could see it, or you could make it available with a getter.
If you use an unsynchronized queue, you have more work to do, because you have to manually synchronize all access to it, which means you have to track down all usages; not easy when there's a getter method. Not only do you need to protect the queue from simultaneous access, you must make sure interdependent calls end up in the same synchronized block. For instance:
if (!queue.isEmpty()) obj = queue.remove();
If the whole thing is not synchronized, queue is perfectly capable of telling you it is not empty, then throwing a NoSuchElementException when you try to get the next element. (ConcurrentLinkedQueue's interface is specifically designed to let you do operations like this with one method call. Take a good look at it even if you don't want to use it.)
The simple solution is to wrap the queue in another object whose methods are carefully chosen and all synchronized. The wrapped class, even if it's LinkedList or ArrayList, will now act (if you do it right) like CLQ, and it can be freely released to the rest of the program.
So you would have what is really a global field with an immutable (final) reference to a wrapper class, which contains a LinkedList (for example) and has synchronized methods that use the LinkedList to store and access data. The wrapper class, like CLQ, would be thread-safe.
Some variants on this might be desirable. It might make sense to combine the wrapper with some other high-level class in your program. It might also make sense to create and make available instances of nested classes: perhaps one that only adds to the queue and one that only removes from it. (You couldn't do this with CLQ.)
A final note: having synchronized everything, the next step is to figure out how to unsynchronize (to keep threads from waiting too much) without breaking thread safety. Work really hard on this, and you'll end up rewriting ConcurrentLinkedQueue.
Consider a simple Android application: there are two TabActivities and a thread in the background getting integer values from a server. If the number is even, it must be displayed in the first tab otherwise in the second. Obviously I will be doing something more complicated, but this is the basic pattern. How do I go about doing this? I have been scratching my head for about a day now and here are things I have come across:
Use of EventHandlers. The two TabActivities register for listening for my_events and when a value is received by the thread, it 'throws my_event' and then specific methods in both these activites are called and the value is passed.
The use of Handlers.
I have not used both of these concepts before and I would like to know which might be the better/correct route to take. Further, any more tips along the chosen route will be appreciated. Also, should this thread be run from a service class?
When you create your thread just pass the objects of your tabs into it, then in your execution you can easily put the text you want into tabs.
Possibly you want to look at using an AysncTask. If you do this you want to insert the values into the appropriate tab in the onProgressUpdate() method. Since the arguments passed to this method may not actually be able to represent the incoming data sufficiently you'll just want to put the new data somewhere that it can be accessed from the onProgressUpdate() method, probably in a member variable. Keep in mind that access to this member variable probably needs to be synchronized because code in onProgressUpdate is running on the application's main thread, while code in doInBackground is running on a background thread so code in these methods will be running concurrently.
AsyncTask uses Handlers transparently for you, but you could use raw Handlers if you wanted. The basic things you need to keep in mind are
You can/should only update the UI from the main application thread
Code in a Handler will always run on the Thread that created the Handler
Handlers must be created on a Thread that has a Looper (the main Thread has a Looper)
Be careful if creating the Handler as an anonymous inner class or handing it a reference to a Context since this creates the potential for a memory leak
Possibly the Thread should be invoked by a Service, but if the Thread only needs to exist when there is a UI for it to update there may be little point to this.
I have two threads. One thread has an instance of myObjectManager. myObjectManager has a list of objects, and a method for retrieving an object( public myObjectClass getObjectById(int ID) )
I need the first thread to render an object in myObjectManagers list of objects, and the second thread to perform game logic and move it around etc.
This is what I tried
//thread 1:
m = myObjectManager.getObjectById(100);
m.render();
//thread 2:
m = myObjectManager.getObjectById(100);
m.rotate( m.getRotation() + 5 ); //increment rotation value
However, it seems that thread 1 has an instance of the object without the updated rotation. When I run it, the rendered object doesn't rotate, but when I make the second thread print out the rotation value it is rotated.
In C++ I would just make the function getObjectById() return a pointer to an instance of myObjectClass, but I'm not sure what exactly java does when I say "return myInstance;"
How would I do something similar in java?
Sorry, I'm new to this language!
In Java, all Object variables are "pointers" (or "references", as people typically say). The problem must be elsewhere. My guess is that thread 1 has already rendered the object before thread 2 has even modified it.
Edit: Another theory: subsequent render() operations don't actually change the screen display. The rotation value is updated just fine - but it doesn't reflect to the display.
The references (pointers) are alright but in Java each thread is allowed to make local copies of objects (think of it like a cache) they're working with and unless they are synchronized in some way, changes made by one thread may not be visible to the other.
This tutorial will hopefully help.
You have 2 potential problems, both of which have been stated here in different answers.
You give no indication as to any
control of ordering of your thread
operations. Therefore the render
may be occurring before the rotation
update. This assumes that the the
classes involved are in fact
threadsafe and will behave as
expected.
If the classes are not
threadsafe (i.e. synchronized in
some way), then the updates to the
rotation thread may never be seen in
the rendering thread.
To know for sure we would have to see the source for the m class. Also, you may have issues with the getObjectById() as well if it is not threadsafe either.
Try marking your rotation variable in the object as volatile
All objects in Java are passed by reference.
It is impossible to write code that does what you're trying not to do.
Your first thread is probably running before the second thread.
All object references in Java, like your m variable, are in fact pointers.
So in your example, both m variables point to the same object.
With reference to the java.util.concurrent package and the Future interface I notice (unless I am mistaken) that the ability to start a lengthy tasks and be able to query on the progress only comes with the SwingWorker implementing class.
This begs the following question:
Is there a way, in a non-GUI, non-Swing application (imaging a console application) to start a lengthy task in the background and allow the other threads to inspect the progress ? It seems to me that there is no reason why this capability should be limited to swing / GUI applications. Otherwise, the only available option, the way I see it, is to go through ExecutorService::submit which returns a Future object. However, the base Future interface does not allow monitoring the progress.
Obviously, the Future object would only be good for blocking and then receiving the result.
The Runnable or Callable object that you submit would either have to know how to provide this progress (percentage complete, count of attempts, status (enum?) etc) and provide that as an API call to the object itself, or posted in some lookup resource (in memory map or database if necessary). For simplicity I tend to like the object itself, especially since you're going to most likely need a handle (id) to lookup the object or a reference to the object itself.
This does mean that you have 3 threads operating. 1 for the actual work, 1 that is blocked while waiting for the result, and 1 that is a monitoring thread. The last one could be shared depending on your requirements.
In my case I passed a HashSet, with the Objects to process, as Parameter to the Method, wich was created as instance variable in the calling Class. When the asyncronous method removes the Objects after processing one can retrieve the size of the Map remaining in the calling Method. I thing in general passing Objects by Reference solves the Problem.
I was hoping that there was a standard concurrency framework way to stay updated on the progress of a long running task without requiring the client program to worry about orchestrating and synchronizing everything correctly. It seemed to me to that one could fathom an extended version of the Future<T> interface that would support:
public short progress(); in addition to the usual isDone() and get() methods.
Obviously the implementation of the progress() would then need to poll the object directly so maybe Future<T> would need to be specified as Future<T extends CanReportProgress> where CanReportProgress is the following interface:
public interface CanReportProgress {
public short progress();
}
This begs the question of why one would bother to go through the Future object as opposed to calling the object itself to get the progress. I don't know. I'll have to give it more thought. It could be argued that it is closer to the current contract / semantics whereby the Callable object is not, itself, accessed again by the client programmer after the call to ExecutorService::submit / execute.