DictionaryPool.java revision e897e4d3422c8d9d8b6f051376cc2ba16e4d5945
1/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy of
6 * the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations under
14 * the License.
15 */
16
17package com.android.inputmethod.latin.spellcheck;
18
19import android.content.Context;
20
21import java.util.Locale;
22import java.util.concurrent.LinkedBlockingQueue;
23
24/**
25 * A blocking queue that creates dictionaries up to a certain limit as necessary.
26 */
27public class DictionaryPool extends LinkedBlockingQueue<DictAndProximity> {
28    private final AndroidSpellCheckerService mService;
29    private final int mMaxSize;
30    private final Locale mLocale;
31    private int mSize;
32    private volatile boolean mClosed;
33
34    public DictionaryPool(final int maxSize, final AndroidSpellCheckerService service,
35            final Locale locale) {
36        super();
37        mMaxSize = maxSize;
38        mService = service;
39        mLocale = locale;
40        mSize = 0;
41        mClosed = false;
42    }
43
44    @Override
45    public DictAndProximity take() throws InterruptedException {
46        final DictAndProximity dict = poll();
47        if (null != dict) return dict;
48        synchronized(this) {
49            if (mSize >= mMaxSize) {
50                // Our pool is already full. Wait until some dictionary is ready.
51                return super.take();
52            } else {
53                ++mSize;
54                return mService.createDictAndProximity(mLocale);
55            }
56        }
57    }
58
59    // Convenience method
60    public DictAndProximity takeOrGetNull() {
61        try {
62            return take();
63        } catch (InterruptedException e) {
64            return null;
65        }
66    }
67
68    public void close() {
69        synchronized(this) {
70            mClosed = true;
71            for (DictAndProximity dict : this) {
72                dict.mDictionary.close();
73            }
74            clear();
75        }
76    }
77
78    @Override
79    public boolean offer(final DictAndProximity dict) {
80        if (mClosed) {
81            dict.mDictionary.close();
82            return false;
83        } else {
84            return super.offer(dict);
85        }
86    }
87}
88