DictionaryPool.java revision a562767a14c7bbac95b25e69e360fc28d6ce9e33
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 = 0;
32
33    public DictionaryPool(final int maxSize, final AndroidSpellCheckerService service,
34            final Locale locale) {
35        super();
36        mMaxSize = maxSize;
37        mService = service;
38        mLocale = locale;
39    }
40
41    @Override
42    public DictAndProximity take() throws InterruptedException {
43        final DictAndProximity dict = poll();
44        if (null != dict) return dict;
45        synchronized(this) {
46            if (mSize >= mMaxSize) {
47                // Our pool is already full. Wait until some dictionary is ready.
48                return super.take();
49            } else {
50                ++mSize;
51                return mService.createDictAndProximity(mLocale);
52            }
53        }
54    }
55}
56