473,471 Members | 2,075 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

java threading question

1 New Member
Hey everyone,

Let me state up front that this is a homework assignment.

I'm supposed to take a simple task (flipping a coin n number of times) and use threading to increase the execution speed of the program. The basic idea is that to flip a coin 1,000,000 times, you could launch n threads and have it execute approx. n times as fast.

I've been working on it for a few days. The code is complete in that the task gets divided up and runs on multiple threads. However, the execution time doesn't nearly reflect what I would expect it to be.

For example, flipping 10,000,000 "coins" takes:

~700ms using 1 thread.
~980ms using 2 threads.
~920ms using 4 threads.

I would expect that the execution time would decrease as I add more threads. This time difference is magnified as I increase the number of coin flips. For example, flipping 100,000,000 "coins" takes:

~7 seconds using 1 thread.
~10 seconds using 2 threads.

Does this make sense? My code isn't very long, and I've included it below. Am I just missing something obvious?

The project contains three files:
- CoinFlip.java (the main program)
- FlipCoins.java (implements Runnable - used to execute some number of coin tosses on a separate thread)
- CoinData.java (basically a struct to store the coin toss statistics)

CoinFlip.java
Expand|Select|Wrap|Line Numbers
  1. public class CoinFlip
  2. {
  3.     public static void main(String[] args)
  4.     {
  5.         // declare needed variables
  6.         int numTosses = 10000000;
  7.         int numThreads = 8;
  8.         int numTossesPerThread = numTosses / numThreads;
  9.         int numTossesLeftover = numTosses - numTossesPerThread * numThreads;
  10.         int workload;
  11.         long startTime, endTime, totalTime;
  12.  
  13.         // basically a struct to hold the coin toss statistics 
  14.         CoinData data = new CoinData();
  15.  
  16.         // array of threads
  17.         Thread[] threads = new Thread[numThreads];
  18.  
  19.         // set the start time
  20.         startTime = System.currentTimeMillis();
  21.  
  22.         // spawn the threads
  23.         for (int i = 0; i < numThreads; i++)
  24.         {
  25.             // calculate the workload for each thread
  26.             if (i == numThreads - 1)
  27.             {
  28.                 workload = numTossesPerThread + numTossesLeftover;
  29.             }
  30.             else
  31.             {
  32.                 workload = numTossesPerThread;
  33.             }
  34.  
  35.             // spawn the thread
  36.             threads[i] = new Thread(new FlipCoins(data,workload));
  37.             threads[i].start();
  38.         }
  39.  
  40.         // wait for the threads to complete
  41.         for (int i = 0; i < numThreads; i++)
  42.         {
  43.             try
  44.             {
  45.                 threads[i].join();
  46.             }
  47.             catch (InterruptedException e)
  48.             {
  49.                 e.printStackTrace();
  50.             }
  51.         }
  52.  
  53.         // calculate the total execution time
  54.         endTime = System.currentTimeMillis();
  55.         totalTime = endTime - startTime;
  56.  
  57.         // print out the results
  58.         System.out.println("Execution Time: " + totalTime + "ms");
  59.         System.out.println("Num Heads: " + data.numHeads());
  60.         System.out.println("Num Tails: " + data.numTails());
  61.     }
  62. }
  63.  
FlipCoins.java
Expand|Select|Wrap|Line Numbers
  1. public class FlipCoins implements Runnable
  2. {
  3.     private int mNumIterationsToRun = 0;
  4.     private CoinData mCoinData;
  5.  
  6.     public FlipCoins(CoinData d, int n)
  7.     {
  8.         mCoinData = d;
  9.         mNumIterationsToRun = n;
  10.     }
  11.  
  12.     @Override
  13.     public void run()
  14.     {
  15.         int numHeads = 0;
  16.         int numTails = 0;
  17.  
  18.         for (int i = 0; i < mNumIterationsToRun; i++)
  19.         {
  20.             if (flipCoin())
  21.                 numHeads++;
  22.             else
  23.                 numTails++;
  24.         }
  25.  
  26.         mCoinData.addHeadData(numHeads);
  27.         mCoinData.addTailData(numTails);
  28.     }
  29.  
  30.     private boolean flipCoin()
  31.     {
  32.         if (Math.random() > 0.5)
  33.             return true;
  34.         else 
  35.             return false;
  36.     }
  37. }
  38.  
CoinData.java
Expand|Select|Wrap|Line Numbers
  1. public class CoinData
  2. {
  3.     private volatile int mNumHeads = 0;
  4.     private volatile int mNumTails = 0;
  5.  
  6.     public synchronized void addHeadData(int n)
  7.     {
  8.         mNumHeads += n;
  9.     }
  10.  
  11.     public synchronized void addTailData(int n)
  12.     {
  13.         mNumTails += n;
  14.     }
  15.  
  16.     public int numHeads()
  17.     {
  18.         return mNumHeads;
  19.     }
  20.  
  21.     public int numTails()
  22.     {
  23.         return mNumTails;
  24.     }
  25. }
  26.  
I appreciate your time and any thoughts you might have. Thanks!
Sep 9 '10 #1
1 2676
Oralloy
988 Recognized Expert Contributor
Actually, your results are probably reasonable.

First off, does your system have multiple CPUs? Or at least multiple cores? If not, all the threads will have to share the CPU, and consequently your performance will drop, as the calculation will take the same amount of time, plus there will be additional time spent managing the multiple threads and swapping them.

Even if your system has multiple cores, if there's a sequencing point in the code, then your program still has to visit that point every time for every thread. Unless the sequencing time cost is less than the cost of a coin flip, you'll see an increase in execution time.

About the only way that your throughput will increase in this case is if you can guarantee that the threads are completely disjoint. That means that there is no shared resource (e.g. a counter or I/O), and you have a true multiple processing system that you can exploit.

Still, even in that case, the CPU time will probably go up, because you have the minimum cost (the execution time of the coin flips) plus some overhead time for synchronization. Wall-clock time may go down, however, in this case.

Also, given the jitter in clocks, tests that run under one second are generally dubious at best. Try to increase the execution time by a factor of 100, if you can. This will eliminate small statistical issues associated with the clock.

Good luck!
Sep 9 '10 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: codecraig | last post by:
If i have a class such as class Foo: def doSomething(self, cmd, cmd2, callback): cmd = <translate command> results = <..do some possibly long task..> callback(results) What I am looking to...
0
by: Alina | last post by:
Hello I'm working with a disconnected DataSet and I wish to make thread-safe the "add new rows" method. I try like this, but does not work: public class MyXmlDataDoc { ........
0
by: CK | last post by:
I have the following code in a windows service, when I start the windows service process1 and process2 work fine ,When process 1) and 2) get completed process 3) starts and sofar so good. the...
9
by: Edward | last post by:
Hello I hope someone could help me I'm trying to prevent code from running before the thread I created completes. Here's the code snippet DataTransformerWorker dtw = new...
6
by: Matt Long | last post by:
I was wondering if any one could help me out with a threading question. Im developing an app which starts a thread, which in turn starts 4 of its own threads. If I call 'sleep' on the initial...
2
by: Rothariger | last post by:
hello, i have a question of threads, im making some tests, and i want to get a value of a variable inside a thread, but i want to retrieve from outside of it.. was it clear? 'when i clic the...
4
by: DBC User | last post by:
I have a background process which reads a table to see if there are any pending requests. If there are any, then it will start a worker thread (only 10 allowed at a time) and executes a method. In...
19
by: frankiespark | last post by:
Hello all, I was perusing the internet for information on threading when I came across this group. Since there seems to be a lot of good ideas and useful info I thought I'd pose a question. ...
3
by: Sparky | last post by:
It seems strange, but I can't find a list of operating systems which support / don't support threading in Python. Can anyone point me in the right direction? Thanks, Sam
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.