Java calculate pi loop9/18/2023 ![]() ![]() This would be fine if only one thread is running the job method. So, on the face of it, it looks like sampledelay is supposed to be how long to wait before generating the next sample. I don't see a benefit over using sleep here at all. ![]() Looking at the code you've written, you're essentially replacing sleep with your own more complicated implementation of it. ![]() I think the aversion to putting sleeps in loops is that it suggests that you're polling / performing an operation that might be handled better in another way. So, for example the generation of the x/ y values and dist don't really need to be done during protected processing. Sometimes that might mean doing a bit of extra work that's wasted but the net result can be beneficial. In general, I try to keep the amount of work that's done within locks to a minimum. This seems like wasted cycles that could be used elsewhere. If you fail to get the lock, you're simply spinning checking if enough samples have been generated / it's been shutdown. I don't really see the advantage of using trylock here, over just using lock. If you're not going to protect it, it may be worth considering using AtomicInteger. It's also worth mentioning that sample++ isn't guaranteed to be threadsafe. This would result in an extra sample being created and added to points. As it stands, it's possible (although fairly unlikely) that a thread would unlock lock just as another thread enters the while loop, having checked the value of samples. How important is it that the number of samples collected is exactly reqsamples? If it's important then you need to protect samples. I'm assuming that the job method will be running on multiple threads. }, (long)(sampledelay * 1000000), TimeUnit.NANOSECONDS) Īs has been said in the comments, there are bits missing here for a full answer. calling Thread.sleep() in a loop isn't that good instead of all of this code, because I know that I don't know if it is safe to use Thread.sleep() here here I use a scheduled thread pool to avoid Thread.sleep() private volatile boolean waiting = false I'm also learning how do Java threadpools and multithreading work.Ĭan you tell me if this method is thread-safe and how can I improve it if there is a deadlock chance. I made this code to calculate pi using MonteCarlo method. ![]()
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |