Java concurrency - marbles moving around a circle - java

Let's imagine a simple Java program, where there are 5 2D marbles moving around in a circle in a fixed order. You can control the speed of every marble keeping in mind that slower marble is blocking the marble moving faster (they can't overtake). They all move in one direction in a circle. What would be the best way to program this? The idea is to assign a separate thread to every marble, that's actually one of the requirements.
Then I create five threads, synchronize the "move" method on some object common to all threads. The next step is checking whether I can move the marble forward, if there is some free space. So before I move, I check if there is free space and then take action. Is it necessary or at least a good idea to use wait() and notify() mechanism here?
Thanks for help.

Well, I'm not going to code your homework for you, but here is a high level look at it.
You will need each marble to update it's position at regular intervals, so some type of looping is required. This loop is commonly known as a game loop. Here is a discussion of various types of them, going from simple to complex. http://www.java-gaming.org/index.php?topic=24220.0 For your project, something simply may be sufficient, but I don't know the requirements of it.
Each time a marble tries to move, it must check to make sure it isn't being blocked. If you have the move method synchronized, as you mentioned, then only one marble should be able to move at a time, so that should avoid concurrency issues.
Except for using a Thread.sleep in your game loops, I don't see any reason for you to doing any waiting. Java has a synchronize keyword, which can be used to lock the shared object that you mentioned using for movement, to avoid the concurrency issues. So I don't believe wait and notify are necessary.
Just my thoughts, I hope it is of some help.

Related

Each action in a thread happens-before every action in that thread that comes later in the program's order

The first bullet point of Memory Consistency Properties is:
Each action in a thread happens-before every action in that thread that comes later in the program's order.
I guess this is a relatively recent addition to Java memory model because Jon Skeet didn't mention it in 2011.
What exactly does this bullet point mean in practice? I'm having a hard time making sense of it. Does it simply mean "There are no concurrency issues within a single thread"? Or is there more to it?
What exactly does this bullet point mean in practice?
Everything in a thread notionally occurs in the order the program executes (in reality it, instructions can be reordered to make the program run faster)
I'm having a hard time making sense of it.
Most likely you are over thinking it. Imagine you are reading the lyrics of a song. The words in each line happen after all the words before it, and all the words after that line happen after it.
Does it simply mean "There are no concurrency issues within a single thread"?
Yes, there shouldn't but there can be. e.g. The Spectre and Meltdown security issue exploited this.

Why not use a scheduledExcecutor for a game loop

I'm currently reading about game development, every time I see a game loop implemented it is always the same way.
A while(true) block, with a sleep inside for the FPS.
And I'm asking myself, why shouldn't I use a scheduledExcecutor, it seems like the obvious choice?
I mean, I'm sure I'm wrong here, it's unlikely that I'm the first one to think of this, but WHY not ?
First of all, look at some of the evolution of the traditional game loop. Your while(true) + sleep example is the simplest one.
Then people noticed that games were affected by the speed of the computer they were running on. Look up "variable time step game loop" on Google, for examples of how this is dealt with.
Now read over the docs on the ScheduledExecutorService. Neither scheduleAtFixedRate nor scheduleWithFixedDelay are quite what you'd want for a game.
Also, scrolling down in the docs, you'll notice "If any execution of the task encounters an exception, subsequent executions are suppressed." This can cause your game loop to abruptly terminate if you don't handle every possible exception.
There's nothing to stop you from extending the ScheduledExecutorService and modifying it to suit your needs, but I wouldn't recommend it as-is.
The main reason is probably simply that most of the code you are reading was coded before (or following patterns that were coded before) the concurrent package came out/was in heavy use.
A secondary might be trust. When you are coding something that critical to your app you want to be sure exactly how it behaves. The while(true) loop makes it very clear exactly what's going on... You'd have to spend some time dealing with the various executors before you became truly comfortable with one.
There should be a solution that solves your problem, I'm sure you can find something that fires regularly, and has an adjustment in case one iteration takes a little longer than expected.
You may even want to build your own executor. The pattern itself is fine, it's just finding a way to make it work for you.

Grouping animations for sequential execution

I have a Swing program that executes 2D animations using Swing Timers. With each button click there are several timers created to animate several different components - some of them moving off the screen and others moving on. (I do not know ahead of time what animations will need to be executed with each button click, but it isnt a problem to distinguish between the two "types" of animations at runtime - they're initiated from different methods, and thus its easy to imagine adding them to two different "queues" - a queue of outgoing items and a queue of incoming items. Having done so, I could then implement the basic strategy of calling a
That said - that all only makes sense to me intuitively, heuristically - I haven't figured out how to implement it in practice. What would those "queues" actually be, and what class would hold and later execute them?? Presumably one that implements Runnable, creating a second thread that can execute the animations with tighter control on how they proceed? Or does the event-dispatch thread give me the ample control here: Is there a way to use SwingUtilities.invokeAndWait() (or something like it) to collect all the animations to be performed, while assigning priority to those of a certain class, or that are marked in a certain way?
I would suggest taking a look at the design of some of the existing animation engines like:
The Timing Framework
Trident
The Universal Tween Engine and AurelienRibon / sliding-layout which uses the Tween Engine.
Generally what these engines tend to do is have a central "clock" which ticks at a regular interval. They then provide callback functionality to notify interested parties that a "tick" has occured.
They then offer a series of layers on top of this concept to make it easier to interact with, such as providing a time range for animations, presented as a percentage over time (rather than a physical time measurement), which can be used to calculate fractions of change.
The also provide interpolation, allowing you to affect the speed of the animation through the time cycle (such as slow in, fast out effects).
This approach reduces the overhead of having to have multiple Timers running, which may reduce the performance over time while, providing a separation model, so each "animation" is it's own entity.
Personally, I'd evaluate each one and see which best meets your needs and run with, but if you really want to do it yourself, they provide a good starting point for ideas and designs

Thread safety when only one thread is writing

I know if two threads are writing to the same place I need to make sure they do it in a safe way and cause no problems but what if just one thread reads and does all the writing while another just reads.
In my case I'm using a thread in a small game for the 1st time to keep the updating apart from the rendering. The class that does all the rendering will never write to anything it reads, so I am not sure anymore if I need handle every read and write for everything they both share.
I will take the right steps to make sure the renderer does not try to read anything that is not there anymore but when calling things like the player and entity's getters should I be treating them in the same way? or would setting the values like x, y cords and Booleans like "alive" to volatile do the trick?
My understanding has become very murky on this and could do with some enlightening
Edit: The shared data will be anything that needs to be drawn and moved and stored in lists of objects.
For example the player and other entity's;
With the given information it is not possible to exactly specify a solution, but it is clear that you need some kind of method to synchronize between the threads. The issue is that as long as the write operations are not atomic that you could be reading data at the moment that it is being updates. This means that you for instance get an old y-coordinate with a new x-coordinate.
Basically you only do not need to worry about synchronization if both threads are only reading the information or - even better - if all the data structures are immutable (so both threads can not modify the objects). The best way to proceed is to think about which operations need to be atomic first, and then create a solution to make the operations atomic.
Don't forget: get it working, get it right, get it optimized (in that order).
You could have problems in this case if list's sizes are variable and you don't synchronize the access to them, consider this:
read-only thread reads mySharedList size and it sees it is 15; at that moment its CPU time finishes and read-write thread is given the CPU
read-write thread deletes an element from the list, now its size is 14.
read-only thread is again granted CPU time, it tries to read the last element using the (now obsolete) size it read before being interrupted, you'll have an Exception.

Multithreading in applet

I was wondering how I would use multiple threads in an applet at the same time. I'm creating a game like Space Invaders and I wrote all the code for the enemies to move and shoot but I can't add the player in to move around using the keyboard at the same time as the enemies. So I was thinking I needed to have 2 different threads running. I would upload the code but there is a lot of different classes and code.
If someone could help me out quick I would appreciate it a lot.
Yes they are independant of each other i got my single thread that moves the enemies in the run() method that i overloaded and all my movements are in the paint method.
should they be somewhere else?
You can do this with one thread, or with two.
Either way you have to work with the GUI Event Thread to do all the screen updates.
There is a lot of reference on the web discussing how to do this. If you google java space invaders you get 1.5 million hits and usually the first page of such a search has more than what you need.
I think the enemies are independent and have particular movements, if that's the case, you will need several threads enemy, and for each player, but taking into account the resources of the computer you should deal with a manager thread or task managers.
These are links that maybe help you.
http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/ThreadPoolExecutor.html
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CyclicBarrier.html

Categories