简体   繁体   中英

How to get make thread class instance if they are cached for next time

I have a context class. So I create an instance of a class. Since this class performs tough and costly mathematical operation I don't want to do it every time. So I am caching the class.

What if as I am creating a new instance what if another thread comes and get the same instance from the cache?

Is there any solution to this problem...?

Since you have not mentioned any code, the simplest suggestion is make your class Immutable . This means the state of class, once initialized cannot be changed. Request you to post some sample/representative code.

Depends on cache implementation. Highly depends on which parts of it you can control.

I believe you are talking about protecting your cache from race conditions . Race conditions happen when two or more threads are accessing a shared resource (in this case your cache) at the same time without proper protection.

There are many ways that you can protect your cache from improper multithreaded access. Without having the details or showing us some code, it's hard to be specific but consider some of the following techniques.

  1. Use of the synchronized keyword of course could help protect the cache from race conditions. The thread adding the instance of your class to cache would synchronize on the cache when it is inserted. Threads getting the instance from the cache would synchronize as well.

  2. If the instance of your class should only be used by one thread at a time then you could use a BlockingQueue with a size of one. The instance of your class could be added to the queue and the threads would wait until one gets the instance. When done it would put it back in the BlockingQueue letting the next thread get the class.

  3. Make sure that the instance of your class is fully initialized when it is put into the cache.

If you edit your question and provide a code sample or more details we can help you better.

You could create a thread-local cache to avoid sharing cached instances with different threads:

class CostyThingCache { 

    static ThreadLocal<CostyClass> cache = new ThreadLocal<CostyClass>() {

        // This gets called once ever per thread:
        @Override
        protected CostyClass initialValue() {
            return new CostyClass();
        }

    };

    static CostyClass getCostyThing() {
        return cache.get();
    }

}

Alternatively, serialize (synchronize) access to the costy object and create only one of them. Which of these alternatives is better depends totally on what you're actually doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM