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
18package org.apache.harmony.luni.util;
19
20
21import java.io.File;
22import java.util.ArrayList;
23import java.util.Collections;
24
25// BEGIN android-changed
26/**
27 * Implements the actual DeleteOnExit mechanism. Is registered as a shutdown
28 * hook in the Runtime, once it is actually being used.
29 */
30public class DeleteOnExit extends Thread {
31
32    /**
33     * Our singleton instance.
34     */
35    private static DeleteOnExit instance;
36
37    /**
38     * Our list of files scheduled for deletion.
39     */
40    private ArrayList<String> files = new ArrayList<String>();
41
42    /**
43     * Returns our singleton instance, creating it if necessary.
44     */
45    public static synchronized DeleteOnExit getInstance() {
46        if (instance == null) {
47            instance = new DeleteOnExit();
48            Runtime.getRuntime().addShutdownHook(instance);
49        }
50
51        return instance;
52    }
53
54    /**
55     * Schedules a file for deletion.
56     *
57     * @param filename The file to delete.
58     */
59    public void addFile(String filename) {
60        synchronized(files) {
61            if (!files.contains(filename)) {
62                files.add(filename);
63            }
64        }
65    }
66
67    /**
68     * Does the actual work. Note we (a) first sort the files lexicographically
69     * and then (b) delete them in reverse order. This is to make sure files
70     * get deleted before their parent directories.
71     */
72    @Override
73    public void run() {
74        Collections.sort(files);
75        for (int i = files.size() - 1; i >= 0; i--) {
76            new File(files.get(i)).delete();
77        }
78    }
79}
80// END android-changed
81