I have an interesting question if someone can help me to think up a solution.
I spawn 2 separate processes, A and B. Think them as a Queue waiting for work
A is being filled and do something
A is done and pass onto B
B do something and finish
How do I detect where in the process we are in using Java? And how I would stop this process where ever we are at?
Thanks!
In pure Java, you would have memory variables that are accessed by both threads, so they can communicate. You would need to make them synchronized or use semaphores to make sure only one thread at a time is modifying the information in the variable.
Other languages have the concept of actors, which implement more robust inter-thread communication by passing messages. Look into Scala - it's built on top of Java. Or the akka library, which has Scala and Java versions.
If you like thinking about this stuff, try the book Seven Languages in Seven Weeks by the Pragmatic Programmers.
you can add a currentStage variable and update stage at different locations in your code. Also save your "registers". By this I mean save your local variables that you care about. Serialize objects and perhaps place them in a database.
Then if you quit and restart, you go to the last saved stage and restore the corresponding objects from the database.
To follow the process you would need another Thread (C) that can read status information outputted by A & B and that can be asked by A & B if they should continue.
For instance, create a ProcessFollower interface with 2 methods:
void updateStatus (String)
boolean shouldStop ()
C can implement this interface and pass itself when calling A, A passed the reference to ProcessFollower (C) to B. Each time the status changes A and B call updateStatus and on each occasion (e.g. each loop iteration) they check shouldStop(); if false they simply return or such.
Related
First I'll explain what I want to do and afterwords I'll provide a proposed solution.
Problem
I'm running a game where I want to do a certain amount of work every frame. For example, I have N objects that are in a queue waiting to be initialized (imagine initialization is a fairly expensive operation and N is large) and after adding them all, I want to create their collision boxes, and after that, I want to merge them together to limit render calls. I can't do these operations on a different thread because all this stuff is heavily coupled with the game world. But I want to split up all these operations into bite-size chunks to run each frame so that there is minimal lag (framerate dips). How would I go about doing this?
Proposed Solution
It would be nice to have a function that can stop after one call and continue where it left off after calling it again:
For example,
boolean loadEverything() {
for (int i = 0; i < objectsToAdd.length; i++) {
world.add(objectsToAdd[i]);
if (i % 10 == 0) {
return stop();
}
}
makeCollision();
return stop();
mergeObjects();
return true;
}
Calling loadEverything() the first objectsToAdd/10 times adds 10 objects to the game world at a time. Then calling it after should run makeCollision() and then stop. Calling it again runs mergeObjects() and then the function returns true. In the caller function I would run loadEverything() until it returns true.
I'm aware of yeild-return, yield-break implementations like those described here exist, but I'm wondering if there's a more general implementation of them, or that maybe a better solution exists that doesn't require any extra dependencies.
Do you look at Coroutine yet? There's native implementation in Kotlin but in Java there're options here and here.
By all means we need to make sure those OpenGL or Box2D operations that required to be in main thread should be in main thread, as I believe coroutine will be created under a new thread. So there might not be gain to split works for those kind of operations.
Another option
You say you need to split works in creating objects in run time. Can you predict or estimate the number of objects you would want before hand? and so if you don't really need to dynamically create object like that, I suggest to look at Object Pool in libgdx (see more here). That link has working example to use Pool in your game.
Such Pool already have initialized objects ready to be grabbed and used on-demand, also can grow if need in run time, so initially if you can provide a good estimation of number of objects you intend to use, it's all good.
Why don't you add one static variable which would keep it's value between function calls? Then you can loop from current value to current value + 10, increase current value (that static variable) by 10 and exit.
I read about how methods are executed and this is what I understand:
1) Methods are allocated memory in method area and only a single copy is maintained which is used across all the instances of the class.
2) When a method is called from an instance then the current thread(single threaded env) say main gets loaded and then stack is loaded with the method being called via instance.eg:
main(String ags[])
{
A a = new A();
a.method();
}
// code of method
method()
{
for(int i=0;i<25;i++)
system.out.println(i);
}
so for this thread it has its own call stack and then on method call same method body with its local variables gets pushed onto the same stack above main method.
Now based on above understanding, what I dont understand is that in multi threaded environment how the same code will behave if I run two threads
and both share the same instance. eg:
//My run method for myRunnable
run()
{
a.method();
}
Thread one = new Thread(new myRunnable(a)); // object from above
Thread two= new Thread(new myRunnable(a));
Now when the two threads start executing they will have there own call stack.
How will the method of the shared object execute in this case?.
Thanks
1) Methods are allocated memory in method area and only a single copy is maintained which is used across all the instances of the class >> that means that the bytecode of method implementation is only one per all instances. And method bytecode memory region is separated from the object's heap.
Each thread has its own stack of course, just like you explain it.
If you have multiple threads running the same method on the same object concurrently, you have the following situation:
local variables are stored on each thread's stack. They are not shared and do not conflict.
The object instance (this) is stored on the heap, as well as all its fields (such as this.foo). The heap is shared. To ensure that this works properly, you have to apply thread synchronization mechanisms as appropriate.
static fields are also shared and access must be coordinated, too
In your example, the i in the loop is a local variable. Both threads will print all of the numbers in sequence (but the output of the two threads is interleaved in an undefined order).
OK, you walk into a room.
Somebody hands you a clipboard and a pencil and a whiteboard marker, and then
tells you to start following the instructions that are written on a certain
poster on the wall.
There's a whiteboard on another wall: It looks like a spreadsheet with rows
and columns, and numbers and words written in the cells. Your clipboard has a
sheet of paper with more rows and columns, and some numbers are written in
some of the cells in pencil.
The instructions tell you, step-by-step, how to perform some complex
calculation. They say things like,
...
Step 37: Copy the number from B5 on the whiteboard into J2 on your
clipboard.
Step 38: Add J2 through J7 on your clipboard, and write the result in J9.
Step 39: If the result in J9 is greater than the value in whiteboard-C9,
then go back to step 22, otherwise, go on to step 40.
Step 40: Erase whiteboard-C9, and then copy the value from clipboard-J9
into that location.
...
There's a space on your clipboard where you can write your own notes. You can
use it, for example, to keep track of what step you're on, or whatever else
you need to remember in order to get the job done.
There are other posters on the wall, and there are other people, each with
his/her own clipboard. Some of the people are following instructions from the
same poster as you, and some of them are reading from other posters.
Everybody is reading from/writing to the same whiteboard.
Everybody is going at her/his own pace. The ones who are reading the same
poster as you are not necessarily on the same step as you, and because each of
you had different initial numbers written on your clipboards, you may not even
be performing the instructions in the same sequence.
This is a simplistic model of multi-threaded computing: The posters on the
wall are the methods, The whiteboard is the heap, the people are threads, and
your clipboards are your stacks.
It's also, roughly similar to how scientific/engineering calculations were
done during the industrial age. The people who did that kind of work were
called "computers".
If you're coordinating the whole thing, and it's time to add a new "thread" (i.e., when a new volunteer walks into the room), then you'll need to give that person his/her own clipboard (stack), with its own initial values (parameters), but you don't give the new person her/his own poster (methods): You just point her/him at one of the posters that already is up on the wall.
I'm making a series of connections asynchronously via MySQL, and I have a class which contains a bunch of easy-accesible static methods to update/remove/clear/get/etc data.
The issue I'm confronted with is that the getter methods won't return the proper value (practically ever) because they are returned before the async connection gets a chance to update the value to be returned.
Example:
public static int getSomething(final UUID user)
{
Connection c = StatsMain.getInstance().getSQL().getConnection();
PreparedStatement ps;
try
{
ps = c.prepareStatement("select something from stats where uuid=?");
ps.setString(1, user.toString());
ResultSet result = ps.executeQuery();
return result.getInt("something");
}
catch (SQLException e)
{
return false;
}
}
(Not copy & pasted, but pretty close)
I realize I can use a 'callback' effect by passing an interface to the method and doing such, but that becomes very tedious when the database stores 10 values for a key.
Sounds like you're looking for Futures since Java 6 or CompletableFuture, which is new in Java 8
Solution 1:
The best method I've come up with is have a thread with a loop in it that waits for MySQL to return values and responds to each value. This is rather like the callback in the get routine, but you only have the one loop. Of course, the loop has to know what to do with each possible returned piece of data.
This means rethinking a bit how your program works. Instead of: ask a question, get an answer, use the answer, you have two completely independent operations. The first is: ask a question, then forget about it. The second is: get an answer, then, knowing nothing about the question, use the answer. It's a completely different approach, and you need to get your head around it before using it.
(One possible further advantage of this approach is that MySQL end can now send data without being prompted. You have the option of feeding changes made by another user to your user in real time.)
Solution 2:
My other solution is simpler in some ways, but it can have you firing off lots of threads. Just have your getSomething method block until it has the answer and returns. To keep your program from hanging, just put the whole block of code that calls the method in its own thread.
Hybrid:
You can use both solutions together. The first one makes for cleaner code, but the second lets you answer a specific question when you get the reply. (If you get a "Customer Name" from the DB, and you have a dozen fields it could go in, it might help to know that you did ask for this field specifically, and that you asked because the user pushed a button to put the value in a specific text box on the screen.)
Lastly:
You can avoid a lot of multithreading headaches by using InvokeLater to put all changes to your data structures on your EventQueue. This can nicely limit the synchronization problems. (On the other hand, having 20 or 30 threads going at once can make good use of all your computer's cores, if you like to live dangerously.)
You may want to stick with synchronized calls, but if you do want to go asynchronous, this is how I'd do it. It's not too bad once you get some basic tools written and get your brain to stop thinking synchronously.
I am making a 2 player videogame, and the oponent's position gets updated on a thread, because it has a socket that is continuously listening. What I want to share is position and rotation.
As it is a videogame I don't want the main thread to be blocked (or be just the minimum time possible) and I don't want the performance to be affected. So from what I've seen to share this info the normal thing to do would be something like
class sharedinfo
{
public synchronized read();
public synchronized write();
}
but this would block the read in the main thread (the same that draws the videogame) until the three values (or even more info in the future are written) are written, and also I've read that synchronized is very expensive (also it is important to say this game is for android also, so performance is very important).
But I was thinking that maybe having sharedInfo inside an AtomicReference and eliminating synchronized would make it more efficient, because it would only stop when the reference itself is being updated (the write would not exist, I would create a new object and put it on the atomicreference), also they say that atomic* use hardware operations and are more efficient than synchronized.
What do you think?
Consider using a queue for this, Java has some nice concurrent queue implementations. Look up the BlockingQueue interface in java.util.concurrent, and who implements it. Chances are you fill find strategies implemented that you hadn't even considered.
Before you know it, you will want to communicate more than just positions between your threads, and with a queue you can stick different type of objects in there, maybe at different priorities, etc.
If in your code you use Interfaces (like Queue or BlockingQueue) as much as possible (i.e. anywhere but the place where the specific instance is constructed), it is really easy to swap out what exact type of Queue you are using, if you need different functionality, or just want to play around.
The easiest implementation is when we call from single class main method other classes implementing runnable:
public static void main(String [] args){
// declarations ...
receiver.start();
player.start();
}
Say inside receiver I have while loop which receives a packet value and I want to send that value to the second thread. How to do that?
Just to clarify I don't yet care about one thread controlling another, I just want first thread to share values with second.
And tiny question aside - does JDK 7 Fork really dramatically increases performance for java concurrent api?
Thank You For Your Time,
A simple option is to use a java.util.concurrent.atomic.AtomicReference (or one of the other Atomic... classes). Create a single instance of AtomicReference, and pass it to the code that the various threads run, and set the value from the receiver thread. The other thread(s) can then read the value at their leisure, in a thread-safe manner.
does JDK 7 Fork really dramatically increases performance for java concurrent api?
No, it's just a new API to make some things easier. It's not there to make things faster.
The java.util.concurrent -package contains many helpful interfaces and classes for safely communicating between threads. I'm not sure I understand your use-case here, but if your player (producer) is supposed to pass tasks to the receiver (consumer), you could for example use a BlockingQueue -implementation.