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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T18:28:07+00:00 2026-05-27T18:28:07+00:00

An interviewer asked me that How can you implement a class Foo, where you

  • 0

An interviewer asked me that

How can you implement a class Foo, where you will be able to count
instances of that class. There are more threads which are creating
instance of that class Foo.

I replyed that with following code

public class Foo {
    private static int count = 0;

    public Foo() {
    incrementCount();
    }

    public void incrementCount() {
        synchronize (Foo.class) {
            count++;
        }
    }
} 

She again asked me that

If a thread ends, counter should be decrement, how can you do that?

I didn’t answer this question.

I know about finalize() method, but it depends on Garbage collector that when this method will be called, even if we override finalize().

I have no solution yet, can you explain it please?

  • 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-27T18:28:07+00:00Added an answer on May 27, 2026 at 6:28 pm

    You could wrap the Thread’s Runnable inside another Runnable that would decrement the counter:

    Thread createThread(final Runnable r) {
      return new Thread(new Runnable() {
        @Override public void run() {
          try {
            r.run();
          } finally {
            Foo.decrementCounter();
          }
        }
      });
    }
    

    The problem with this is if the Runnable r creates multiple instances of Foo. You’d have to somehow track how many instances the thread created. You could do so using a ThreadLocal<Integer>, and then call decrementCounter(), in the finally block, the appropriate number of times. See below for a complete, working example.

    If you can avoid it, you should not rely on the behavior of the GC as it is quite impredictable! If you insist into dealing with the Garbage Collector, then you should use reference queues — and to use it properly, you should study the concept of object reachability: http://docs.oracle.com/javase/7/docs/api/index.html?java/lang/ref/package-summary.html

    As a final note, if I were interviewing you, I’d try to make you realize that the code you propose does not perfectly satisfy the requirements: you’d have to make the class final, or the method incrementCount() final or private. Or, easier, you could increment the count in an instance initializer block: no need to think about methods being overriden in subclasses or newly added constructors not incrementing the count.


    A complete example:

    public class Foo {
      private static final AtomicInteger liveInstances = new AtomicInteger(0);
      private static final ThreadLocal<Integer> threadLocalLiveInstances = new ThreadLocal<Integer>() {
        @Override protected Integer initialValue() { return 0; }
      }
    
      // instance initializer (so you won't have problems with multiple constructors or virtual methods called from them):
      {
        liveInstances.incrementAndGet();
        threadLocalLiveInstances.set(threadLocalLiveInstances.get() + 1);
      }
    
      public static int getTotalLiveInstances() {
        return liveInstances.get();
      }
    
      public static int getThreadLocalLiveInstances() {
        return threadLocalLiveInstances.get();
      }
    
      public static void decrementInstanceCount() {
        threadLocalLiveInstances.set(threadLocalLiveInstances.get() - 1);
        liveInstaces.decrementAndGet();
      }
    
      // ... rest of the code of the class ...
    }
    
    class FooCountingThreadFactory implements ThreadFactory {
      public Thread newThread(final Runnable r) {
        return new Thread(new Runnable() {
          @Override public void run() {
            try {
              r.run();
            } finally {
              while (Foo.getThreadLocalLiveInstances() > 0) {
                Foo.decrementInstanceCount();
              }
            }
          }
        });
      }
    }
    

    This way, you can feed this ThreadFactory to a thread pool, for example, or you can use it yourself when you want to build a thread: (new FooCountingThreadFactory()).newThread(job);

    Anyways, there’s still a problem with this approach: if a thread creates instances of Foo and stores them on global scope (read: static fields), then these instances will still be alive after the thread has died, and the counter will all the same be decremented to 0.

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

Sidebar

Related Questions

In my last job interview I was asked how to implement a class which
How can we Implement a c++ class such that it allows us to add
I was asked by an interviewer that how would I implement tail (yes, the
Recently I was asked in an interview that, can an Interface be considered as
a question that a co-interviewer asked in interviews. I always thought it was a
Yesterday in my interview I was asked this question. (At that time I was
I was asked in an interview that what is the usage of virtual keyword
Recently I faced few interview questions.The interviewer asked the to give the detailed answer.
Last day I have been interviewed and the interviewer asked me a) what is
I had telephone interview question yesterday. The interviewer asked me if I had faced

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.