[java] A little bit of theory on threading!

Started by
2 comments, last by FlaiseSaffron 14 years, 1 month ago
How should I thread a swing based RTS? I was previously using ignoreRepaint(true) for all my components and repainting manually all in one thread to avoid concurrent mod exceptions. What is the correct way to do this? For smoothness, efficiency, etc. I imagine it would be a nightmare to program every in game entity to know when it needs repainting, so updating the gui at fixed intervals still seems desirable. Thoughts!
Advertisement
That will only work if your game environment updates at the same rate as you update the screen. That's fine for a fighting game, but 30-60 physics updates per second sounds excessive for an RTS.

I suggest using a swing Timer to run each type of task from the event dispatch thread. That way you'll be accessing and modifying data from only one thread and you will have no concurrency issues.

In code, this would be:
Timer physics = new Timer(100, new ActionListener() {	public void actionPerformed(ActionEvent evt) {		// updates physics 10x per second	}});Timer animation = new Timer(30, new ActionListener() {	public void actionPerformed(ActionEvent evt) {		// updates animation ~30x per second		repaint(); // repaint normally; no need for immediate drawing	}});physics.start();animation.start();
Quote:Original post by Dathgale
That will only work if your game environment updates at the same rate as you update the screen. That's fine for a fighting game, but 30-60 physics updates per second sounds excessive for an RTS.

I suggest using a swing Timer to run each type of task from the event dispatch thread. That way you'll be accessing and modifying data from only one thread and you will have no concurrency issues.

In code, this would be:
*** Source Snippet Removed ***


Would this fix concurrent modification exceptions? What about the whole invokeLater() usage?

Here is some in-game footage of what i have now. The scrolling glitch with fields of stray lines only appears during video recording.

Quote:Original post by overeasy
Would this fix concurrent modification exceptions?

Concurrent modification exceptions occur if you modify a collection while iterating over it. This can be caused by multithreading, but a thread can cause that exception by itself like so:
List list = ...;for(Object element: list)	list.add(...); // <-- throws ConcurrentModificationException


If you don't do anything like the above, then single-threading your application will solve the concurrent modification problems.

Quote:What about the whole invokeLater() usage?

EventQueue.invokeLater(new Runnable() {	public void run() {		// This runs in the event dispatch thread at the next opportunity.	}});

There's not much to this method. Read the documentation if you still don't understand.

This topic is closed to new replies.

Advertisement