Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple question

 
Vasily Kukhta
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello!

I am studying java multithreading now, and i have a simple question, please help.

How can i make a thread attempting to lock several objects at once, waiting for them if they are all locked already by another threads, and lock the first which is released?

I have found tutorials only about how to make a thread waiting for a single monitor, not several objects at once. It is perhaps a basic question, but i'm stuck.

Thanks in advance!
 
Henry Wong
author
Marshal
Pie
Posts: 22111
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

There is actually no such mechanism in Java threading (or POSIX, Solaris, Windows, etc), that will allow you to acquire multiple locks simultaneously. This is why when you need more than one lock, you should always establish a lock order. If no such order exists, and two threads need more than one lock, then it is possible for the two threads to deadlock.

As for the waiting for multiple locks, and get the first one freed, that is a sign of a poor design.... but you can kinda hack it. Java does provide a mechanism (if you use the Lock and Condition class to check the status of the lock or try to acquire locks).

Henry
 
Vasily Kukhta
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Henry!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic