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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 8, 20262026-06-08T08:28:05+00:00 2026-06-08T08:28:05+00:00

I have the following use case: I have a class that has two methods

  • 0

I have the following use case: I have a class that has two methods m1 and m2. Normally, m1() need not be synchronized, however if someone calls m2(), then m1() needs to be synchronized as long as m2() is being executed. In order to achieve this, I came up with the following code. Could you pl. comment on it and suggest better options?

Note: I realize that this situation is not practical, because e.g. if some thread is in the middle of m1 and some other thread calls m2, then there would be a problem (and it would be great if someone points out how to take care of that); nonetheless I found thinking about this interesting.

public class DynamicSync
{
    volatile MyLock lock;   
    private final MyLock DUMMY_LOCK = new DummyMyLock();
    private final MyLock SYNCHRONIZED_LOCK = new SynchronizedMyLock();

    public DynamicSync()
    {
        lock = DUMMY_LOCK;
    }

    public void dynamicallySynchronizedMethod() // this is method m1() in the question above
    {
        lock.lock();
        // some logic
        lock.unlock();
    }

    public void setLockAndExecuteLogic() // this is method m2() in the question above
    {       
        synchronized(SYNCHRONIZED_LOCK)
        {
            lock = SYNCHRONIZED_LOCK;       
            // some logic                               
        }
    }

    interface MyLock
    {
        void lock();
        void unlock();
    }

    class DummyMyLock implements MyLock
    {
        @Override
        public void lock() 
        {
        }

        @Override
        public void unlock() 
        {
        }       
    }

    class SynchronizedMyLock implements MyLock
    {
        @Override
        public synchronized void lock() 
        {
            // no op
        }

        @Override
        public void unlock() 
        {
            lock = DUMMY_LOCK;
        }       
    }
}

EDIT: the actual problem is: I’m designing an object pool, where I need to know how many and which of the objects are given out, and how many remain. So I was thinking of maintaining two collections: origSet would be a HashSet that contains all the objects and dynaSet would be a ConcurrentSkipListSet from which I give out objects and put them back in. If I need to figure out the difference between origSet and dynaSet at an instant, I need to ‘freeze’ dyanSet till the difference is calculated. But getting this difference will be a very infrequent operation, hence my question.

  • 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-06-08T08:28:08+00:00Added an answer on June 8, 2026 at 8:28 am

    Java has an extensive API for multi-threading Synchronization so I warmly suggest you don’t try writing anything like that if you do not want to die suffering in the hell of race conditions.

    If you have already read the book http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz , then you should now:

    • The best solution would be to stay immutable and kick thread-synchronization problems out of your world.
    • If you can’t stay immutable, stay defensive and make defensive copies of your internal properties when sharing them. This is called “safe publication”
    • If you can’t stay immutable, try at least to use concurrent collections to make your life easier.
    • If you really need to develop your own locking system, please have a look to Java ReadWriteLock.

    According to your last comments, I have two proposals:

    1. If you just need to get the size of the collection, but not doing anything on the collection using the data. I do not think you need to synchronize at all. Your call to getDynaSize will return the last available value: not sure it is the current one when you will use it, but unless you clearly see race conditions inside your processing method, do not synchronize at all. (maybe you want to give us more details?)

    2. If you really need to lock, use a ReadWriteLock,

      • It is a reentrant lock, so that if a Thread has already acquired, a consequent try to acquire will be non blockin, it allows for multiple readers to enter, but only one writer.
      • You need to acquire the writer every time you need to add an element to your concurrent collection, and release it after adding it. And also, you have to acquire the writer lock before getting the size, and release it after having completed the processing
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have the following use case: There's a class called Template and with that
I have following code snippet that i use to compile class at the run
I have following use-case: there are several assemblies decorated with ProtoContract classes and I
Say I have a trait that has two lists. Sometimes I'm interested in the
I have the following code: use Imager::Screenshot 'screenshot'; my $img = screenshot(hwnd => 'active',
I have the following code: use strict; function isDefined(variable) { return (typeof (window[variable]) ===
I have the following code I use to insert form data into a single
I have the following test code use Data::Dumper; my $hash = { foo =>
I have following Image as src in ImageView. I use this as background image.
I have following webservice: [webmethod] public string MakeReservation(?? PassengersInfo)//what data type use for PassengerInfo

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.