Creates the tile cache with the AndroidUtil helper
420977
@Override
    protected void createTileCaches() {
        this.tileCaches.add(AndroidUtil.createTileCache(this, getPersistableId(),
                this.mapView.getModel().displayModel.getTileSize(), this.getScreenRatio(),
                this.mapView.getModel().frameBufferModel.getOverdrawFactor()));
    }
393085
private void cutCurrentCache() {

		final File lock=Configuration.getInstance().getOsmdroidTileCache();
		synchronized (lock) {

			if (mUsedCacheSpace > Configuration.getInstance().getTileFileSystemCacheTrimBytes()) {

				Log.d(IMapView.LOGTAG,"Trimming tile cache from " + mUsedCacheSpace + " to "
						+ Configuration.getInstance().getTileFileSystemCacheTrimBytes());

				final List<File> z = getDirectoryFileList(Configuration.getInstance().getOsmdroidTileCache());

				// order list by files day created from old to new
				final File[] files = z.toArray(new File[0]);
				Arrays.sort(files, new Comparator<File>() {
					@Override
					public int compare(final File f1, final File f2) {
						return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified());
					}
				});

				for (final File file : files) {
					if (mUsedCacheSpace <= Configuration.getInstance().getTileFileSystemCacheTrimBytes()) {
						break;
					}

					final long length = file.length();
					if (file.delete()) {
						if (Configuration.getInstance().isDebugTileProviders()){
							Log.d(IMapView.LOGTAG,"Cache trim deleting " + file.getAbsolutePath());
						}
						mUsedCacheSpace -= length;
					}
				}

				Log.d(IMapView.LOGTAG,"Finished trimming tile cache");
			}
		}
	}
989889
function(prepareTiles, rendererHelper,
        visited, flowEvents, sortedRasterizerSlices) {
      if (!prepareTiles.args.prepare_tiles_id)
        return;

      if (!rendererHelper || !rendererHelper.rasterWorkerThreads)
        return;

      var rasterWorkerThreads = rendererHelper.rasterWorkerThreads;
      var prepare_tile_id = prepareTiles.args.prepare_tiles_id;
      var pendingEventQueue = [];

      // Collect all the rasterizer tasks. Return the cached copy if possible.
      if (sortedRasterizerSlices.length === 0)
        this.sortRasterizerSlices(rasterWorkerThreads, sortedRasterizerSlices);

      // TODO(yuhao): Once TaskSetFinishedTaskImpl also get the prepare_tile_id
      // we can simply track by checking id rather than counting.
      var numFinishedTasks = 0;
      var RASTER_TASK_TITLE = 'RasterizerTaskImpl::RunOnWorkerThread';
      var IMAGEDECODE_TASK_TITLE = 'ImageDecodeTaskImpl::RunOnWorkerThread';
      var FINISHED_TASK_TITLE = 'TaskSetFinishedTaskImpl::RunOnWorkerThread';

      for (var i = 0; i < sortedRasterizerSlices.length; i++) {
        var task = sortedRasterizerSlices[i];

        if (task.title === RASTER_TASK_TITLE ||
            task.title === IMAGEDECODE_TASK_TITLE) {
          if (task.args.source_prepare_tiles_id === prepare_tile_id)
            this.addEntireSliceHierarchy(task.mostTopLevelSlice);
        } else if (task.title === FINISHED_TASK_TITLE) {
          if (task.start > prepareTiles.start) {
            pendingEventQueue.push(task.mostTopLevelSlice);
            if (++numFinishedTasks === 3)
              break;
          }
        }
      }

      // Trace PostTask from rasterizer tasks.
      while (pendingEventQueue.length != 0) {
        var event = pendingEventQueue.pop();

        this.addEntireSliceHierarchy(event);
        this.followSubsequentSlices(event, pendingEventQueue, visited,
            flowEvents);
      }
    }
811206
private static void initDesugarJar(@Nullable FileCache cache) throws IOException {
        if (isDesugarJarInitialized()) {
            return;
        }

        URL url = DesugarProcessBuilder.class.getClassLoader().getResource(DESUGAR_JAR);
        Preconditions.checkNotNull(url);

        Path extractedDesugar = null;
        if (cache != null) {
            try {
                String fileHash;
                try (HashingInputStream stream =
                             new HashingInputStream(Hashing.sha256(), url.openStream())) {
                    fileHash = stream.hash().toString();
                }
                FileCache.Inputs inputs =
                        new FileCache.Inputs.Builder(FileCache.Command.EXTRACT_DESUGAR_JAR)
                                .putString("pluginVersion", Version.ANDROID_GRADLE_PLUGIN_VERSION)
                                .putString("jarUrl", url.toString())
                                .putString("fileHash", fileHash)
                                .build();

                File cachedFile =
                        cache.createFileInCacheIfAbsent(
                                inputs, file -> copyDesugarJar(url, file.toPath()))
                                .getCachedFile();
                Preconditions.checkNotNull(cachedFile);
                extractedDesugar = cachedFile.toPath();
            } catch (IOException | ExecutionException e) {
                logger.error(e, "Unable to cache Desugar jar. Extracting to temp dir.");
            }
        }

        synchronized (desugarJar) {
            if (isDesugarJarInitialized()) {
                return;
            }

            if (extractedDesugar == null) {
                extractedDesugar = PathUtils.createTmpToRemoveOnShutdown(DESUGAR_JAR);
                copyDesugarJar(url, extractedDesugar);
            }
            desugarJar.set(extractedDesugar);
        }
    }
263374
def downloader(self):
        ''''''
        while self.tiles_pending() > 0:
            time.sleep(self.tile_delay)

            keys = sorted(self._download_pending.keys())

            # work out which one to download next, choosing by request_time
            tile_info = self._download_pending[keys[0]]
            for key in keys:
                if self._download_pending[key].request_time > tile_info.request_time:
                    tile_info = self._download_pending[key]

            url = tile_info.url(self.service)
            path = self.tile_to_path(tile_info)
            key = tile_info.key()

            try:
                if self.debug:
                    print("Downloading %s [%u left]" % (url, len(keys)))
                req = url_request(url)
                if url.find('google') != -1:
                    req.add_header('Referer', 'https://maps.google.com/')
                resp = url_open(req)
                headers = resp.info()
            except url_error as e:
                #print('Error loading %s' % url)
                if not key in self._tile_cache:
                    self._tile_cache[key] = self._unavailable
                self._download_pending.pop(key)
                if self.debug:
                    print("Failed %s: %s" % (url, str(e)))
                continue
            if 'content-type' not in headers or headers['content-type'].find('image') == -1:
                if not key in self._tile_cache:
                    self._tile_cache[key] = self._unavailable
                self._download_pending.pop(key)
                if self.debug:
                    print("non-image response %s" % url)
                continue
            else:
                img = resp.read()

            # see if its a blank/unavailable tile
            md5 = hashlib.md5(img).hexdigest()
            if md5 in BLANK_TILES:
                if self.debug:
                    print("blank tile %s" % url)
                    if not key in self._tile_cache:
                        self._tile_cache[key] = self._unavailable
                self._download_pending.pop(key)
                continue

            mp_util.mkdir_p(os.path.dirname(path))
            h = open(path+'.tmp','wb')
            h.write(img)
            h.close()
            try:
                os.unlink(path)
            except Exception:
                pass
            os.rename(path+'.tmp', path)
            self._download_pending.pop(key)
        self._download_thread = None
1308271
public static void generate(Elements elementUtils, Filer filer, SQLiteDatabaseSchema schema) throws IOException {
		String className = schema.getName();

		String dataSourceName = PREFIX + className;

		className = className.replaceAll(BindDataSourceBuilder.SUFFIX, SUFFIX);
		className = PREFIX + className;

		PackageElement pkg = elementUtils.getPackageOf(schema.getElement());
		String packageName = pkg.isUnnamed() ? "" : pkg.getQualifiedName().toString();

		AnnotationProcessorUtilis.infoOnGeneratedClasses(BindDataSource.class, packageName, className);

		//@formatter:off
		builder = TypeSpec.classBuilder(className).addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("I"))
				.addTypeVariable(TypeVariableName.get("U"))
				.addTypeVariable(TypeVariableName.get("R"));
		//@formatter:on

		// javadoc
		builder.addJavadoc("\n<p>\nSpecialized async task to make async database operation on activity\n</p>\n");
		builder.addJavadoc("\n<p>\nUnlike standard async task, for an instance of this class can be used many time.\n</p>\n");
		builder.addJavadoc("\n<p>\nWhen method <code>execute</code> is invoked, an inner async task is created.\n</p>\n\n");
		JavadocUtility.generateJavadocGeneratedBy(builder);
		builder.addJavadoc("@param I input param\n");
		builder.addJavadoc("@param U update param\n");
		builder.addJavadoc("@param R result param\n\n");
		builder.addJavadoc("@see $T\n", className(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)));
		builder.addJavadoc("@see $T\n", className(dataSourceName));
		builder.addJavadoc("@see $T\n", BindAsyncTaskType.class);

		// build constructors
		builder.addMethod(MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addStatement("this($T.READ)", BindAsyncTaskType.class)
				.addJavadoc("<p>\nWith this constructor, a read only database connection will be used\n</p>\n").build());

		builder.addMethod(
				MethodSpec.constructorBuilder().addModifiers(Modifier.PUBLIC).addJavadoc("<p>\nWith this constructor it is possible to specify which type of database use in async task\n</p>\n\n")
						.addJavadoc("@param mode allows to specify if and how open a data source connection\n").addParameter(BindAsyncTaskType.class, "mode").addCode("this.mode = mode;").build());

		// define fields
		{
			FieldSpec.Builder fieldSpec = FieldSpec.builder(BindAsyncTaskType.class, "mode", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Allows to specify how async task interacts with data source.\n\n");
			builder.addField(fieldSpec.build());
		}

		{
			ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.typeName("I"), TypeUtility.typeName("U"),
					TypeUtility.typeName("R"));
			FieldSpec.Builder fieldSpec = FieldSpec.builder(parameterizedTypeName, "asyncTask", Modifier.PROTECTED);
			fieldSpec.addJavadoc("Async task wrapped by this class\n\n");
			builder.addField(fieldSpec.build());
		}

		// build methods
		builder.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addJavadoc("Use this method for operations on UI-thread before start execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onExecute").returns(TypeUtility.typeName("R")).addParameter(TypeUtility.typeName(dataSourceName), "dataSource")
				.addJavadoc(
						"Method used to encapsulate operations on datasource\n\n@param dataSource\n\tuse it to retrieve DAO\n@return\n\tresult of operation (list, bean, etc) and execute transactions.\n")
				.addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT).addException(Throwable.class).build());
		builder.addMethod(MethodSpec.methodBuilder("onFinish").addParameter(TypeUtility.typeName("R"), "result").addModifiers(Modifier.PUBLIC).addModifiers(Modifier.ABSTRACT)
				.addJavadoc("Use this method for operations on UI-thread after execution\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onProgressUpdate").addModifiers(Modifier.PUBLIC).addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.typeName("U")), "update").addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
				.varargs().addJavadoc("Override this method to KRIPTON_DEBUG operation progress on UI-Thread\n").build());

		builder.addMethod(MethodSpec.methodBuilder("onError").addParameter(Throwable.class, "exception").addModifiers(Modifier.PUBLIC)
				.addJavadoc("This method is invoked when <code>onExecute</code> method generate an exception.\n@param exception exception generated\n")
				.addStatement("$T.error(exception.getMessage())", Logger.class).addStatement("exception.printStackTrace()").build());

		// method execute1
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("execute")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

			executeBuilder.addStatement("executeOnExecutor($T.SERIAL_EXECUTOR, params)", android.os.AsyncTask.class);
			builder.addMethod(executeBuilder.build());
		}

		// method execute2
		{
			MethodSpec.Builder executeBuilder = MethodSpec.methodBuilder("executeOnExecutor").addParameter(Executor.class, "executor")
					.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
							.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value", "$S", "unchecked").build()).build())
					.varargs(true).addModifiers(Modifier.PUBLIC).addJavadoc("Method to start operations.\n\n@param executor used executor\n@param data input\n");

		//@formatter:off
		TypeSpec.Builder anonymous = TypeSpec.anonymousClassBuilder("")
				.addSuperinterface(ParameterizedTypeName.get(TypeUtility.className(AsyncTask.class), TypeUtility.className("I"), TypeUtility.className("U"), TypeUtility.className("R")));
		anonymous.addMethod(MethodSpec.methodBuilder("onPreExecute").addModifiers(Modifier.PUBLIC).addAnnotation(Override.class).addStatement("$L.this.onPreExecute()",className).build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("doInBackground").addModifiers(Modifier.PUBLIC).returns(TypeUtility.typeName("R")).addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("I")), "params")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build()).varargs(true)
				.addStatement("$L dataSource=$L.getInstance()", dataSourceName, dataSourceName)
				.addStatement("R result=null")
				.addStatement("boolean needToOpened=false")
				.addCode("if (mode==$T.READ) { needToOpened=true; dataSource.openReadOnlyDatabase(); } else if (mode==$T.READ_WRITE) { needToOpened=true; dataSource.openWritableDatabase();}\n", BindAsyncTaskType.class,BindAsyncTaskType.class)
				//.addStatement("$T sqlite=readOnlyTask ? dataSource.getReadableDatabase() : dataSource.getWritableDatabase()", SQLiteDatabase.class)
				.beginControlFlow("try")
				.addStatement("result=onExecute(dataSource)")
				.nextControlFlow("catch(Throwable e)")
					.addStatement("onError(e)")
				.nextControlFlow("finally")
					.beginControlFlow("if (needToOpened)")
					.addStatement("dataSource.close()")
					.endControlFlow()
				.endControlFlow()
				.addStatement("return result").build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onProgressUpdate")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(ArrayTypeName.of(TypeUtility.className("U"))
						, "values")
						.addAnnotation(AnnotationSpec.builder(SuppressWarnings.class).addMember("value","$S", "unchecked").build())
						.build())
				.varargs(true)
				.addStatement("$L.this.onProgressUpdate(values)", className)
				.build());
		
		anonymous.addMethod(MethodSpec.methodBuilder("onPostExecute")
				.addModifiers(Modifier.PUBLIC)
				.addAnnotation(Override.class)
				.addParameter(ParameterSpec.builder(TypeUtility.className("R"), "result").build())
				.addStatement("$L.this.onFinish(result)",className)
				.build());
		//@formatter:on

		//@formatter:off
		executeBuilder.addStatement("asyncTask=$L", anonymous.build());		
		executeBuilder.addStatement("asyncTask.executeOnExecutor(executor, params)", anonymous.build());
		builder.addMethod(executeBuilder.build());		
					
		anonymous.addMethod(MethodSpec.methodBuilder("cancel")
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.FINAL)
				.addParameter(Boolean.TYPE, "mayInterruptIfRunning")
				.beginControlFlow("if (asyncTask!=null, args)")
				.addStatement("return asyncTask.cancel(mayInterruptIfRunning)")
				.endControlFlow()
				.addStatement("return false").build());
		}

		
		// build SimpleAsyncTask
		builder.addType(TypeSpec.classBuilder("Simple")
				.addJavadoc("Simple implementation of async task. It uses read only database.\n\n")
				.addJavadoc("@see $T\n", TypeUtility.typeName(className.replaceAll(SUFFIX, BindDaoFactoryBuilder.SUFFIX)))
				.addJavadoc("@see $T\n", TypeUtility.typeName(dataSourceName))
				.addModifiers(Modifier.PUBLIC)
				.addModifiers(Modifier.STATIC)
				.addModifiers(Modifier.ABSTRACT)
				.addTypeVariable(TypeVariableName.get("R"))
				.superclass(
						ParameterizedTypeName.get(TypeUtility.className(className),
								TypeUtility.className("Void"), 
								TypeUtility.className("Void"), 
								TypeUtility.className("R")
								)							
				)				
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task allowing user to decide which kind of operation can be done on datasource")
						.addParameter(BindAsyncTaskType.class, "mode")
						.addStatement("super(mode)").build())
				.addMethod(MethodSpec.constructorBuilder()
						.addModifiers(Modifier.PUBLIC)
						.addJavadoc("Create an simple async task for data source read only operation")
						.addStatement("super($T.READ)", BindAsyncTaskType.class).build())
				.build());		
		//@formatter:on

		TypeSpec typeSpec = builder.build();
		JavaWriterHelper.writeJava2File(filer, packageName, typeSpec);		
	}
753761
public static MemoryCache createMemoryCache(Context context, int memoryCacheSize) {
		if (memoryCacheSize == 0) {
			ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
			int memoryClass = am.getMemoryClass();
			if (hasHoneycomb() && isLargeHeap(context)) {
				memoryClass = getLargeMemoryClass(am);
			}
			memoryCacheSize = 1024 * 1024 * memoryClass / 8;
		}
		return new LruMemoryCache(memoryCacheSize);
	}
1215197
def _get_satellite_tile(self, x_tile, y_tile, z_tile):
        """"""
        cache_file = "mapscache/{}.{}.{}.jpg".format(z_tile, x_tile, y_tile)
        if cache_file not in self._tiles:
            if not os.path.isfile(cache_file):
                url = _IMAGE_URL.format(z_tile, x_tile, y_tile, _KEY)
                data = requests.get(url).content
                with open(cache_file, 'wb') as f:
                    f.write(data)
            self._tiles[cache_file] = [
                x_tile, y_tile, z_tile,
                ColourImageFile(self._screen, cache_file, height=_START_SIZE, dither=True,
                                uni=self._screen.unicode_aware),
                True]
            if len(self._tiles) > _CACHE_SIZE:
                self._tiles.popitem(False)
            self._screen.force_update()
1336235
@Override
	public boolean saveFile(final ITileSource pTileSource, final long pMapTileIndex,
			final InputStream pStream, final Long pExpirationTime) {

		final File file = getFile(pTileSource, pMapTileIndex);

		if (Configuration.getInstance().isDebugTileProviders()){
			Log.d(IMapView.LOGTAG, "TileWrite " + file.getAbsolutePath());
		}
		final File parent = file.getParentFile();
		if (!parent.exists() && !createFolderAndCheckIfExists(parent)) {
			return false;
		}

		BufferedOutputStream outputStream = null;
		try {
			outputStream = new BufferedOutputStream(new FileOutputStream(file.getPath()),
					StreamUtils.IO_BUFFER_SIZE);
			final long length = StreamUtils.copy(pStream, outputStream);

			mUsedCacheSpace += length;
			if (mUsedCacheSpace > Configuration.getInstance().getTileFileSystemCacheMaxBytes()) {
				cutCurrentCache(); // TODO perhaps we should do this in the background
			}
		} catch (final IOException e) {
			Counters.fileCacheSaveErrors++;
			return false;
		} finally {
			if (outputStream != null) {
				StreamUtils.closeStream(outputStream);
			}
		}
		return true;
	}
706448
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        createSharedPreferences();
        createMapViews();
        createTileCaches();
        checkPermissionsAndCreateLayersAndControls();
    }
1223127
def tilecache(self, event, *args, **kwargs):
        """"""
        request, response = event.args[:2]
        self.log(request.path, lvl=verbose)
        try:
            filename, url = self._split_cache_url(request.path, 'tilecache')
        except UrlError:
            return

        # self.log('CACHE QUERY:', filename, url)

        # Do we have the tile already?
        if os.path.isfile(filename):
            self.log("Tile exists in cache", lvl=verbose)
            # Don't set cookies for static content
            response.cookie.clear()
            try:
                yield serve_file(request, response, filename)
            finally:
                event.stop()
        else:
            # We will have to get it first.
            self.log("Tile not cached yet. Tile data: ", filename, url,
                     lvl=verbose)
            if url in self._tiles:
                self.log("Getting a tile for the second time?!", lvl=error)
            else:
                self._tiles += url
            try:
                tile, log = yield self.call(task(get_tile, url), "tcworkers")
                if log:
                    self.log("Thread error: ", log, lvl=error)
            except Exception as e:
                self.log("[MTS]", e, type(e))
                tile = None

            tile_path = os.path.dirname(filename)

            if tile:
                try:
                    os.makedirs(tile_path)
                except OSError as e:
                    if e.errno != errno.EEXIST:
                        self.log(
                            "Couldn't create path: %s (%s)" % (e, type(e)), lvl=error)

                self.log("Caching tile.", lvl=verbose)
                try:
                    with open(filename, "wb") as tile_file:
                        try:
                            tile_file.write(bytes(tile))
                        except Exception as e:
                            self.log("Writing error: %s" % str([type(e), e]), lvl=error)

                except Exception as e:
                    self.log("Open error on %s - %s" % (filename, str([type(e), e])), lvl=error)
                    return
                finally:
                    event.stop()

                try:
                    self.log("Delivering tile.", lvl=verbose)
                    yield serve_file(request, response, filename)
                except Exception as e:
                    self.log("Couldn't deliver tile: ", e, lvl=error)
                    event.stop()
                self.log("Tile stored and delivered.", lvl=verbose)
            else:
                self.log("Got no tile, serving default tile: %s" % url)
                if self.default_tile:
                    try:
                        yield serve_file(request, response, self.default_tile)
                    except Exception as e:
                        self.log('Cannot deliver default tile:', e, type(e),
                                 exc=True, lvl=error)
                    finally:
                        event.stop()
                else:
                    yield
602271
public static String generateCacheFileFullPath(Uri fileOriginalUri, File cacheDir, long createdTime) {
		String source = fileOriginalUri.toString() + Long.toString(createdTime);
		String fileName = md5(source);
		File cacheFile = new File(cacheDir, fileName);
		return cacheFile.getPath();
	}
749413
private static ImageDescriptor createUnManagedCached(String prefix,
			String name)
	{
		return new CachedImageDescriptor(create(prefix, name, true));
	}
274863
protected void buildCache(int maxCacheSize) {
        if (blackPrefixList != null && !blackPrefixList.isEmpty()) {
            int min = Math.min(256, maxCacheSize);
            int max = Math.min(10240, maxCacheSize);
            ConcurrentLinkedHashMap.Builder<String, Boolean> builder = new ConcurrentLinkedHashMap.Builder<String, Boolean>()
                .initialCapacity(min).maximumWeightedCapacity(max);
            this.resultOfInBlackList = builder.build();
        } else {
            this.resultOfInBlackList = null;
        }
    }
1307560
static synchronized void saveToCache(UnixUserGroupInformation ugi) {
    ugiCache.put(ugi.getUserName(), new CachedUgi(ugi, System
        .currentTimeMillis()));
  }
982307
private void addToCache(BundleInfo bInfo) {
        List<Resource> info = _cacheBySymbolicName.get(bInfo.symbolicName);
        if (info == null) {
            info = new ArrayList<Resource>();
            info.add(bInfo);
        }

        info = _cacheBySymbolicName.putIfAbsent(bInfo.symbolicName, info);

        if (info != null) {
            synchronized (info) {
                info.add(bInfo);
            }
        }

        _bundleLocations.add(bInfo.file);
    }
459042
function init(){
    if(!cacheServiceConfig) {
      cacheServiceConfig = {};
    }
    self.nameSpace = cacheServiceConfig.nameSpace || '';
    self.verbose = (typeof cacheServiceConfig.verbose === 'boolean') ? cacheServiceConfig.verbose : false;
    self.writeToVolatileCaches = (typeof cacheServiceConfig.writeToVolatileCaches === 'boolean') ? cacheServiceConfig.writeToVolatileCaches : true;
    self.caches = new CacheCollection({nameSpace: self.nameSpace, verbose: self.verbose}, cacheModules).caches;
    self.cachesLength = self.caches.length;
  }