Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6762325
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T14:18:28+00:00 2026-05-26T14:18:28+00:00

I’m wondering if there’s a way in Java to synchronize using two lock objects.

  • 0

I’m wondering if there’s a way in Java to synchronize using two lock objects.
I don’t mean locking on either object, I mean locking only on both.

e.g. if I have 4 threads:

  • Thread A requests a lock using Object1 and Object2
  • Thread B requests a lock using Object1 and Object3
  • Thread C requests a lock using Object4 and Object2
  • Thread D requests a lock using Object1 and Object2

In the above scenario, Thread A and Thread D would share a lock, but Thread B and Thread C would have their own locks. Even though they overlap with one of the two objects, the same lock only applies if it overlaps on both.

So I have a method called by many threads which is going to perform a specific activity type based on a specific database. I have identifier objects for both the database and the activity, and I can guarantee that the action will be thread safe as long as it is not the same activity based on the same database as another thread.

My ideal code would look something like:

public void doActivity(DatabaseIdentifier dbID, ActivityIdentifier actID) {    
    synchronized( dbID, actID ) { // <--- Not real Java
       // Do an action that can be guaranteed thread-safe per unique
       // combination of dbIT and actID, but needs to share a 
       // lock if they are both the same.
    }
}

I could create a hashmap of lock objects that are keyed by both the DatabaseIdentifier and the ActivityIdentifier, but I’m going to run into the same synchronization issue when I need to create/access those locks in a thread-safe way.

For now I’m just synchronizing on the DatabaseIdentifier. It’s much less likely that there will be multiple activities going on at the same time for one DBIdentifier, so I will only rarely be over-locking. (Can’t say the same for the opposite direction though.)

Anyone have a good way to handle this that doesn’t involve forcing unnecessary threads to wait?

Thanks!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T14:18:29+00:00Added an answer on May 26, 2026 at 2:18 pm

    have each DatabaseIdentifier keep a set of locks keyed to ActivityIdentifiers that it owns

    so you can call

    public void doActivity(DatabaseIdentifier dbID, ActivityIdentifier actID) {    
        synchronized( dbID.getLock(actID) ) { 
           // Do an action that can be guaranteed thread-safe per unique
           // combination of dbIT and actID, but needs to share a 
           // lock if they are both the same.
        }
    }
    

    then you only need a (short) lock on the underlying collection (use a ConcurrentHashMap) in dbID

    in other words

    ConcurrentHashMap<ActivityIdentifier ,Object> locks = new...
    public Object getLock(ActivityIdentifier actID){
        Object res = locks.get(actID); //avoid unnecessary allocations of Object
    
        if(res==null) {
            Object newLock = new Object();
            res = locks.puIfAbsent(actID,newLock );
            return res!=null?res:newLock;
        } else return res;
    }
    

    this is better than locking the full action on dbID (especially when its a long action) but still worse than your ideal scenario

    update in responce to comments about EnumMap

    private final EnumMap<ActivityIdentifier ,Object> locks;
    
    /**
      initializer ensuring all values are initialized 
    */
    {
        EnumMap<ActivityIdentifier ,Object> tmp = new EnumMap<ActivityIdentifier ,Object>(ActivityIdentifier.class)
        for(ActivityIdentifier e;ActivityIdentifier.values()){
            tmp.put(e,new Object());
        }
        locks = Collections.unmodifiableMap(tmp);//read-only view ensures no modifications will happen after it is initialized making this thread-safe
    }
    
    
    public Object getLock(ActivityIdentifier actID){
        return locks.get(actID);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have thousands of HTML files to process using Groovy/Java and I need to
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
I'm using v2.0 of ClassTextile.php, with the following call: $testimonial_text = $textile->TextileRestricted($_POST['testimonial']); ... and
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
We're building an app, our first using Rails 3, and we're having to build
I'm making a simple page using Google Maps API 3. My first. One marker
We are using XSLT to translate a RIXML file to XML. Our RIXML contains
i got an object with contents of html markup in it, for example: string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.