1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.vfs2.provider.zip;
18
19 import static org.junit.jupiter.api.Assertions.assertTrue;
20
21 import java.io.File;
22
23 import org.apache.commons.vfs2.FileObject;
24 import org.apache.commons.vfs2.FileSystemException;
25 import org.apache.commons.vfs2.cache.WeakRefFilesCache;
26 import org.apache.commons.vfs2.impl.StandardFileSystemManager;
27 import org.junit.jupiter.api.Test;
28
29 public class ZipFileSystemTest {
30
31 /**
32 * Sets a file system's file cache to use WeakReference, and test resolve file after GC.
33 */
34 @Test
35 public void testZipFileUseWeakRefFilesCache() throws FileSystemException {
36
37 final File file = new File("src/test/resources/test-data/test.zip");
38 final String fileUri = "zip:file:" + file.getAbsolutePath();
39 FileObject fileObject = null;
40
41 try (StandardFileSystemManager manager = new StandardFileSystemManager()) {
42 // set file system's file cache use WeakReference, and init file system
43 @SuppressWarnings("resource") // Managed by the file system, no need to close.
44 final WeakRefFilesCache filesCache = new WeakRefFilesCache();
45 manager.setFilesCache(filesCache);
46 manager.init();
47
48 int cnt = 0;
49 while (cnt < 100_000) {
50 cnt++;
51
52 // resolve file, assert fileObject exist. clear fileObject to null and wait GC.
53 try {
54 fileObject = manager.resolveFile(fileUri);
55 assertTrue(fileObject.exists());
56 } finally {
57 FileObject.close(fileObject);
58 fileObject = null;
59 }
60 // every 200 times suggest one gc
61 if (cnt % 200 == 0) {
62 System.gc();
63 }
64 }
65 }
66 }
67
68 }