Example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

List of usage examples for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue

Introduction

In this page you can find the example usage for java.util.concurrent LinkedBlockingQueue LinkedBlockingQueue.

Prototype

public LinkedBlockingQueue() 

Source Link

Document

Creates a LinkedBlockingQueue with a capacity of Integer#MAX_VALUE .

Usage

From source file:SwingWorker.java

/**
 * returns workersExecutorService./*from  ww w.ja v a  2 s  . com*/
 *
 * returns the service stored in the appContext or creates it if
 * necessary. If the last one it triggers autoShutdown thread to
 * get started.
 * 
 * @return ExecutorService for the {@code SwingWorkers}
 * @see #startAutoShutdownThread
 */
private static synchronized ExecutorService getWorkersExecutorService() {
    if (executorService == null) {
        //this creates non-daemon threads. 
        ThreadFactory threadFactory = new ThreadFactory() {
            final ThreadFactory defaultFactory = Executors.defaultThreadFactory();

            public Thread newThread(final Runnable r) {
                Thread thread = defaultFactory.newThread(r);
                thread.setName("SwingWorker-" + thread.getName());
                return thread;
            }
        };

        /*
         * We want a to have no more than MAX_WORKER_THREADS
         * running threads.
         *
         * We want a worker thread to wait no longer than 1 second
         * for new tasks before terminating.
         */
        executorService = new ThreadPoolExecutor(0, MAX_WORKER_THREADS, 1L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), threadFactory) {

            private final ReentrantLock pauseLock = new ReentrantLock();
            private final Condition unpaused = pauseLock.newCondition();
            private boolean isPaused = false;
            private final ReentrantLock executeLock = new ReentrantLock();

            @Override
            public void execute(Runnable command) {
                /*
                 * ThreadPoolExecutor first tries to run task
                 * in a corePool. If all threads are busy it
                 * tries to add task to the waiting queue. If it
                 * fails it run task in maximumPool.
                 *
                 * We want corePool to be 0 and
                 * maximumPool to be MAX_WORKER_THREADS
                 * We need to change the order of the execution.
                 * First try corePool then try maximumPool
                 * pool and only then store to the waiting
                 * queue. We can not do that because we would
                 * need access to the private methods.
                 *
                 * Instead we enlarge corePool to
                 * MAX_WORKER_THREADS before the execution and
                 * shrink it back to 0 after. 
                 * It does pretty much what we need.
                 *
                 * While we changing the corePoolSize we need
                 * to stop running worker threads from accepting new
                 * tasks.
                 */

                //we need atomicity for the execute method.
                executeLock.lock();
                try {

                    pauseLock.lock();
                    try {
                        isPaused = true;
                    } finally {
                        pauseLock.unlock();
                    }

                    setCorePoolSize(MAX_WORKER_THREADS);
                    super.execute(command);
                    setCorePoolSize(0);

                    pauseLock.lock();
                    try {
                        isPaused = false;
                        unpaused.signalAll();
                    } finally {
                        pauseLock.unlock();
                    }
                } finally {
                    executeLock.unlock();
                }
            }

            @Override
            protected void afterExecute(Runnable r, Throwable t) {
                super.afterExecute(r, t);
                pauseLock.lock();
                try {
                    while (isPaused) {
                        unpaused.await();
                    }
                } catch (InterruptedException ignore) {

                } finally {
                    pauseLock.unlock();
                }
            }
        };
    }
    return executorService;
}

From source file:com.netflix.curator.framework.recipes.cache.TestPathChildrenCache.java

@Test
public void testBasics() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), new RetryOneTime(1));
    client.start();/*from  w ww . ja  va  2 s.  c  om*/
    try {
        client.create().forPath("/test");

        final BlockingQueue<PathChildrenCacheEvent.Type> events = new LinkedBlockingQueue<PathChildrenCacheEvent.Type>();
        PathChildrenCache cache = new PathChildrenCache(client, "/test", true);
        cache.getListenable().addListener(new PathChildrenCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception {
                if (event.getData().getPath().equals("/test/one")) {
                    events.offer(event.getType());
                }
            }
        });
        cache.start();

        client.create().forPath("/test/one", "hey there".getBytes());
        Assert.assertEquals(events.poll(10, TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_ADDED);

        client.setData().forPath("/test/one", "sup!".getBytes());
        Assert.assertEquals(events.poll(10, TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_UPDATED);
        Assert.assertEquals(new String(cache.getCurrentData("/test/one").getData()), "sup!");

        client.delete().forPath("/test/one");
        Assert.assertEquals(events.poll(10, TimeUnit.SECONDS), PathChildrenCacheEvent.Type.CHILD_REMOVED);

        cache.close();
    } finally {
        client.close();
    }
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void createFileAsync(String filename, int loop, int batch) throws Exception, InterruptedException {
    System.out.println("createFileAsync, filename " + filename + ", loop " + loop + ", batch " + batch);

    //warmup/*w w  w .j a  v  a2  s.com*/
    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    CrailBuffer buf = fs.allocateBuffer();
    bufferQueue.add(buf);
    warmUp(filename, warmup, bufferQueue);
    fs.freeBuffer(buf);

    //benchmark
    System.out.println("starting benchmark...");
    fs.getStatistics().reset();
    LinkedBlockingQueue<Future<CrailNode>> futureQueue = new LinkedBlockingQueue<Future<CrailNode>>();
    LinkedBlockingQueue<CrailFile> fileQueue = new LinkedBlockingQueue<CrailFile>();
    LinkedBlockingQueue<String> pathQueue = new LinkedBlockingQueue<String>();
    fs.create(filename, CrailNodeType.DIRECTORY, CrailStorageClass.DEFAULT, CrailLocationClass.DEFAULT).get()
            .syncDir();

    for (int i = 0; i < loop; i++) {
        String name = "/" + i;
        String f = filename + name;
        pathQueue.add(f);
    }

    long start = System.currentTimeMillis();
    for (int i = 0; i < loop; i += batch) {
        //single operation == loop
        for (int j = 0; j < batch; j++) {
            String path = pathQueue.poll();
            Future<CrailNode> future = fs.create(path, CrailNodeType.DATAFILE, CrailStorageClass.DEFAULT,
                    CrailLocationClass.DEFAULT);
            futureQueue.add(future);
        }
        for (int j = 0; j < batch; j++) {
            Future<CrailNode> future = futureQueue.poll();
            CrailFile file = future.get().asFile();
            fileQueue.add(file);
        }
        for (int j = 0; j < batch; j++) {
            CrailFile file = fileQueue.poll();
            file.syncDir();
        }
    }
    long end = System.currentTimeMillis();
    double executionTime = ((double) (end - start));
    double latency = executionTime * 1000.0 / ((double) loop);
    System.out.println("execution time [ms] " + executionTime);
    System.out.println("latency [us] " + latency);

    fs.delete(filename, true).get().syncDir();

    fs.getStatistics().print("close");

}

From source file:com.revetkn.ios.analyzer.ArtworkAnalyzer.java

/**
 * @return Creates a backing thread pool used for concurrent execution of image processing tasks.
 *///from   w ww  . j  a va 2  s  . c o m
protected ExecutorService createExecutorService() {
    int coreThreadCount = getRuntime().availableProcessors();
    int maximumThreadCount = coreThreadCount;
    int unusedThreadTerminationTimeoutInSeconds = 5;

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(coreThreadCount, maximumThreadCount,
            unusedThreadTerminationTimeoutInSeconds, SECONDS, new LinkedBlockingQueue<Runnable>());

    threadPoolExecutor.allowCoreThreadTimeOut(true);

    return threadPoolExecutor;
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

/**
 * Construct an index in the given directory.
 * // w  w w. j av a  2  s. com
 * @param indexDirectory File
 * @param config LuceneConfig
 */
private IndexInfo(File indexDirectory, LuceneConfig config) {
    super();
    initialiseTransitions();
    this.config = config;

    if (config != null) {
        this.readWriteLock = new ReentrantReadWriteLock(config.getFairLocking());
        this.maxFieldLength = config.getIndexerMaxFieldLength();
        this.threadPoolExecutor = config.getThreadPoolExecutor();
        IndexInfo.useNIOMemoryMapping = config.getUseNioMemoryMapping();
        this.maxDocsForInMemoryMerge = config.getMaxDocsForInMemoryMerge();
        this.maxRamInMbForInMemoryMerge = config.getMaxRamInMbForInMemoryMerge();
        this.maxDocsForInMemoryIndex = config.getMaxDocsForInMemoryIndex();
        this.maxRamInMbForInMemoryIndex = config.getMaxRamInMbForInMemoryIndex();
        this.writerMaxBufferedDocs = config.getWriterMaxBufferedDocs();
        this.writerRamBufferSizeMb = config.getWriterRamBufferSizeMb();
        this.writerMergeFactor = config.getWriterMergeFactor();
        this.writerMaxMergeDocs = config.getWriterMaxMergeDocs();
        this.mergerMaxBufferedDocs = config.getMergerMaxBufferedDocs();
        this.mergerRamBufferSizeMb = config.getMergerRamBufferSizeMb();
        this.mergerMergeFactor = config.getMergerMergeFactor();
        this.mergerMaxMergeDocs = config.getMergerMaxMergeDocs();
        this.termIndexInterval = config.getTermIndexInterval();
        this.mergerTargetOverlays = config.getMergerTargetOverlayCount();
        this.mergerTargetIndexes = config.getMergerTargetIndexCount();
        this.mergerTargetOverlaysBlockingFactor = config.getMergerTargetOverlaysBlockingFactor();
        // Work out the relative path of the index
        try {
            String indexRoot = new File(config.getIndexRootLocation()).getCanonicalPath();
            this.relativePath = indexDirectory.getCanonicalPath().substring(indexRoot.length() + 1);
        } catch (IOException e) {
            throw new AlfrescoRuntimeException("Failed to determine index relative path", e);
        }
    } else {
        this.readWriteLock = new ReentrantReadWriteLock(false);

        // need a default thread pool ....
        TraceableThreadFactory threadFactory = new TraceableThreadFactory();
        threadFactory.setThreadDaemon(true);
        threadFactory.setThreadPriority(5);

        threadPoolExecutor = new ThreadPoolExecutor(10, 10, 90, TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(), threadFactory, new ThreadPoolExecutor.CallerRunsPolicy());

        // Create a 'fake' relative path
        try {
            this.relativePath = indexDirectory.getCanonicalPath();
            int sepIndex = this.relativePath.indexOf(File.separator);
            if (sepIndex != -1) {
                if (this.relativePath.length() > sepIndex + 1) {
                    this.relativePath = this.relativePath.substring(sepIndex + 1);
                } else {
                    this.relativePath = "";
                }
            }
        } catch (IOException e) {
            throw new AlfrescoRuntimeException("Failed to determine index relative path", e);
        }

    }

    // Create an empty in memory index
    IndexWriter writer;
    try {
        writer = new IndexWriter(emptyIndex, new AlfrescoStandardAnalyser(), true, MaxFieldLength.LIMITED);
        writer.setUseCompoundFile(writerUseCompoundFile);
        writer.setMaxBufferedDocs(writerMaxBufferedDocs);
        writer.setRAMBufferSizeMB(writerRamBufferSizeMb);
        writer.setMergeFactor(writerMergeFactor);
        writer.setMaxMergeDocs(writerMaxMergeDocs);
        writer.setWriteLockTimeout(writeLockTimeout);
        writer.setMaxFieldLength(maxFieldLength);
        writer.setTermIndexInterval(termIndexInterval);
        writer.setMergeScheduler(new SerialMergeScheduler());
        writer.setMergePolicy(new LogDocMergePolicy());
        writer.close();
    } catch (IOException e) {
        throw new IndexerException("Failed to create an empty in memory index!");
    }

    this.indexDirectory = indexDirectory;

    // Make sure the directory exists
    if (!this.indexDirectory.exists()) {
        if (!this.indexDirectory.mkdirs()) {
            throw new AlfrescoRuntimeException("Failed to create index directory");
        }
    }
    if (!this.indexDirectory.isDirectory()) {
        throw new AlfrescoRuntimeException("The index must be held in a directory");
    }

    // Create the info files.
    File indexInfoFile = new File(this.indexDirectory, INDEX_INFO);
    File indexInfoBackupFile = new File(this.indexDirectory, INDEX_INFO_BACKUP);
    if (createFile(indexInfoFile) && createFile(indexInfoBackupFile)) {
        // If both files required creation this is a new index
        version = 0;
    }

    // Open the files and channels for the index info file and the backup
    this.indexInfoRAF = openFile(indexInfoFile);
    this.indexInfoChannel = this.indexInfoRAF.getChannel();

    this.indexInfoBackupRAF = openFile(indexInfoBackupFile);
    this.indexInfoBackupChannel = this.indexInfoBackupRAF.getChannel();

    // If the index found no info files (i.e. it is new), check if there is
    // an old style index and covert it.
    if (version == 0) {
        // Check if an old style index exists

        final File oldIndex = new File(this.indexDirectory, OLD_INDEX);
        if (IndexReader.indexExists(oldIndex)) {
            getWriteLock();
            try {
                doWithFileLock(new LockWork<Object>() {
                    public Object doWork() throws Exception {
                        IndexWriter writer;
                        try {
                            writer = new IndexWriter(oldIndex, new AlfrescoStandardAnalyser(), false,
                                    MaxFieldLength.LIMITED);
                            writer.setUseCompoundFile(writerUseCompoundFile);
                            writer.setMaxBufferedDocs(writerMaxBufferedDocs);
                            writer.setRAMBufferSizeMB(writerRamBufferSizeMb);
                            writer.setMergeFactor(writerMergeFactor);
                            writer.setMaxMergeDocs(writerMaxMergeDocs);
                            writer.setWriteLockTimeout(writeLockTimeout);
                            writer.setMaxFieldLength(maxFieldLength);
                            writer.setTermIndexInterval(termIndexInterval);
                            writer.setMergeScheduler(new SerialMergeScheduler());
                            writer.setMergePolicy(new LogDocMergePolicy());
                            writer.optimize();
                            long docs = writer.numDocs();
                            writer.close();

                            IndexEntry entry = new IndexEntry(IndexType.INDEX, OLD_INDEX, "",
                                    TransactionStatus.COMMITTED, "", docs, 0, false);
                            indexEntries.put(OLD_INDEX, entry);

                            writeStatus();

                            // The index exists and we should initialise the single reader
                            registerReferenceCountingIndexReader(entry.getName(),
                                    buildReferenceCountingIndexReader(entry.getName(),
                                            entry.getDocumentCount()));
                        } catch (IOException e) {
                            throw new IndexerException("Failed to optimise old index");
                        }
                        return null;
                    }

                    public boolean canRetry() {
                        return false;
                    }
                });
            } finally {
                releaseWriteLock();
            }

        }
    }

    // The index exists
    else if (version == -1) {
        getWriteLock();
        try {
            doWithFileLock(new LockWork<Object>() {
                public Object doWork() throws Exception {
                    setStatusFromFile();

                    // If the index is not shared we can do some easy clean
                    // up
                    if (!indexIsShared) {
                        HashSet<String> deletable = new HashSet<String>();
                        // clean up
                        for (IndexEntry entry : indexEntries.values()) {
                            switch (entry.getStatus()) {
                            // states which can be deleted
                            // We could check prepared states can be
                            // committed.
                            case ACTIVE:
                            case MARKED_ROLLBACK:
                            case NO_TRANSACTION:
                            case PREPARING:
                            case ROLLEDBACK:
                            case ROLLINGBACK:
                            case MERGE_TARGET:
                            case UNKNOWN:
                            case PREPARED:
                            case DELETABLE:
                                if (s_logger.isInfoEnabled()) {
                                    s_logger.info("Deleting index entry " + entry);
                                }
                                entry.setStatus(TransactionStatus.DELETABLE);
                                deletable.add(entry.getName());
                                break;
                            // States which are in mid-transition which we
                            // can roll back to the committed state
                            case COMMITTED_DELETING:
                            case MERGE:
                                if (s_logger.isInfoEnabled()) {
                                    s_logger.info("Resetting merge to committed " + entry);
                                }
                                entry.setStatus(TransactionStatus.COMMITTED);
                                registerReferenceCountingIndexReader(entry.getName(),
                                        buildReferenceCountingIndexReader(entry.getName(),
                                                entry.getDocumentCount()));
                                break;
                            // Complete committing (which is post database
                            // commit)
                            case COMMITTING:
                                // do the commit
                                if (s_logger.isInfoEnabled()) {
                                    s_logger.info("Committing " + entry);
                                }
                                entry.setStatus(TransactionStatus.COMMITTED);
                                registerReferenceCountingIndexReader(entry.getName(),
                                        buildReferenceCountingIndexReader(entry.getName(),
                                                entry.getDocumentCount()));
                                break;
                            // States that require no action
                            case COMMITTED:
                                registerReferenceCountingIndexReader(entry.getName(),
                                        buildReferenceCountingIndexReader(entry.getName(),
                                                entry.getDocumentCount()));
                                break;
                            default:
                                // nothing to do
                                break;
                            }
                        }
                        // Delete entries that are not required
                        invalidateMainReadersFromFirst(deletable);
                        for (String id : deletable) {
                            indexEntries.remove(id);
                        }
                        clearOldReaders();

                        cleaner.schedule();

                        merger.schedule();

                        // persist the new state
                        writeStatus();
                    }
                    return null;
                }

                public boolean canRetry() {
                    return false;
                }

            });
        } finally {
            releaseWriteLock();
        }
    }
    // Need to do with file lock - must share info about other readers to support this with shared indexer
    // implementation

    getWriteLock();
    try {
        LockWork<Object> work = new DeleteUnknownGuidDirectories();
        doWithFileLock(work);
    } finally {
        releaseWriteLock();
    }

    // Run the cleaner around every 20 secods - this just makes the request to the thread pool
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            cleaner.schedule();
        }
    }, 0, 20000);

    publishDiscoveryEvent();
}

From source file:alluxio.master.file.DefaultFileSystemMaster.java

/**
 * Checks the consistency of the root in a multi-threaded and incremental fashion. This method
 * will only READ lock the directories and files actively being checked and release them after the
 * check on the file / directory is complete.
 *
 * @return a list of paths in Alluxio which are not consistent with the under storage
 * @throws InterruptedException if the thread is interrupted during execution
 * @throws IOException if an error occurs interacting with the under storage
 *//*ww  w . j  av a  2s .c om*/
private List<AlluxioURI> startupCheckConsistency(final ExecutorService service)
        throws InterruptedException, IOException {
    /** A marker {@link StartupConsistencyChecker}s add to the queue to signal completion */
    final long completionMarker = -1;
    /** A shared queue of directories which have yet to be checked */
    final BlockingQueue<Long> dirsToCheck = new LinkedBlockingQueue<>();

    /**
     * A {@link Callable} which checks the consistency of a directory.
     */
    final class StartupConsistencyChecker implements Callable<List<AlluxioURI>> {
        /** The path to check, guaranteed to be a directory in Alluxio. */
        private final Long mFileId;

        /**
         * Creates a new callable which checks the consistency of a directory.
         * @param fileId the path to check
         */
        private StartupConsistencyChecker(Long fileId) {
            mFileId = fileId;
        }

        /**
         * Checks the consistency of the directory and all immediate children which are files. All
         * immediate children which are directories are added to the shared queue of directories to
         * check. The parent directory is READ locked during the entire call while the children are
         * READ locked only during the consistency check of the children files.
         *
         * @return a list of inconsistent uris
         * @throws IOException if an error occurs interacting with the under storage
         */
        @Override
        public List<AlluxioURI> call() throws IOException {
            List<AlluxioURI> inconsistentUris = new ArrayList<>();
            try (LockedInodePath dir = mInodeTree.lockFullInodePath(mFileId, InodeTree.LockMode.READ)) {
                Inode parentInode = dir.getInode();
                AlluxioURI parentUri = dir.getUri();
                if (!checkConsistencyInternal(parentInode, parentUri)) {
                    inconsistentUris.add(parentUri);
                }
                for (Inode childInode : ((InodeDirectory) parentInode).getChildren()) {
                    try {
                        childInode.lockReadAndCheckParent(parentInode);
                    } catch (InvalidPathException e) {
                        // This should be safe, continue.
                        LOG.debug("Error during startup check consistency, ignoring and continuing.", e);
                        continue;
                    }
                    try {
                        AlluxioURI childUri = parentUri.join(childInode.getName());
                        if (childInode.isDirectory()) {
                            dirsToCheck.add(childInode.getId());
                        } else {
                            if (!checkConsistencyInternal(childInode, childUri)) {
                                inconsistentUris.add(childUri);
                            }
                        }
                    } finally {
                        childInode.unlockRead();
                    }
                }
            } catch (FileDoesNotExistException e) {
                // This should be safe, continue.
                LOG.debug("A file scheduled for consistency check was deleted before the check.");
            } catch (InvalidPathException e) {
                // This should not happen.
                LOG.error("An invalid path was discovered during the consistency check, skipping.", e);
            }
            dirsToCheck.add(completionMarker);
            return inconsistentUris;
        }
    }

    // Add the root to the directories to check.
    dirsToCheck.add(mInodeTree.getRoot().getId());
    List<Future<List<AlluxioURI>>> results = new ArrayList<>();
    // Tracks how many checkers have been started.
    long started = 0;
    // Tracks how many checkers have completed.
    long completed = 0;
    do {
        Long fileId = dirsToCheck.take();
        if (fileId == completionMarker) { // A thread signaled completion.
            completed++;
        } else { // A new directory needs to be checked.
            StartupConsistencyChecker checker = new StartupConsistencyChecker(fileId);
            results.add(service.submit(checker));
            started++;
        }
    } while (started != completed);

    // Return the total set of inconsistent paths discovered.
    List<AlluxioURI> inconsistentUris = new ArrayList<>();
    for (Future<List<AlluxioURI>> result : results) {
        try {
            inconsistentUris.addAll(result.get());
        } catch (Exception e) {
            // This shouldn't happen, all futures should be complete.
            Throwables.propagate(e);
        }
    }
    service.shutdown();
    return inconsistentUris;
}

From source file:com.ibm.crail.tools.CrailBenchmark.java

void getFileAsync(String filename, int loop, int batch) throws Exception, InterruptedException {
    System.out.println("getFileAsync, filename " + filename + ", loop " + loop + ", batch " + batch);

    //warmup//from  w w  w  . j a  v a 2s  . co  m
    ConcurrentLinkedQueue<CrailBuffer> bufferQueue = new ConcurrentLinkedQueue<CrailBuffer>();
    CrailBuffer buf = fs.allocateBuffer();
    bufferQueue.add(buf);
    warmUp(filename, warmup, bufferQueue);
    fs.freeBuffer(buf);

    //benchmark
    System.out.println("starting benchmark...");
    fs.getStatistics().reset();
    LinkedBlockingQueue<Future<CrailNode>> fileQueue = new LinkedBlockingQueue<Future<CrailNode>>();
    long start = System.currentTimeMillis();
    for (int i = 0; i < loop; i++) {
        //single operation == loop
        for (int j = 0; j < batch; j++) {
            Future<CrailNode> future = fs.lookup(filename);
            fileQueue.add(future);
        }
        for (int j = 0; j < batch; j++) {
            Future<CrailNode> future = fileQueue.poll();
            future.get();
        }
    }
    long end = System.currentTimeMillis();
    double executionTime = ((double) (end - start));
    double latency = executionTime * 1000.0 / ((double) batch);
    System.out.println("execution time [ms] " + executionTime);
    System.out.println("latency [us] " + latency);

    fs.getStatistics().print("close");
}

From source file:co.beem.project.beem.FbTextService.java

/**
 * {@inheritDoc}//w  w w  . j  av a  2  s. c o  m
 */
@Override
public void onCreate() {
    super.onCreate();
    Utils.setContext(getApplicationContext());
    smackAndroid = SmackAndroid.init(FbTextService.this);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    savingMessageQueue = new LinkedBlockingQueue<co.beem.project.beem.service.BeemMessage>();
    stateChangeQueue = new LinkedBlockingQueue<User>();
    sendImageQueue = new LinkedBlockingDeque<ImageMessageInQueue>();
    isRunning = true;
    sessionManager = new SessionManager(FbTextService.this);
    savingMessageOnBackgroundThread(new SavingNewMessageTask());
    savingMessageOnBackgroundThread(new UpdateUserStateTask());
    savingMessageOnBackgroundThread(new SendImageTask());
    handler = new Handler();
    registerReceiver(mReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CLOSED));
    this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTED));
    this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTING));
    this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_DISCONNECT));
    this.registerReceiver(mReceiver, new IntentFilter(BeemBroadcastReceiver.BEEM_CONNECTION_CONNECTING_In));
    registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.SEND_IMAGE_MESSAGE));
    registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.SEND_INVITATION));
    registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.UPDATE_USER_STATE));
    registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.PUSH_NOTIFICATION_FAVORITE_ONLINE));
    registerReceiver(mOnOffReceiver, new IntentFilter(FbTextApplication.CHANGE_STATUS));
    mSettings = PreferenceManager.getDefaultSharedPreferences(this);
    mSettings.registerOnSharedPreferenceChangeListener(mPreferenceListener);
    if (mSettings.getBoolean(FbTextApplication.USE_AUTO_AWAY_KEY, false)) {
        mOnOffReceiverIsRegistered = true;
        registerReceiver(mOnOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
        registerReceiver(mOnOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
        // registerReceiver(sma, filter)
    }
    String tmpJid = mSettings.getString(FbTextApplication.ACCOUNT_USERNAME_KEY, "").trim();
    mLogin = StringUtils.parseName(tmpJid);
    boolean useSystemAccount = mSettings.getBoolean(FbTextApplication.USE_SYSTEM_ACCOUNT_KEY, false);
    mPort = DEFAULT_XMPP_PORT;
    mService = StringUtils.parseServer(tmpJid);
    mHost = mService;
    initMemorizingTrustManager();

    if (mSettings.getBoolean(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_KEY, false)) {
        mHost = mSettings.getString(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_HOST_KEY, "").trim();
        if ("".equals(mHost))
            mHost = mService;
        String tmpPort = mSettings.getString(FbTextApplication.ACCOUNT_SPECIFIC_SERVER_PORT_KEY, "5222");
        if (!"".equals(tmpPort))
            mPort = Integer.parseInt(tmpPort);
    }
    if (mSettings.getBoolean(FbTextApplication.FULL_JID_LOGIN_KEY, false) || "gmail.com".equals(mService)
            || "googlemail.com".equals(mService) || useSystemAccount) {
        mLogin = tmpJid;
    }

    configure(ProviderManager.getInstance());

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
    mBind = new XmppFacade(this);
    if (FbTextApplication.isDebug)
        Log.d(TAG, "Create FacebookTextService \t id: " + mLogin + " \t host: " + mHost + "\tmPort" + mPort
                + "\t service" + mService);
}