• Post Reply Bookmark Topic Watch Topic
  • New Topic

Simple question  RSS feed

 
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
Sheriff
Posts: 23289
125
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
Boost this thread!