• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Simple question

Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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!
Posts: 23883
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux 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).

Vasily Kukhta
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, Henry!
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    Bookmark Topic Watch Topic
  • New Topic