DictionaryPool.java revision c160373b6a8e8a536ad8aa2798a33a41d3050f3b
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    public void close() {
60        synchronized(this) {
61            mClosed = true;
62            for (DictAndProximity dict : this) {
63                dict.mDictionary.close();
64            }
65            clear();
66        }
67    }
68
69    @Override
70    public boolean offer(final DictAndProximity dict) {
71        if (mClosed) {
72            dict.mDictionary.close();
73            return false;
74        } else {
75            return super.offer(dict);
76        }
77    }
78}
79