### Multi-Core Programming with Java

Processors speeds are no longer growing at the rate we've grown accustomed to. Moore's law states that computers double in speed every 18 months. Moore's law is still alive and well, but we just need to find alternate ways to speed up computers. That's where multi-core programming comes into play. The idea behind it is that 2 heads are better than one and in the right situation 2 processors can work on the same problem to solve it twice as fast. Parallel programming is becoming increasingly important these days and there are many different flavors of it including distributed computing, shared memory computing, and GPU computing. Today I am going to focus on shared memory computing, or using multi-core computers rather than many single core computers. This blog post is intended to serve as a beginners guide to parallel programming with Java. It is recommended that the reader have some java experience and is familiar with some of the features of Java 8 (namely lambda expressions and streams). Most modern day computers are multi-core and 4 cores is the norm from what I've seen, but depending on your computer you may have more or less.

### The Problem

I will demonstrate multi-core programming with java by means of example. For simplicity and demonstration purposes, I am going to use the Monte Carlo method for approximating Pi. If you are unfamiliar with the algorithm, I created an animation to demonstrate how it works:

Note that you can restart the animation by pressing the Space Bar. The algorithm works by taking a random sample of points from a uniform distribution with $0<x,y<1$ and determining if that point lies within the first quadrant of the unit circle centered at $(0,0)$. If it does, then that is considered a success. If the random number generator is truly uniform, then $\frac{success}{total} \approx \frac{\pi}{4}$, since the area of the first quadrant of the unit circle is $\frac{\pi}{4}$ and the total area of the unit cube is $1$.

### Java Implementation

The Java Runnable interface is designed for handling parallel and concurrent programs. Any class that implements this interface must implement this function:
@Override
public void run() {
//implementation here
}

Here is my Java implementation of this class:
import java.util.concurrent.ThreadLocalRandom;
class ComputeUnit implements Runnable {

private int trials, success;
private CountDownLatch latch;

public ComputeUnit(int trials) {
this.trials = trials;
this.success = 0;
}

public int getTrials() {
return trials;
}

public int getSuccess() {
return success;
}

public void setLatch(CountDownLatch latch) {
this.latch = latch;
}

@Override
public void run() {
for(int i=0; i < trials; i++) {
if(x*x + y*y < 1)
success++;
}
latch.countDown();
}
}
There are a few things to note about this implementation. First, the information about what is being computed is being passed in to the constructor. In this case, that is just the number of trials to compute. Second, the CountDownLatch is a java class in the java.util.concurrent package. It is a mechanism to safely handle counting the number of completed tasks. You should call latch.countDown() whenever the run method competes.

So now we have a Runnable class that can handle a single set of trials. Now, I want to create multiple instances of this Runnable and let my quad-core computer quadruple the performance! The ExecutorService is exactly what we need to accomplish this.
static double montecarlo(int threads, int trials) throws InterruptedException {

Arrays.setAll(runnables, n -> new ComputeUnit(trials));
for(ComputeUnit r : runnables) {
r.setLatch(latch);
exec.execute(r);
}

latch.await();
exec.shutdown();

int success = Arrays.stream(runnables).mapToInt(r -> r.getSuccess()).sum();
int total = threads * trials;
double pi = 4.0 * success / total;
return pi;
}

public static void main(String[] args) throws InterruptedException {
System.out.println(montecarlo(8,1000000));
}

The ExecutorService class enables you to easily run and execute Runnables (and Callables). It is created with the Executors.newFixedThreadPool(threads) method. The input argument is the number of threads you want in your pool. I typically like to choose this number to be twice as many cores on my computer, but depending on the situation you might want to do something different. If you expect each job to take the same amount of time, then it's a good idea to make this a multiple of the number of cores on your computer. If the amount of time for each job varies based on the input, then it's a good idea to set this value to be larger so that 1 job wont be a major bottleneck. Next, you need to instantiate a CountDownLatch with the same number of jobs as before. Next, you need to create the jobs; I store them in an array so I can collect the results at the end. If your runnable just updates a global variable, then it's not necessary to store these runnables objects. exec.execute(r) adds r to the thread pool. After all the runnables have been added to the pool, you need to call latch.await() which blocks until the latch reaches 0 (indicating all the compute units finished computing). Then, it's safe to shutdown the ExecutorService and collect the results.

### Conclusion

The above code should provide a minimal working parallel program for you to play around with. You can tinker with the existing code or implement your own Runnable class and try it out for yourself. You'll need to have Java 8 installed but other than that it should be good to go!

1. thankx for the detail css article i enjoined it

1. Hall of Fame - 2017, Live Stream, Pro Football, TV Online, How to watch Free

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

https://halloffame-game.com

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai

4. Hey, thank you very much for this work, I found this very helpful!

I got one question, when I try run this code, it seems that running it on 1 thread on my pool makes it execute faster, shouldn't the opposite be the case? I am running on a quad-core A10 processor btw.

1. I saw something similar with my i7-4700HQ based laptop (4 cores supporting 8 threads per Intel documentation). I can see indirectly that the cores are being used since the Task Manager shows the level of CPU usage and this scales with the number of threads I specify. However, the benchmark execution times do not reduce with the number of threads going from 4 to 8, but rather increases by ~35% (repeatably). The fastest execution time is with 1 or 2 threads. And this is with all applications under my control stopped and wireless disconnected.

I love the example, but am mystified by the benchmarks.

5. The blog gave me idea about multicore programming Thanks for sharing it

6. awesome thought.I have used java 8 streams and lambda expression.After reading your blog I have one question here. How java 8 stream works concurrently.Is it some kind of thread running in parallel.
By Devglan

7. This comment has been removed by the author.

8. useful information .Thanks for sharing this post. Also learn the python programming course from the experts.

9. Hello Admin, thank you for enlightening us with your knowledge sharing.
J2EE Training in Chennai

11. Thanks for Sharing. Nice article. https://www.uui.ac.id

1. https://stanley-cup.org/

https://stanley-cup.org/

https://stanley-cup.org/

https://stanley-cup.org/

https://stanley-cup.org/

12. A very Impressive and detailed post. Thanks for sharing such a wonderful and important information. Check for more latest job openings Contact Us @ CelebrateJobs

13. keep writing the article and thankyou for information. so nice !!

Agen Sakong Online
Agen Domino99 Online
Agen BandarQ Online
Agen Texas Online

14. https://212ufc.org/

https://212ufc.org/

https://stevensonvsfonfara.org/

https://stevensonvsfonfara.org/

15. Thanks so much for taking the time to submit such a comprehensive, beneficial post. I've been being "swayed" by all the positive talk. A valuable information is also available here.
Web Designing Training in Chennai | Dot Net Training in Chennai

16. https://nba-final.net/

https://nba-final.net/

https://finals--nba.com/

https://finals--nba.com/

17. https://stakesbelmont.org/

https://stakesbelmont.org/

https://belmontstakes-2017.com/

https://belmontstakes-2017.com/

18. I've found my answer here http://breakyourillusions.com/

19. https://americas-cup.org/

https://americas-cup.org/

https://2017-usopen.org/

https://2017-usopen.org/

https://collegeworld-series.org/

https://collegeworld-series.org/

20. ultimately impacting quality of care Casino Sbobet

21. https://india-vspakistan.org/

https://india-vspakistan.org/

https://india-vspakistan.org/

22. https://worldseriescollege.com/

https://worldseriescollege.com/

https://worldseriescollege.com/

https://worldseriescollege.com/

Python Training in Chennai | Big Data Analytics Training in Chennai

24. Thanks so much for taking the time to submit such a comprehensive, beneficial post. IA valuable information is also available here. Hadoop Training in Chennai | Cloud Computing Training in Chennai

25. awesome thought.I have used java 8 streams and lambda expression.After reading your blog I have one question here. How java 8 stream works concurrently.Is it some kind of thread running in parallel.

Python Online Training

26. Best site to find newspapers directory is Librly. Do not wait just find list of newspapers or full best newspapers directory. If you are intrested in top newspapers in world just go to Librly. You will find complete list of newspapers in world contains best newspapers in world

27. awesome thought.I have used java 8 streams and lambda expression.After reading your blog I have one question here. How java 8 stream works concurrently.Is it some kind of thread running in parallel.

Domino 99, AseanQQ, Prediksi Togel

28. https://open-british.com/

https://open-british.com/

https://open-british.com/

29. https://open-british.org/

https://open-british.org/

https://open-british.org/

30. https://the-british-open.org/

https://the-british-open.org/

https://the-openchampionship.org/

https://the-openchampionship.org/

Prediksi Togel

Togel Singapura

Hongkong Pools

Togel SGP

32. https://iaafworld-championships.org/

https://iaafworld-championships.org/

https://iaafworld-championships.org/

33. https://the-pga-championship.org/

https://the-pga-championship.org/

https://thepga-championship.com/

https://thepga-championship.com/

34. https://pgachampionshipthe.org/

https://pgachampionshipthe.org/

https://pgachampionshipthe.org/

35. https://pgachampionshipthe.com/

https://pgachampionshipthe.com/

https://uspgachampionship.com/

https://uspgachampionship.com/

36. https://thepga-championship.org/

https://thepga-championship.org/

https://thepga-championship.org/

37. Memberikan Prediksi Skor Pertandingan Sepak bola Akurat Malam hari ini, serta Prediksi Togel setiap harinya terupdate dan terpercaya Prediksi Bola

38. Learn top most programming language java very easily,
This tutorial with few easy steps you can learn java in short time,
Click below to learn java

http://www.technewsncareer.com/p/java-tutorial.html

Learn java with easy steps 7 days

http://www.technewsncareer.com/p/java-tutorial.html

39. If you are looking for spring hibernate training institute in chennai then candid training is the best place to learn.

Candid gives you best in class spring hibernate training with high quality and post training support, We provide you free demo session and candid promises the permanent trainer throughout your session and focus on more practical.

1. Demo classes will be arranged before joining

for more details visit candid industrial training at chennai

40. nice info you got there, i found this site from my friend computer and good things this is a good site judi dewa poker terbaik indonesia

42. Very nice..I gain some knowledge about core Java Techniques ..It's really useful from me..
Software Testing Training in Chennai |No.1 Selenium Training Institute in Chennai | Web Designing Training Institute in Chennai

43. nice info you got there, i found this site from my friend computer and good things this is a good site poker online

info menarik

44. https://panthers-vs49ers.org/

https://panthers-vs49ers.org/

https://panthers-vs49ers.org/

45. Hey, Wow all the posts are very informative for the people who visit this site. Good work! We also have a Blog.Please feel free to visit our site. Thank you for sharing.
Web Designing Training in Indore
Keep Posting:)

46. Bergabung Dan Tunjukkan Cara Bermain Pokermu.
https://goo.gl/iXP5pY
Untuk Info Lebih lanjut Silakan hubungi CS (custumer Service).
poker online

judi poker

47. 18++ visit my site
http://www.bungarangkaian.com/kuliner-bandung/
http://www.zeralyn.com/refrensi-liburan-di-bandung-dari-prestisa/
http://www.bungarangkaian.com/jajanan-surabaya/
http://www.zeralyn.com/toko-bunga-online-di-surabaya/
http://www.bungarangkaian.com/prestisa-toko-bunga-online-di-bekasi/
http://www.zeralyn.com/toko-bunga-kalimalang-bekasi/
http://www.bungarangkaian.com/toko-bunga-online-di-malang/
http://www.zeralyn.com/toko-bunga-online-prestisa-di-malang/
http://www.prestisa.com/toko-bunga-pasar-minggu-pesan-bunga-papan-24-jam-di-jakarta-selatan/
http://www.zeralyn.com/liburan-di-pulau-seribu/

49. Vary helpful article on multi-threading with java. You put a lot of effort into it. ... and the animation is cool :)

Best Regards,
JTN ( https://javatutorial.net )

50. Good post. Thank you for sharing such a wonderful information...CCNA Training Institute in Chennai | CCNA Training Institute in Velachery.

51. Hello
this is my first visit to your site
judi poker

52. Awesome blog with great content, you explained everything in detailed manner. Thanks a lot for share such a nice article. Linux Training in Chennai | Unix Training in Chennai | Python Training in Chennai

53. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharing this information, this is useful to me…
No.1 Software Testing Training Institute in Chennai | Best Selenium Training Institute in Chennai | ISTQB Certification Center in Velachery

54. It is a one of the great discussion which is very essential for me as well. I must follow the handy discussion and sure that the content will be very useful to me as well. Keep it up.
C &C++ Training in Chennai | Embedded System Training in Chennai | VLSI Training Center in Chennai

55. Your blog is amazing,its very interesting to read..Thank you for sharing such an interesting article.
MBA Project Center in Chennai | MCA Project Center in Chennai | BBA Project Center in Chennai

56. Bergabung Dan Tunjukkan Cara Bermain Pokermu.
Dan Jangan Lupa Juga kami Ada Promo Buat Anda.
https://goo.gl/iXP5pY
Untuk Info Lebih lanjut Silakan hubungi CS (custumer Service).
-Whatsapp : +855966624192
-BBM : D8C893A4
agen judi poker online terpercaya di indonesia

bandar judi poker online yang paling aman

taruhan judi poker online terpercaya

poker online

judi poker

dewa poker

raja poker

judi poker online terbesar

judi poker online yang aman dan terpercaya

bandar poker online indonesia

judi dewa poker terbaik indonesia

agen poker online indonesia

poker online betting

poker online terbaik

57. I really like your article and my new time this blog is very interesting thank you
poker online

58. love the article that you make really very inspiring terimakasjh for this
sinidomino

59. verynice

http://www.prestisa.com/toko-bunga-online-di-kota-bandung/
http://www.bungarangkaian.com/kuliner-bandung/ http://www.zeralyn.com/refrensi-liburan-di-bandung-dari-prestisa/

60. Nice Blog thanks for sharing this information with us Tripura Govt Jobs

61. What a great article, please keep writing!

Situs Bandarq
Agen Bandarq
Situs Domino99
Kumpulan Situs Poker

62. Mari Boskuu...
hanya Butuh 1 ID dan Anda Bisa Bermain 6 Permainan Di Sini.
jadi Tunggu Apa lagi,, Ayo Bergabung Dan MenangKan Jutaan Rupiah.

Jangan Ragu Dengan kami Di sini Kami MenjaminKan Pemainan Tanpa Robot.
Ataupun Admin Kami Bermain Bersama anda.
DI sini kami Fairplay, 100% Player VS player.
Poker Aman Dan Terpercaya Hanya Bersama Gadispoker.
Kami Juga Menyediakan Bermacam Promo untuk Para Member Setia Kami.

-Bonus Deposit Setiap hari Untuk Para member.
-Bonus Refferal 10% Seumur Hidup.
-Bonus TO/Turn Over Up TO 0,3% - 0,5%
-Bonus SmartPhone Xiomi 4A
Kalian Juga Akan Di layani dengan CS Kami Yang Ramah dan Sangat propesional.
Selama 24jam Nonstop,
JAdi Jangan Berpikir panjang lagi mari Bergabung bersama Gadispoker dan Di tunggu Kemenangannya,
Untuk Info Lebih lanjut Silakan hubungi CS (custumer Service).
-Whatsapp : +855966624192
-BBM : D8C893A4
Hubungi Segera Dan Jangan Lewatkan Kemenanganmu..!
agen judi poker online terpercaya di indonesia

bandar judi poker online yang paling aman

taruhan judi poker online terpercaya

poker online

judi poker

dewa poker

raja poker

judi poker online terbesar

judi poker online yang aman dan terpercaya

bandar poker online indonesia

judi dewa poker terbaik indonesia

agen poker online indonesia

poker online betting

poker online terbaik

63. I would like to say that this blog really convinced me, you give me best information! Thanks, very good post.
web design training in Indore
Keep Posting:)

64. nice information. Thanks for sharing...
https://www.brihaspathi.com/search-engine-optimization.html

65. Good Post,Thanks for sharing...
https://www.brihaspathi.com/search-engine-optimization.html

66. Thanks for your marvelous posting! It is very useful and good. Come on. I want to introduce the best aso services for you, I try it and I feel it is so good to rank app to top in app store search results, have you ever heard it?

67. Hey, would you mind if I share your blog with my twitter group? There’s a lot of folks that I think would enjoy your content. Please let me know. Thank you.

Java Training in Bangalore

68. https://world-juniors.com/

https://world-juniors.com/

https://world-juniors.com/

https://world-juniors.com/

https://world-juniors.com/

https://world-juniors.com/

https://world-juniors.com/

https://world-junior.com/

https://world-junior.com/

https://world-junior.com/

https://world-junior.com/

https://world-junior.com/

69. https://nfl-playoffs.net/

https://nfl-playoffs.net/

https://nfl-playoffs.net/

https://nfl-playoffs.net/

70. https://goldenglobes-2018.com/

https://goldenglobes-2018.com/

https://goldenglobes-2018.com/

https://the-goldenglobes.com/

https://the-goldenglobes.com/

https://the-goldenglobes.com/

https://goldenglobe-awards.com/

https://goldenglobe-awards.com/

https://goldenglobe-awards.com/

71. https://playoff-nfl.com/

https://playoff-nfl.com/

https://playoff-nfl.com/

https://thenflplayoffs.com/

https://thenflplayoffs.com/

https://thenflplayoffs.com/

https://nflplayoff2018.com/

https://nflplayoff2018.com/

https://nflplayoff2018.com/

72. Super Bowl 2018

https://superbowlsi.com/
https://superbowlsi.com/
https://superbowlsi.com/
https://superbowlsi.com/

Super Bowl 2018

73. intext:"berita online" "good post" "nice post"
bandar judi online

74. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.
dewa poker

75. very good article, do not forget to visit other interesting articles at:poker online uang asli

76. intext:"berita online" "good post" "nice post internet"
bandar judi online

77. intext:"berita online" "good post" "nice post internet"
bandar judi online

78. Thank you Information that you convey is very useful, waiting for the next update friend, Greetings Success :)
bandar judi online

79. good post http://www.dompetmgm.com/

80. Thank you Information that you convey is very useful, waiting for the next update friend, Greetings Success :)
agen bandarq

81. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.

82. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.

83. Guys just sharing, I've found this interesting! Check it out! https://marugujarat.online

84. A content of gratitude is in order for one great posting! I appreciated understanding it; you are an incredible creator. I will make a point to bookmark your blog and may return sometime in the future. I need to energize that you proceed with your incredible posts, have a nice day!
https://www.besanttechnologies.com/training-courses/dot-net-training

85. Thanks a lot very much for the word to say thanks to you for those wonderful tips and hints you are showing on this site.

Selenium Training in Jaya Nagar

86. Hey,
I think this is a standout amongst the most critical data for me. What's more, i'm happy perusing your article. Be that as it may, ought to comment on some broad things, The site style is flawless, the articles is truly awesome : D. Great job, here's to you
Web Design Surat
Surat IT Company
SEO Company in Surat

dewa poker

https://topsitusonline.com/8-permainan-game-online-yang-berpenghasilan-ratusan-juta/

89. Very good article! This is very interesting! Thank you for this blog!
You can find more information on Lingerie de charme. There's everything you need at the best price. http://dcbachata.com

90. Your good knowledge and kindness in playing with all the pieces were very useful. I don’t know what I would have done if I had not encountered such a step like this.

UIPath Training in Bangalore

91. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.
domino qiu qiu

92. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.
poker online betting

93. It is amazing article information when I was enjoying the trips of Jungle tours in India, Rajasthan India tours, Tiger tours in India, Tailor made trips in India, Best travel agent in Delhi, Golden triangle tours in India, Gujarat tour in India, Ladakh Festivals tours in India on that movement I read all the article news thanks for sharing

94. Daftarkan Diri anda segera di BANDAR TOGEL SINGAPORE Aman Dan Terpercaya

Bandar Togel Online Dengan Berbagai Kelebihan
# Minimal Bet 500 Perak
# Bonus Deposit Awal Idr.10.000
# Bonus Deposit Setiap Hari 2%
# Bonus Prize 2 & Prize 3
# BBFS 8 Digit
# Aman dan Terbukti Terpercaya

Togel Hongkong
Togel singapore
Togel sydney
Bandar online terpercaya
Pasang Togel
Bandar Togel
Agen Togel Singapore

95. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.
dewa poker

96. interesting articles and this is my first first reading a very interesting article thanks for this article that fits with the theme news.
bandar poker online indonesia

97. This comment has been removed by the author.

98. Thank You for sharing,
I'm Looking forward for aother good article like this, from you.
Thank You

Paket Tour Bandung
Paket Wisata Bandung
Paket Tour Wisata Bandung

99. Nice Article, Very useful and informative.
I'm Looking forward for another good article like this, from you.
Thank You

Paket Tour Bandung
Paket Wisata Bandung
Paket Tour Wisata Bandung

1. Nice Website, Very useful and informative.
I'm Looking forward for another good website like this, from you.
Thank You

Paket Wisata Bandung
Wisata Bandung

2. Nice Website, Very useful and informative.
I'm Looking forward for another good website like this, from you.
Thank You

Paket Wisata Bandung
Wisata Bandung

100. articles that I really like and thank you for this excellent article
togel singapura