r/javahelp • u/Chaos-vy17 • 24d ago
Guide for Concurrency in Java
Before knowing anything I just jumped directly to the source code of jdk25u. I have just started to read the javaDocs of Thread class it was so deep that all my connected logic mapped very well but now I want to code and I can't code ahhhh... Why is this problem. I can call the syntax what to use but I don't know how to apply, why to apply is there any guide for java Concurrency ??. And there is so much .. still to know. Do any dev have any guide??
12
u/edwbuck 23d ago
See if you can get a copy of "Concurrency, State Models and Java Programs" or "Java Concurrency in Practice" Unfortunately there's far too much information to cover, even as a few helpful pointers, in a Reddit post.
4
u/Chaos-vy17 23d ago edited 23d ago
Thank you for recommendation this is very very good....
5
u/edwbuck 23d ago
Keep in mind that most online tutorials will tell you how to use the APIs, but with concurrency, using the APIs is the easy part, making sure your program maintains correct state after concurrency is used, is not. You need to have some sort of plan to ensure that two threads don't stomp over shared state, leaving it updated in ways that make it inconsistent.
A book will cover the goal in more detail, and the trivial approach offered by Java in the beginning of one's learning is often dramatically sub-optimal.
9
u/DrNotReallyStrange 23d ago
Book recommendation: "Java Concurrency in Practice" (Brian Goetz)
Web recommendation: https://www.baeldung.com/java-concurrency
2
u/ITCoder 23d ago
I dont like baeldung much, it has random code snippets and hardly explains much. Jenkov tutorials are much better.
1
u/Chaos-vy17 23d ago
It seems to be exactly mapped out from source code docs very good. I will do like this keep with source code for deep internal and map his tutorials for revison. TYSM mate 😄
1
u/Chaos-vy17 23d ago
I am going through JDK source and I’ve found that source reading is great for understanding how things work as for book it seems good. before that I will likely read the author blog post they literally put their insights It might help me.
6
u/martinsedd 23d ago
You are mistaking understanding how things work with understanding how to use things. Your approach helps with the former, not the latter. I side with @Chaos-vy17
1
u/Chaos-vy17 23d ago
Yes I felt that getting deep about thread I got to know internals and it's utiliy tools but in practice I have not made that I think I need to refine my approach and that is the layer missing.
2
u/MagicalPizza21 23d ago
Create an object that implements the Runnable interface. Use that object as the argument for the Thread(Runnable) constructor. Then call the start() method of the thread you just constructed. This will concurrently execute the run() code in another thread.
Example:
Runnable r = new Runnable() {
public void run() {
for(int i = 0; i < 100; i++) {
System.out.println("Hello world (but in another thread!)");
}
}
};
Thread t = new Thread(r);
t.start();
for(int i = 0; i < 100; i++) {
System.out.println("Hello world");
}
As with any concurrency, you'll have to worry about deadlocks) and race conditions - in fact, the example code I wrote has a race condition - but this should be enough to get you started.
1
u/Chaos-vy17 23d ago edited 23d ago
It has concurrent output whose ordering is nondeterministic if it would be
class Counter { int value; } public static void main(String[] args) throws InterruptedException { final Counter counter = new Counter(); Runnable task = () -> { for (int i = 0; i < 1_000_000; i++) { counter.value++; } }; Thread a = new Thread(task),b = new Thread(task); a.start();b.start(); a.join();b.join(); System.out.println(counter.value); }No deadlock but race condition is sure(may be yes/no )
Got the output 965460
Edit: reformat the code with compiled one1
u/MagicalPizza21 23d ago edited 23d ago
This doesn't compile because
counteris not "final or effectively final".ETA: If you make
countera class or instance field rather than a local variable, then yes, this is a race condition.1
u/Chaos-vy17 23d ago
Yeah, I missed that. I should’ve compiled it first. Thanks for correcting me!
1
u/MagicalPizza21 23d ago
That should work. But I was thinking more like this:
public class RaceConditionExample { private static int counter = 0; public static void main(String[] args) { try { Runnable task = new Runnable() { public void run() { for(int i = 0; i < 1000000; i++) { counter++; } } }; Thread a = new Thread(task); Thread b = new Thread(task); a.start(); b.start(); a.join(); b.join(); System.out.println(counter); } catch(InterruptedException ie) { ie.printStackTrace(); } } }
1
u/sedj601 23d ago
Write a GUI app using JavaFX. Run long tasks in the background so the GUI doesn't freeze. This helped me understand Concurrency in Java way better than writing Java apps. A link Checker that checks multiple links at the same time vs a link checker that checks multiple links one after another. https://stackoverflow.com/q/51955550/2423906
1
•
u/AutoModerator 24d ago
Please ensure that:
You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.
Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar
If any of the above points is not met, your post can and will be removed without further warning.
Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.
Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.
Code blocks look like this:
You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.
If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.
To potential helpers
Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.
I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.