class Cache implements Ehcache, StoreListener {

    public void initialise() {
        synchronized (this) {
            if (!cacheStatus.canInitialize()) {
                throw new IllegalStateException("Cannot initialise the " + configuration.getName()
                        + " cache because its status is not STATUS_UNINITIALISED");
            }

            if (configuration.getMaxElementsInMemory() == 0) {
                LOG.warn("Cache: " + configuration.getName() +
                        " has a maxElementsInMemory of 0.  " +
                        "In Ehcache 2.0 this has been changed to mean a store" +
                        " with no capacity limit. Set it to 1 if you want" +
                        " no elements cached in memory");
            }

            ReadWriteCopyStrategy<Element> copyStrategy = null;
            if (configuration.getTransactionalMode().isTransactional()) {
                configuration.getCopyStrategyConfiguration().setCopyStrategyInstance(null);
                copyStrategy = configuration.getCopyStrategyConfiguration().getCopyStrategyInstance();
                configuration.getCopyStrategyConfiguration().setCopyStrategyInstance(new ImmutableValueElementCopyStrategy());
            }

            if (configuration.getTransactionalMode().isTransactional()
                && configuration.isTerracottaClustered()
                && configuration.getTerracottaConfiguration().getValueMode() != TerracottaConfiguration.ValueMode.SERIALIZATION) {
                throw new CacheException("To be transactional, a Terracotta clustered cache needs to be in Serialization value mode");
            }

            final Store store;
            if (isTerracottaClustered()) {
                final Consistency consistency = getCacheConfiguration().getTerracottaConfiguration().getConsistency();
                final boolean coherent = getCacheConfiguration().getTerracottaConfiguration().isCoherent();
                if (getCacheConfiguration().isOverflowToOffHeap()) {
                    throw new InvalidConfigurationException(
                            "Terracotta clustered caches with local overflow to offheap are not supported yet."
                                    + " You can fix this by disabling overflow to offheap for clustered caches.");
                }
                if (getCacheConfiguration().getTerracottaConfiguration().isSynchronousWrites() && consistency == Consistency.EVENTUAL) {
                    throw new InvalidConfigurationException(
                            "Terracotta clustered caches with eventual consistency and synchronous writes are not supported yet."
                                    + " You can fix this by either making the cache in 'strong' consistency mode "
                                    + "(<terracotta consistency=\"strong\"/>) or turning off synchronous writes.");
                }
                if (getCacheConfiguration().getTransactionalMode().isTransactional() && consistency == Consistency.EVENTUAL) {
                    throw new InvalidConfigurationException("Consistency should be " + Consistency.STRONG
                            + " when cache is configured with transactions enabled. "
                            + "You can fix this by either making the cache in 'strong' consistency mode "
                            + "(<terracotta consistency=\"strong\"/>) or turning off transactions.");
                }
                if (getCacheConfiguration().getTransactionalMode().isTransactional()
                        && !getCacheConfiguration().getTransactionalMode().equals(CacheConfiguration.TransactionalMode.XA_STRICT)
                        && getCacheConfiguration().getTerracottaConfiguration().isNonstopEnabled()) {
                    LOG.warn("Cache: " + configuration.getName() + " configured both NonStop and transactional non xa_strict."
                            + " NonStop features won't work for this cache!");
                }
                if ((coherent && consistency == Consistency.EVENTUAL) || (!coherent && consistency == Consistency.STRONG)) {
                    throw new InvalidConfigurationException("Coherent and consistency attribute values are conflicting. "
                            + "Please remove the coherent attribute as its deprecated.");
                }


                if (!getCacheConfiguration().getTerracottaConfiguration().isStorageStrategySet()) {
                    getCacheConfiguration().getTerracottaConfiguration().storageStrategy(
                            TerracottaClient.getTerracottaDefaultStrategyForCurrentRuntime(getCacheConfiguration()));
                }

                Store tempStore = cacheManager.createTerracottaStore(this);
                if (!(tempStore instanceof TerracottaStore)) {
                    throw new CacheException(
                            "CacheManager should create instances of TerracottaStore for Terracotta Clustered caches instead of - "
                                    + (tempStore == null ? "null" : tempStore.getClass().getName()));
                }
                TerracottaStore terracottaStore = (TerracottaStore) makeXaStrictTransactionalIfNeeded(tempStore, copyStrategy);

                NonstopConfiguration nonstopConfig = getCacheConfiguration().getTerracottaConfiguration().getNonstopConfiguration();
                // freeze the config whether nonstop is enabled or not
                if (nonstopConfig != null) {
                    nonstopConfig.freezeConfig();
                }
                if (getCacheConfiguration().getTerracottaConfiguration().isNonstopEnabled()) {
                    nonstopActiveDelegateHolder.terracottaStoreInitialized(terracottaStore);
                    store = nonstopActiveDelegateHolder.getNonstopStore();
                } else {
                    store = terracottaStore;
                }
            } else if (getCacheConfiguration().isOverflowToOffHeap()) {
                try {
                    Class<Store> storeClass = ClassLoaderUtil.loadClass(OFF_HEAP_STORE_CLASSNAME);
                    try {
                        store = makeXaStrictTransactionalIfNeeded((Store) storeClass.getMethod("create", Ehcache.class, String.class)
                                .invoke(null, this, diskStorePath), copyStrategy);
                    } catch (NoSuchMethodException e) {
                        throw new CacheException("Cache: " + configuration.getName() + " cannot find static factory"
                                + " method create(Ehcache, String)" + " in store class " + OFF_HEAP_STORE_CLASSNAME, e);
                    } catch (InvocationTargetException e) {
                        Throwable cause = e.getCause();
                        if (cause instanceof CacheException) {
                            throw (CacheException) cause;
                        } else {
                            throw new CacheException("Cache: " + configuration.getName() + " cannot instantiate store "
                                    + OFF_HEAP_STORE_CLASSNAME, cause);
                        }
                    } catch (IllegalAccessException e) {
                        throw new CacheException("Cache: " + configuration.getName() + " cannot instantiate store "
                                + OFF_HEAP_STORE_CLASSNAME, e);
                    }
                } catch (ClassNotFoundException e) {
                    throw new CacheException("Cache " + configuration.getName()
                            + " cannot be configured because the off-heap store class could not be found. "
                            + "You must use an enterprise version of Ehcache to successfully enable overflowToOffHeap.");
                }
            } else {
                if (useClassicLru && configuration.getMemoryStoreEvictionPolicy().equals(MemoryStoreEvictionPolicy.LRU)) {
                    Store disk = createDiskStore();
                    store = makeXaStrictTransactionalIfNeeded(new LegacyStoreWrapper(
                            new LruMemoryStore(this, disk), disk, registeredEventListeners, configuration), copyStrategy);
                } else {
                    if (configuration.isDiskPersistent()) {
                        store = makeXaStrictTransactionalIfNeeded(DiskPersistentStore.create(this, diskStorePath), copyStrategy);
                    } else if (configuration.isOverflowToDisk()) {
                        store = makeXaStrictTransactionalIfNeeded(OverflowToDiskStore.create(this, diskStorePath), copyStrategy);
                    } else {
                        store = makeXaStrictTransactionalIfNeeded(MemoryOnlyStore.create(this, diskStorePath), copyStrategy);
                    }
                }
            }

            /* note: this isn't part of makeXaStrictTransactionalIfNeeded() as only xa_strict supports NonStop, meaning that only
             * that transactional store can be wrapped by NonStopStore. Other TX modes have to wrap the NonStop store due to their
             * lack of NonStop support (ie: lack of transaction context suspension/resuming).
             */
            if (configuration.isXaTransactional()) {
                SoftLockFactory softLockFactory = cacheManager.createSoftLockFactory(this);
                LocalTransactionStore localTransactionStore = new LocalTransactionStore(getCacheManager().getTransactionController(),
                        softLockFactory, this, store, copyStrategy);
                this.compoundStore = new JtaLocalTransactionStore(localTransactionStore, transactionManagerLookup,
                        cacheManager.getTransactionController());
            } else if (configuration.isLocalTransactional()) {
                SoftLockFactory softLockFactory = cacheManager.createSoftLockFactory(this);
                this.compoundStore = new LocalTransactionStore(getCacheManager().getTransactionController(), softLockFactory, this, store,
                        copyStrategy);
            } else {
                this.compoundStore = store;
            }


            Map<String, AttributeExtractor> extractors = new HashMap<String, AttributeExtractor>();
            for (SearchAttribute sa : configuration.getSearchAttributes().values()) {
                extractors.put(sa.getName(), sa.constructExtractor());
            }

            compoundStore.setAttributeExtractors(extractors);


            this.cacheWriterManager = configuration.getCacheWriterConfiguration().getWriteMode().createWriterManager(this);
            initialiseCacheWriterManager(false);

            cacheStatus.changeState(Status.STATUS_ALIVE);

            initialiseRegisteredCacheExtensions();
            initialiseRegisteredCacheLoaders();
            initialiseRegisteredCacheWriter();

            // initialize live statistics
            // register to get notifications of
            // put/update/removeInternal/expiry/eviction
            getCacheEventNotificationService().registerListener(liveCacheStatisticsData);
            // set up default values
            liveCacheStatisticsData.setStatisticsAccuracy(Statistics.STATISTICS_ACCURACY_BEST_EFFORT);
            liveCacheStatisticsData.setStatisticsEnabled(configuration.getStatistics());

            // register the sampled cache statistics
            this.registerCacheUsageListener(sampledCacheStatistics);

            if (isTerracottaClustered()) {
                // create this to be sure that it's present on each node to receive clustered events,
                // even if this node is not sending out its events
                cacheManager.createTerracottaEventReplicator(this);
            }

            Object context = compoundStore.getInternalContext();
            if (context instanceof CacheLockProvider) {
                lockProvider = (CacheLockProvider) context;
            } else {
                this.lockProvider = new StripedReadWriteLockSync(StripedReadWriteLockSync.DEFAULT_NUMBER_OF_MUTEXES);
            }
        }

        compoundStore.addStoreListener(this);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Initialised cache: " + configuration.getName());
        }

        if (disabled) {
            LOG.warn("Cache: " + configuration.getName() + " is disabled because the " + NET_SF_EHCACHE_DISABLED
                    + " property was set to true. No elements will be added to the cache.");
        }
    }

    public  Cache(CacheConfiguration cacheConfiguration);
    public  Cache(CacheConfiguration cacheConfiguration,
                 RegisteredEventListeners registeredEventListeners,
                 BootstrapCacheLoader bootstrapCacheLoader);
    public  Cache(String name, int maxElementsInMemory, boolean overflowToDisk,
                 boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds);
    public  Cache(String name,
                 int maxElementsInMemory,
                 boolean overflowToDisk,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds);
    public  Cache(String name,
                 int maxElementsInMemory,
                 MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
                 boolean overflowToDisk,
                 String diskStorePath,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds,
                 RegisteredEventListeners registeredEventListeners);
    public  Cache(String name,
                 int maxElementsInMemory,
                 MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
                 boolean overflowToDisk,
                 String diskStorePath,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds,
                 RegisteredEventListeners registeredEventListeners,
                 BootstrapCacheLoader bootstrapCacheLoader);
    public  Cache(String name,
                 int maxElementsInMemory,
                 MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
                 boolean overflowToDisk,
                 String diskStorePath,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds,
                 RegisteredEventListeners registeredEventListeners,
                 BootstrapCacheLoader bootstrapCacheLoader,
                 int maxElementsOnDisk);
    public  Cache(String name,
                 int maxElementsInMemory,
                 MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
                 boolean overflowToDisk,
                 String diskStorePath,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds,
                 RegisteredEventListeners registeredEventListeners,
                 BootstrapCacheLoader bootstrapCacheLoader,
                 int maxElementsOnDisk,
                 int diskSpoolBufferSizeMB);
    public  Cache(String name,
                 int maxElementsInMemory,
                 MemoryStoreEvictionPolicy memoryStoreEvictionPolicy,
                 boolean overflowToDisk,
                 String diskStorePath,
                 boolean eternal,
                 long timeToLiveSeconds,
                 long timeToIdleSeconds,
                 boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds,
                 RegisteredEventListeners registeredEventListeners,
                 BootstrapCacheLoader bootstrapCacheLoader,
                 int maxElementsOnDisk,
                 int diskSpoolBufferSizeMB,
                 boolean clearOnFlush);
    public  Cache(String name, int maxElementsInMemory, MemoryStoreEvictionPolicy memoryStoreEvictionPolicy, boolean overflowToDisk,
                 String diskStorePath, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds, boolean diskPersistent,
                 long diskExpiryThreadIntervalSeconds, RegisteredEventListeners registeredEventListeners,
                 BootstrapCacheLoader bootstrapCacheLoader, int maxElementsOnDisk, int diskSpoolBufferSizeMB, boolean clearOnFlush,
                 boolean isTerracottaClustered, String terracottaValueMode, boolean terracottaCoherentReads);

}