Example usage for java.util Collections synchronizedMap

List of usage examples for java.util Collections synchronizedMap

Introduction

In this page you can find the example usage for java.util Collections synchronizedMap.

Prototype

public static <K, V> Map<K, V> synchronizedMap(Map<K, V> m) 

Source Link

Document

Returns a synchronized (thread-safe) map backed by the specified map.

Usage

From source file:cz.filmtit.userspace.Session.java

/**
 * Creates a session owned by given user.
 *
 * @param user Owner of the session.//ww w  .  j  a va 2s. c o  m
 */
public Session(USUser user) {
    activeDocuments = Collections.synchronizedMap(new HashMap<Long, USDocument>());
    //lockedTranslationResults = new ArrayList<TranslationResult>();

    sessionStart = new Date().getTime();
    updateLastOperationTime();
    state = SessionState.active;
    this.user = user;

}

From source file:org.apache.hadoop.hbase.coprocessor.TestBatchCoprocessorEndpoint.java

@Test
public void testAggregationWithErrors() throws Throwable {
    HTable table = new HTable(util.getConfiguration(), TEST_TABLE);
    final Map<byte[], ColumnAggregationWithErrorsProtos.SumResponse> results = Collections.synchronizedMap(
            new TreeMap<byte[], ColumnAggregationWithErrorsProtos.SumResponse>(Bytes.BYTES_COMPARATOR));
    ColumnAggregationWithErrorsProtos.SumRequest.Builder builder = ColumnAggregationWithErrorsProtos.SumRequest
            .newBuilder();//from w  w  w .j  a v a  2  s  .  c  o m
    builder.setFamily(HBaseZeroCopyByteString.wrap(TEST_FAMILY));
    if (TEST_QUALIFIER != null && TEST_QUALIFIER.length > 0) {
        builder.setQualifier(HBaseZeroCopyByteString.wrap(TEST_QUALIFIER));
    }

    boolean hasError = false;
    try {
        table.batchCoprocessorService(
                ColumnAggregationWithErrorsProtos.ColumnAggregationServiceWithErrors.getDescriptor()
                        .findMethodByName("sum"),
                builder.build(), ROWS[0], ROWS[ROWS.length - 1],
                ColumnAggregationWithErrorsProtos.SumResponse.getDefaultInstance(),
                new Batch.Callback<ColumnAggregationWithErrorsProtos.SumResponse>() {

                    @Override
                    public void update(byte[] region, byte[] row,
                            ColumnAggregationWithErrorsProtos.SumResponse result) {
                        results.put(region, result);
                    }
                });
    } catch (Throwable t) {
        LOG.info("Exceptions in coprocessor service", t);
        hasError = true;
    }

    int sumResult = 0;
    int expectedResult = 0;
    for (Map.Entry<byte[], ColumnAggregationWithErrorsProtos.SumResponse> e : results.entrySet()) {
        LOG.info("Got value " + e.getValue().getSum() + " for region " + Bytes.toStringBinary(e.getKey()));
        sumResult += e.getValue().getSum();
    }
    for (int i = 0; i < rowSeperator2; i++) {
        expectedResult += i;
    }
    assertEquals("Invalid result", expectedResult, sumResult);
    assertTrue(hasError);
    table.close();
}

From source file:org.lexevs.system.ResourceManager.java

/**
 * Inits the.//from   w  ww . j a  va 2 s .c o  m
 * 
 * @throws Exception the exception
 */
public void init() throws Exception {
    cache_ = Collections.synchronizedMap(new LRUMap(systemVars_.getCacheSize()));

    // This increases the ability of Lucene to do queries against
    // large indexes like the MetaThesaurus without getting errors.
    BooleanQuery.setMaxClauseCount(systemVars_.getLuceneMaxClauseCount());

    codingSchemeToServerMap_ = new Hashtable<String, String>();
    sqlServerInterfaces_ = new Hashtable<String, SQLInterface>();
    historySqlServerInterfaces_ = new Hashtable<String, SQLHistoryInterface>();
    codingSchemeLocalNamesToInternalNameMap_ = new Hashtable<String, Hashtable<String, String>>();
    internalCodingSchemeNameUIDMap_ = new Hashtable<String, List<LocalCodingScheme>>();
    supportedCodingSchemeToInternalMap_ = new Hashtable<String, String>();

    // populate the registry
    //registry_ = new XmlRegistry(systemVars_.getAutoLoadRegistryPath());

    // connect to the histories
    readHistories();

    // go through all of the sql servers and read all of the available code
    // systems.
    // initialize the SQL connections to each server.

    org.lexevs.registry.service.XmlRegistry.DBEntry[] entries = registry_.getDBEntries();
    for (int i = 0; i < entries.length; i++) {
        SQLConnectionInfo temp = new SQLConnectionInfo();
        temp.driver = systemVars_.getAutoLoadDBDriver();
        temp.password = systemVars_.getAutoLoadDBPassword();
        temp.server = entries[i].dbURL;
        temp.prefix = entries[i].prefix;
        temp.username = systemVars_.getAutoLoadDBUsername();
        readTerminologiesFromServer(temp);
    }

    logger_.debug("Reading available terminologies from SQL servers.");

    // same thing as above, this time for pre-configured servers
    Hashtable<String, SQLConnectionInfo> servers = systemVars_.getSqlServers();

    Enumeration<SQLConnectionInfo> e = servers.elements();
    while (e.hasMoreElements()) {
        SQLConnectionInfo server = e.nextElement();
        readTerminologiesFromServer(server);
    }

    logger_.debug("Reading available terminologies from the lucene index locations");

    // go through all of the index locations, finding the right index for
    // each code system.
    // initialize the index readers.
    HashSet<String> indexLocations = systemVars_.getIndexLocations();
    Iterator<String> iterator = indexLocations.iterator();

    indexInterfaces_ = new Hashtable<String, IndexInterface>();
    codingSchemeToIndexMap_ = new Hashtable<String, String>();

    while (iterator.hasNext()) {
        String location = iterator.next();

        File temp = new File(location);
        if (!temp.exists() || !temp.isDirectory()) {
            logger_.error("Bad index location " + location);
        } else {

            IndexInterface is = new IndexInterface(location);
            indexInterfaces_.put(location, is);

            ArrayList<String> keys = is.getCodeSystemKeys();
            for (int i = 0; i < keys.size(); i++) {
                codingSchemeToIndexMap_.put(keys.get(i), location);
            }
        }
    }

    // Start up a thread to handle scheduled deactivations
    fdt_ = new FutureDeactivatorThread();
    deactivatorThread_ = new Thread(fdt_);
    // This allows the JVM to exit while this thread is still active.
    deactivatorThread_.setDaemon(true);
    deactivatorThread_.start();
}

From source file:com.mirth.connect.client.ui.browsers.message.MessageBrowser.java

/**
 * Constructs the new message browser and sets up its default information/layout
 *///from w  ww  . jav  a  2  s. c  o m
@SuppressWarnings("serial")
public MessageBrowser() {
    this.parent = PlatformUI.MIRTH_FRAME;

    messageCache = Collections.synchronizedMap(new LinkedHashMap<Long, Message>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<Long, Message> eldest) {
            return size() > MAX_CACHE_SIZE;
        }
    });

    attachmentCache = Collections.synchronizedMap(new LinkedHashMap<Long, List<Attachment>>() {
        @Override
        protected boolean removeEldestEntry(Map.Entry<Long, List<Attachment>> eldest) {
            return size() > MAX_CACHE_SIZE;
        }
    });

    initColumnData();

    // Generated by Netbeans
    initComponents();
    // Add additional initializations here
    initComponentsManual();

    //Initialize the message table
    makeMessageTable();
    //Initialize the mappings table
    makeMappingsTable();

    executor = Executors.newFixedThreadPool(5);
}

From source file:org.apache.hadoop.hbase.crosssite.coprocessor.TestCrossSiteCoprocessor.java

@Test
public void testBatchCoprocessorWithErrors() throws Throwable {
    CrossSiteHTable table = new CrossSiteHTable(TEST_UTIL.getConfiguration(), TABLE_NAME);
    ColumnAggregationWithErrorsProtos.SumRequest.Builder builder = ColumnAggregationWithErrorsProtos.SumRequest
            .newBuilder();/*from   w  w w .ja v a2  s. c o m*/
    builder.setFamily(HBaseZeroCopyByteString.wrap(CF));
    if (QN != null && QN.length > 0) {
        builder.setQualifier(HBaseZeroCopyByteString.wrap(QN));
    }
    final Map<byte[], ColumnAggregationWithErrorsProtos.SumResponse> results = Collections.synchronizedMap(
            new TreeMap<byte[], ColumnAggregationWithErrorsProtos.SumResponse>(Bytes.BYTES_COMPARATOR));
    boolean hasErrors = false;
    try {
        table.batchCoprocessorService(
                ColumnAggregationWithErrorsProtos.ColumnAggregationServiceWithErrors.getDescriptor()
                        .findMethodByName("sum"),
                builder.build(), HConstants.EMPTY_START_ROW, HConstants.EMPTY_END_ROW, null,
                ColumnAggregationWithErrorsProtos.SumResponse.getDefaultInstance(),
                new Callback<ColumnAggregationWithErrorsProtos.SumResponse>() {

                    @Override
                    public void update(byte[] region, byte[] row,
                            ColumnAggregationWithErrorsProtos.SumResponse result) {
                        if (region != null) {
                            results.put(region, result);
                        }
                    }
                });
    } catch (Exception e) {
        hasErrors = true;
    }
    assertEquals(true, hasErrors);
    int sumResult = 0;
    int expectedResult = 0;
    for (Map.Entry<byte[], ColumnAggregationWithErrorsProtos.SumResponse> e : results.entrySet()) {
        LOG.info("Got value " + e.getValue().getSum() + " for region " + Bytes.toStringBinary(e.getKey()));
        sumResult += e.getValue().getSum();
    }
    for (int i = 1; i < 10; i++) {
        expectedResult += i;
    }
    expectedResult *= 2;
    assertEquals("Invalid result", expectedResult, sumResult);
    table.close();
}

From source file:org.opencms.flex.CmsFlexCache.java

/**
 * Constructor for class CmsFlexCache.<p>
 *
 * The parameter "enabled" is used to control if the cache is
 * actually on or off. Even if you don't need the cache, you still
 * have to create an instance of it with enabled=false.
 * This is because you need some of the FlexCache data structures
 * for JSP inclusion buffering.<p>
 *
 * @param configuration the flex cache configuration
 *///w  w  w  .j  a  v  a  2 s. c  om
public CmsFlexCache(CmsFlexCacheConfiguration configuration) {

    m_enabled = configuration.isCacheEnabled();
    m_cacheOffline = configuration.isCacheOffline();

    // set the local device selector
    m_deviceSelector = configuration.getDeviceSelector();

    long maxCacheBytes = configuration.getMaxCacheBytes();
    long avgCacheBytes = configuration.getAvgCacheBytes();
    int maxEntryBytes = configuration.getMaxEntryBytes();
    int maxKeys = configuration.getMaxKeys();

    m_variationCache = new CmsLruCache(maxCacheBytes, avgCacheBytes, maxEntryBytes);
    OpenCms.getMemoryMonitor().register(getClass().getName() + ".m_entryLruCache", m_variationCache);

    if (m_enabled) {
        CmsFlexKeyMap flexKeyMap = new CmsFlexKeyMap(maxKeys);
        m_keyCache = Collections
                .synchronizedMap(CmsCollectionsGenericWrapper.<String, CmsFlexCacheVariation>map(flexKeyMap));
        OpenCms.getMemoryMonitor().register(getClass().getName() + ".m_resourceMap", flexKeyMap);

        OpenCms.addCmsEventListener(this,
                new int[] { I_CmsEventListener.EVENT_PUBLISH_PROJECT, I_CmsEventListener.EVENT_CLEAR_CACHES,
                        I_CmsEventListener.EVENT_FLEX_PURGE_JSP_REPOSITORY,
                        I_CmsEventListener.EVENT_FLEX_CACHE_CLEAR });
    }

    if (LOG.isInfoEnabled()) {
        LOG.info(Messages.get().getBundle().key(Messages.INIT_FLEXCACHE_CREATED_2, Boolean.valueOf(m_enabled),
                Boolean.valueOf(m_cacheOffline)));
    }
}

From source file:net.sf.morph.transform.transformers.BaseTransformer.java

/**
 * Initialize this Transformer/*from  w  ww .ja v  a  2  s. c o m*/
 * @throws TransformationException
 */
protected synchronized final void initialize() throws TransformationException {
    if (!initialized) {
        if (log.isInfoEnabled()) {
            log.info("Initializing transformer " + ObjectUtils.getObjectDescription(this));
        }

        try {
            initializeImpl();

            if (sourceClasses == null) {
                sourceClasses = getSourceClassesImpl();
            }
            if (destinationClasses == null) {
                destinationClasses = getDestinationClassesImpl();
            }
            if (ObjectUtils.isEmpty(sourceClasses)) {
                throw new TransformationException("This transformer, " + ObjectUtils.getObjectDescription(this)
                        + ", is invalid because it does specify any sourceClasses");
            }
            if (ObjectUtils.isEmpty(destinationClasses)) {
                throw new TransformationException("This transformer, " + ObjectUtils.getObjectDescription(this)
                        + ", is invalid because it does specify any destinationClasses");
            }

            transformableCallCache = Collections.synchronizedMap(new HashMap());

            if (nestedTransformer == null) {
                nestedTransformer = Defaults.createTransformer();
            }

            initialized = true;
        } catch (TransformationException e) {
            throw e;
        } catch (Exception e) {
            if (e instanceof RuntimeException && !isWrappingRuntimeExceptions()) {
                throw (RuntimeException) e;
            }
            throw new TransformationException(
                    "Could not initialize transformer " + ObjectUtils.getObjectDescription(this), e);
        }
    }
}

From source file:org.tightblog.service.WeblogManager.java

/**
 * Job to write out the hit count queue to the database, updating
 * individual blog's hit counters/*w ww.  j av a  2 s. co  m*/
 */
public void updateHitCounters() {
    if (hitsTally.size() > 0) {
        // Make a reference to the current queue
        Map<String, Long> hitsTallyCopy = hitsTally;

        // reset queue for next execution
        hitsTally = Collections.synchronizedMap(new HashMap<>());

        // iterate over the tallied hits and store them in the db
        long totalHitsProcessed = 0;
        Weblog weblog;
        for (Map.Entry<String, Long> entry : hitsTallyCopy.entrySet()) {
            weblog = weblogRepository.findById(entry.getKey()).orElse(null);
            if (weblog != null) {
                weblog.setHitsToday(weblog.getHitsToday() + entry.getValue().intValue());
                saveWeblog(weblog, true);
                totalHitsProcessed += entry.getValue();
                log.info("Updated blog hits, {} total extra hits from {} blogs", totalHitsProcessed,
                        hitsTallyCopy.size());
            }
        }
    }
}

From source file:com.example.login1.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*  w ww  .  j av a 2  s .c o  m*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));

                    //remove the overwritten header
                    request.removeHeader(overwritten);
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}

From source file:com.android.yijiang.kzx.http.AsyncHttpClient.java

/**
 * Creates a new AsyncHttpClient./*  w w  w  .java 2 s .com*/
 *
 * @param schemeRegistry SchemeRegistry to be used
 */
public AsyncHttpClient(SchemeRegistry schemeRegistry) {

    BasicHttpParams httpParams = new BasicHttpParams();

    ConnManagerParams.setTimeout(httpParams, timeout);
    ConnManagerParams.setMaxConnectionsPerRoute(httpParams, new ConnPerRouteBean(maxConnections));
    ConnManagerParams.setMaxTotalConnections(httpParams, DEFAULT_MAX_CONNECTIONS);

    HttpConnectionParams.setSoTimeout(httpParams, timeout);
    HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
    HttpConnectionParams.setTcpNoDelay(httpParams, true);
    HttpConnectionParams.setSocketBufferSize(httpParams, DEFAULT_SOCKET_BUFFER_SIZE);

    HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);

    ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(httpParams, schemeRegistry);

    threadPool = getDefaultThreadPool();
    requestMap = Collections.synchronizedMap(new WeakHashMap<Context, List<RequestHandle>>());
    clientHeaderMap = new HashMap<String, String>();

    httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    httpClient = new DefaultHttpClient(cm, httpParams);
    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(HttpRequest request, HttpContext context) {
            if (!request.containsHeader(HEADER_ACCEPT_ENCODING)) {
                request.addHeader(HEADER_ACCEPT_ENCODING, ENCODING_GZIP);
            }
            for (String header : clientHeaderMap.keySet()) {
                if (request.containsHeader(header)) {
                    Header overwritten = request.getFirstHeader(header);
                    Log.d(LOG_TAG,
                            String.format("Headers were overwritten! (%s | %s) overwrites (%s | %s)", header,
                                    clientHeaderMap.get(header), overwritten.getName(),
                                    overwritten.getValue()));
                }
                request.addHeader(header, clientHeaderMap.get(header));
            }
        }
    });

    httpClient.addResponseInterceptor(new HttpResponseInterceptor() {
        @Override
        public void process(HttpResponse response, HttpContext context) {
            final HttpEntity entity = response.getEntity();
            if (entity == null) {
                return;
            }
            final Header encoding = entity.getContentEncoding();
            if (encoding != null) {
                for (HeaderElement element : encoding.getElements()) {
                    if (element.getName().equalsIgnoreCase(ENCODING_GZIP)) {
                        response.setEntity(new InflatingEntity(entity));
                        break;
                    }
                }
            }
        }
    });

    httpClient.addRequestInterceptor(new HttpRequestInterceptor() {
        @Override
        public void process(final HttpRequest request, final HttpContext context)
                throws HttpException, IOException {
            AuthState authState = (AuthState) context.getAttribute(ClientContext.TARGET_AUTH_STATE);
            CredentialsProvider credsProvider = (CredentialsProvider) context
                    .getAttribute(ClientContext.CREDS_PROVIDER);
            HttpHost targetHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

            if (authState.getAuthScheme() == null) {
                AuthScope authScope = new AuthScope(targetHost.getHostName(), targetHost.getPort());
                Credentials creds = credsProvider.getCredentials(authScope);
                if (creds != null) {
                    authState.setAuthScheme(new BasicScheme());
                    authState.setCredentials(creds);
                }
            }
        }
    }, 0);

    httpClient
            .setHttpRequestRetryHandler(new RetryHandler(DEFAULT_MAX_RETRIES, DEFAULT_RETRY_SLEEP_TIME_MILLIS));
}