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 6107165
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T14:09:32+00:00 2026-05-23T14:09:32+00:00

Ex 1) public void addName(String name) { synchronized(this) { lastName = name; nameCount++; }

  • 0

Ex 1)

public void addName(String name) {
    synchronized(this) {
        lastName = name;
        nameCount++;
    }
    nameList.add(name);
}

Ex 2)

public class MsLunch {
    private long c1 = 0;
    private long c2 = 0;
    private Object lock1 = new Object();
    private Object lock2 = new Object();

    public void inc1() {
        synchronized(lock1) {
            c1++;
        }
    }

    public void inc2() {
        synchronized(lock2) {
            c2++;
        }
    }
}

I got these two java code from java website but I don’t clearly see the difference between these two. Could you guys give more explanation which case I should use this interchangeably ? Thanks in advance

  • 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-23T14:09:33+00:00Added an answer on May 23, 2026 at 2:09 pm

    There are two differences:

    • The first example locks on this instead of a private reference. I view this as a bad idea in general – it means other code could also lock on the same monitor, which makes it harder to reason about your code. Unless you want other code to be able to acquire a lock on the same monitor (in which case I’d usually expose a monitor explicitly for that purpose), why put yourself at the mercy of other code? The lock should be an implementation detail in most cases, but making it a public reference (which this is effectively) makes that implementation detail visible to the world.
    • The second example shows two methods within the same class locking on different references. That means two threads could call inc1 and inc2 concurrently. If there were multiple methods in the first example, all locking on this, then only one thread could enter any of those methods at a time.

    I typically use a single lock for everything within a single class unless I have good reason to believe that there are going to be lots of independent operations working on only part of the state of the class – in which case that suggests the class may be too big to start with.

    I also make my “lock variables” final, as you pretty much never want to be able to change them during the lifetime of an object.

    So if I really wanted to use locks, I’d probably end up writing the second example as:

    public class MsLunch {
        private long c1 = 0;
        private long c2 = 0;
        private final Object lock = new Object();
    
        public void inc1() {
            synchronized(lock) {
                c1++;
            }
        }
    
        public void inc2() {
            synchronized(lock) {
                c2++;
            }
        }
    }
    

    However, I’d also consider:

    • Not making the instance methods thread-safe to start with. I find it’s relatively rare that a single instance of a class will be used from multiple threads concurrently. (Static methods should usually be thread-safe though.)
    • Using AtomicLong instead of locking. Often using a higher-level concept instead of threading primitives can make your code simpler to understand and more efficient.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

#include<iostream> class name { public: int a; name():a(0){}; }; void add(name * pname) {
public void valueChanged(TreeSelectionEvent event) { //Add images depending on selection. String selection = navigation.getLastSelectedPathComponent().toString();
class Customer { public string ID { get; set; } public string Name {
public void printSummaryForPatient(String name){ Patient p = findPatient(name); p.printPatientSummary(); p.computeBMI(); } My method to
Say you have the following java bean: public class MyBean { private List<String> names
public void test() { List<int> list = new List<int>(); list.Add(1); list.Add(2); list.Add(3); for (int
public void EatDinner(string appetizer, string mainCourse, string dessert) { try { // Code }
public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { ... // Create
public abstract class Master { public void printForAllMethodsInSubClass() { System.out.println (Printing before subclass method
public void RestoreDatabase(String databaseName, String filePath, String serverName, String userName, String password, String dataFilePath,

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.