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

  • SEARCH
  • Home
  • 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 7592989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T21:03:06+00:00 2026-05-30T21:03:06+00:00

I have the following code: Note: I simplified the code as much as possible

  • 0

I have the following code:
Note: I simplified the code as much as possible for readability.
If I forgot any critical pieces let me know.

public class User(){

    private Relations relations;

    public User(){
        relations = new Relations(this);
    }   

    public getRelations(){
        return relations;
    }
}


public class Relations(){

    private User user;

    public Relations(User user){
        this.user = user;
    }

    public synchronized void setRelation(User user2){
        Relations relations2 = user2.getRelations();

        synchronized(relations2){

            storeRelation(user2);

            if(!relations2.hasRelation(user))
                relations2.setRelation(user);
        }
    }   

    public synchronized boolean hasRelation(User user2){
        ... // Checks if this relation is present in some kind of collection
    }

    /*Store this relation, unless it is already present*/
    private void storeRelation(User user2){
        ... // Stores this relation in some kind of collection
    }
}

This implementation should make sure that for all Relations x, y with:

x.user = u_x
y.user = u_y

the following invariant holds:

x.hasRelation( u_y ) <=> y.hasRelation( u_x )

I believe that holds for the code stated above?

Note: It does of course not hold during the execution of setRelation(..),
but at that moment the locks for both relations involved are
held by the executing thread so no other thread can read the
hasRelation(..) of one of the relations involved.

Assuming that this holds i believe there is still a potential deadlock-risk.
Is that correct? And if it is, how can I solve it?
I think i would need to obtain both locks in setRelation(..) atomically somehow.

  • 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-30T21:03:07+00:00Added an answer on May 30, 2026 at 9:03 pm

    You are correct on both points: your invariant does hold (assuming that I understand correctly what your method-names mean and so on, and assuming that by if(!relations.hasRelation(user)) relations2.setRelation(user2); you meant to write if(!relations2.hasRelation(user)) relations2.setRelation(user);), but you do have the risk of a deadlock: if one thread needs to obtain a lock on x and then on y, and another thread needs to obtain a lock on y and then on x, then there’s a risk that each thread will succeed in getting its first lock, and thereby prevent the other from getting its second lock.

    One solution is to enforce a strict universal ordering for getting locks on Relations instances. What you do is, you add a constant integer field lockOrder:

    private final int lockOrder;
    

    and a static integer field currentLockOrder:

    private static int currentLockOrder = 0;
    

    and every time you create a Relations instance, you set its lockOrder to the current value of currentLockOrder, and increment said:

    public Relations()
    {
        synchronized(Relations.class) // a lock on currentLockOrder
        {
            lockOrder = currentLockOrder;
            ++currentLockOrder;
        }
    }
    

    such that every instance of Relations will have a distinct, immutable value for lockOrder. Your setRelation method would then obtain locks in the specified order:

    public void setRelation(final User thatUser)
    {
        final Relations that = thatUser.getRelations();
    
        synchronized(lockOrder < that.lockOrder ? this : that)
        {
            synchronized(lockOrder < that.lockOrder ? that : this)
            {
                storeRelation(thatUser);
    
                if(! that.hasRelation(user))
                    that.storeRelation(user);
            }
        }
    }
    

    thereby ensuring that if two threads both need to get locks on both x and y, then either they’ll both first get locks on x, or they’ll both first get locks on y. Either way, no deadlock will occur.

    Note, by the way, that I changed setRelation to storeRelation. setRelation would work, but why add that complexity?

    Also, there’s still one thing I don’t get: how come x.setRelation(u_y) calls x.storeRelation(u_y) unconditionally, but calls y.setRelation(u_x) (or y.storeRelation(u_x)) only if y doesn’t already have the relationship? It doesn’t make sense. It seems like either both checks are needed, or neither check is. (Without seeing the implementation of Relations.storeRelation(...), I can’t guess which of those is the case.)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I Have following code: Controller: public ActionResult Step1() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public
I have following code: public static void ProcessStep(Action action) { //do something here if
I have the following code in my template (please note the if statement): {%
In a Rails application using prototype, I have the following (simplified) code in my
i have the following code in c#. I'm using ASP.NET MVC 3. public override
I have the following code in a PHP file called via Ajax (note -
I have the following HTML w/Javascript code (note: this only works in Internet Explorer):
I currently have the following code for the POST to edit a customer note.
If I have the following code (simplified version of the problem): class TestA {
I have the following code namespace A { [DataContract] public class CustomClass {} }

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.