![]() ![]() This is because the objects are locked in different order. This methods would probably create a great deadlock if called by many threads. This one is a basic one: public void methodA() The result is both threads finishing correctly, avoiding any deadlock. Public static volatile boolean flag = true DEADLOCK IN JAVA CODESo, this same code with just that keyword added: public class UntilYouUpdateIt Volatile tells the compiler: do not try to optimize when this variable is involved. The correct solution to avoid these kind of deadlocks, when working with boolean variables, should be including the volatile keyword. The output would be: I'm loopinnnngĭepending which thread was assigned the cpu time at the end. If some "heavy" operation is included ( int i=1 or similar would'nt work neither), such as a System call, the optimizer will be a little more careful, checking the flag boolean in order to know if he's not wasting resources. Two ways to solve/test this: Thread t1 = new Thread(()-> In other words, Thread1 will always be reading the flag value from the cache, where it is set as true.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |