• 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
Sheriff
Posts: 22641
111
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!
 
my overalls have superpowers - they repel people who think fashion is important. Tiny ad:
the new thread boost feature brings a LOT of attention to your favorite threads
https://coderanch.com/t/674455/Thread-Boost-feature
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!