Wednesday, March 20, 2013

Concurrent Programming Concepts in Java through Traffic Simulation

What's the better way to learn an obscure concept like concurrent programming? Any guesses? Yes, you got it right, it's through real time coding exercise.

Taking the above premise forward, I'm going to solve a coding exercise that touches a gamut of concurrency features in the Java programming language.

The solution touches upon the following java concurrent programming concepts:
  • Callable, ExecutorService, CompletionService and Future interfaces from java.util.concurrent package
  • Atomic variables
  • wait, notify and synchronization
  • Thread-safe singletons
  • How to write Custom Timers to simulate application Time Out.
The Coding Task - Traffic Simulation

Simulates 3 cars on a road and a stoplight. Each car is either moving at full speed, which is one unit per second, or it is stopped because of the stoplight. 
The stoplight is either green or red. If a car is at the same position as the stoplight (i.e. 50), and the stoplight is red, the car stops until the light turns green. 
We can assume that cars can occupy the same space without regard for each other.

The cars initially start at positions 24, 12, and 0. The stoplight is at position 50, is initially green, and switches every 10 seconds.

The program should simulate 100 seconds of operation. For each second, it should print out a line with the second number, the state of the stoplight and the positions of all three cars. The "seconds" are simulated - this is not a real-time simulation.

Example output:
0 Green 24 12 0
1 Green 25 13 1
2 Green 26 14 2
etc...

Java Implementation

The source code for the provided solution be accessed on my Github "Gists" with syntax highlight, better formatting and readability.
Here goes the links to Github.

Road.java (Test Harness)
StopLight.java

Class Diagram (Created using ObjectAid UML Diagram plugin for Eclipse)



Just copy the above file into your Eclipse Java project and run the Road.java as Java Application to play around with implementation and various scenarios.
Sample Output from Test Harness


0 GREEN 24 12 0
1 GREEN 25 13 1
2 GREEN 26 14 2
3 GREEN 26 15 2
4 GREEN 27 15 3
5 GREEN 27 15 3
6 GREEN 27 15 3
7 GREEN 28 16 4
8 GREEN 29 17 5
9 GREEN 30 18 6
10 RED 31 19 7
11 RED 32 20 8
12 RED 32 20 9
13 RED 33 21 10
14 RED 33 22 10
...




There could possibly be a thousand way (hope I'm not exaggerating) to code this exercise and I am providing just one of them that may be...well beyond the optimal solution.

I would love to see comments pouring in with alternate and optimized solutions so request all the readers to be generous with their ideas and thoughts in the comment section.

No comments:

Post a Comment