Java deadlock with 1 bject12/30/2023 It hangs and you have to press Ctrl + C to terminate the program.You can ask why the previous version of the example runs fine. Hence deadlock occurs.That’s why you see the program quickly runs into deadlock after few transactions have been done. Other threads may add funds to accounts 1 and 3, but if all threads are trying to transfer an amount greater than the account’s balance, they are waiting for each other forever. Similarly, thread 2 also has to wait because account 3 doesn’t have sufficient fund. Now the maximum amount can be transferred is 200, so there will be some threads trying to transfer an amount which is greater than the account’s balance, for example: Thread 1 tries to transfer 150 from account 1 to account 2 Thread 2 tries to transfer 170 from account 3 to account 1Account 1 has only 100 in balance so thread 1 has to wait for other threads to deposit more funds to this account. Let’s analyze the code to understand why.In the Bank class you will each account is initialized with an amount of 100. Why can deadlock happen when we increase the maximum amount of money can be transferred among accounts? Guess what will happen?You will see that the program runs for a few transactions and hangs forever, as shown in the following screenshot: The program encounters a deadlock and cannot continue. Modify the maximum amount can be transferred from 10 to 200 in the Bank class as follows: public static final int MAX_AMOUNT = 200 Look at the Transaction class you see the amount is chosen randomly by this statement: int amount = (int) (Math.random() * Bank.MAX_AMOUNT) Now, recompile the Bank and Transaction classes, and then run the TransactionTest program. When deadlock occurs, the program hangs forever and the only thing you can do is to kill the program.Let’s consider the account transaction example in this tutorial. Understanding Deadlock Deadlock describes a situation where two more threads are blocked because of waiting for each other forever. You will be able to identify each kind of problem so you can know to avoid them. This Java concurrency tutorial helps you understand the 3 problems that may happen in multi-threaded applications: deadlock, livelock and starvation.
0 Comments
Leave a Reply.AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |