Example usage for java.util.concurrent ConcurrentHashMap ConcurrentHashMap

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

Introduction

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

Prototype

public ConcurrentHashMap() 

Source Link

Document

Creates a new, empty map with the default initial table size (16).

Usage

From source file:eu.stratosphere.runtime.io.network.netty.NettyConnectionManager.java

public NettyConnectionManager(ChannelManager channelManager, InetAddress bindAddress, int bindPort,
        int bufferSize, int numInThreads, int numOutThreads, int lowWaterMark, int highWaterMark) {
    this.outConnections = new ConcurrentHashMap<RemoteReceiver, Object>();
    this.channelManager = channelManager;

    // --------------------------------------------------------------------

    int defaultNumThreads = Math.max(Runtime.getRuntime().availableProcessors() / 4, 1);
    numInThreads = (numInThreads == -1) ? defaultNumThreads : numInThreads;
    numOutThreads = (numOutThreads == -1) ? defaultNumThreads : numOutThreads;
    LOG.info(String.format("Starting with %d incoming and %d outgoing connection threads.", numInThreads,
            numOutThreads));//  w ww .  j  a v a  2s.  c  o  m

    lowWaterMark = (lowWaterMark == -1) ? bufferSize / 2 : lowWaterMark;
    highWaterMark = (highWaterMark == -1) ? bufferSize : highWaterMark;
    LOG.info(String.format("Setting low water mark to %d and high water mark to %d bytes.", lowWaterMark,
            highWaterMark));

    // --------------------------------------------------------------------
    // server bootstrap (incoming connections)
    // --------------------------------------------------------------------
    this.in = new ServerBootstrap();
    this.in.group(new NioEventLoopGroup(numInThreads)).channel(NioServerSocketChannel.class)
            .localAddress(bindAddress, bindPort).childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline()
                            .addLast(new InboundEnvelopeDecoder(NettyConnectionManager.this.channelManager))
                            .addLast(new InboundEnvelopeDispatcherHandler(
                                    NettyConnectionManager.this.channelManager));
                }
            }).option(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(bufferSize))
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);

    // --------------------------------------------------------------------
    // client bootstrap (outgoing connections)
    // --------------------------------------------------------------------
    this.out = new Bootstrap();
    this.out.group(new NioEventLoopGroup(numOutThreads)).channel(NioSocketChannel.class)
            .handler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel channel) throws Exception {
                    channel.pipeline().addLast(new OutboundEnvelopeEncoder());
                }
            }).option(ChannelOption.WRITE_BUFFER_LOW_WATER_MARK, lowWaterMark)
            .option(ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK, highWaterMark)
            .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
            .option(ChannelOption.TCP_NODELAY, false).option(ChannelOption.SO_KEEPALIVE, true);

    try {
        this.in.bind().sync();
    } catch (InterruptedException e) {
        throw new RuntimeException("Could not bind server socket for incoming connections.");
    }

    if (LOG.isDebugEnabled()) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Date date = new Date();

                while (true) {
                    try {
                        Thread.sleep(DEBUG_PRINT_QUEUED_ENVELOPES_EVERY_MS);

                        date.setTime(System.currentTimeMillis());
                        System.out.println(date);

                        System.out.println(getNonZeroNumQueuedEnvelopes());

                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }
}

From source file:org.pentaho.pat.server.services.impl.SessionServiceImpl.java

public String createNewSession(final String userId) {
    this.validateUser(userId);

    final String generatedId = String.valueOf(UUID.randomUUID());

    if (!sessions.containsKey(userId)) {
        sessions.put(userId, new ConcurrentHashMap<String, Session>());
    }/*from w ww  .jav  a  2  s .  c o m*/

    sessions.get(userId).put(generatedId, new Session(generatedId));

    return generatedId;
}

From source file:com.bstek.dorado.view.service.LongPollingServiceProcessor.java

protected void doExecute(Writer writer, ObjectNode objectNode, DoradoContext context) throws Exception {
    synchronized (this) {
        if (!inited) {
            inited = true;//from   w ww .ja v a 2  s  . c o  m
            longPollingGroups = new ConcurrentHashMap<String, LongPollingGroup>();
            pollDuration = Configure.getLong("view.longPolling.duration", 20) * ONE_SECOND;
            defaultResponseDelay = Configure.getLong("view.longPolling.defaultResponseDelay", 200);
            minResponseDelay = Configure.getLong("view.longPolling.minResponseDelay", 50);
        }
    }

    // hand-shake?send?poll?disconnect
    String subAction = JsonUtils.getString(objectNode, "subAction");
    Object result = null;

    if (POLL.equals(subAction)) {
        result = processPoll(writer, objectNode, context);
    } else if (STOP_POLL.equals(subAction)) {
        result = processStopPoll(writer, objectNode, context);
    } else if (SEND.equals(subAction)) {
        result = processSend(writer, objectNode, context);
    } else if (HAND_SHAKE.equals(subAction)) {
        result = processHandShake(writer, objectNode, context);
    } else if (DISCONNECT.equals(subAction)) {
        result = processDisconnect(writer, objectNode, context);
    } else {
        throw new IllegalArgumentException("Unrecognized long-polling action [" + subAction + "].");
    }

    OutputContext outputContext = new OutputContext(writer);
    outputContext.setUsePrettyJson(Configure.getBoolean("view.outputPrettyJson"));
    getDataOutputter().output(result, outputContext);
}

From source file:fathom.realm.htpasswd.HtpasswdRealm.java

public HtpasswdRealm() {
    this.credentialsMap = new ConcurrentHashMap<>();
}

From source file:com.networknt.registry.support.command.CommandServiceManager.java

public CommandServiceManager(URL refUrl) {
    if (logger.isInfoEnabled())
        logger.info("CommandServiceManager init url:" + refUrl.toFullStr());
    this.refUrl = refUrl;
    notifySet = new ConcurrentHashSet<NotifyListener>();
    groupServiceCache = new ConcurrentHashMap<String, List<URL>>();

}

From source file:com.joshlong.esb.springintegration.modules.services.amazon.sqs.AmazonSQS2Client.java

public AmazonSQS2Client(String awsUser, String awsPw, String awsHost) {
    this.messageQueuesById = new ConcurrentHashMap<String, MessageQueue>();
    this.messagesNotYetRecieved = new ConcurrentLinkedQueue<Message>();
    this.awsUser = awsUser;
    this.awsPassword = awsPw;

    if (StringUtils.isEmpty(awsHost)) {
        awsHost = null; /// by default itll use "queue.amazonaws.com"  
    }/*from w  ww .  jav a2 s . c o  m*/

    this.awsHost = awsHost;
}

From source file:com.opengamma.financial.currency.AbstractCurrencyMatrix.java

protected void addConversion(final Currency source, final Currency target, final CurrencyMatrixValue rate) {
    ArgumentChecker.notNull(source, "source");
    ArgumentChecker.notNull(target, "target");
    ArgumentChecker.notNull(rate, "rate");
    ConcurrentHashMap<Currency, CurrencyMatrixValue> conversions = _values.get(source);
    if (conversions == null) {
        conversions = new ConcurrentHashMap<Currency, CurrencyMatrixValue>();
        final ConcurrentHashMap<Currency, CurrencyMatrixValue> newConversions = _values.putIfAbsent(source,
                conversions);/*from   w  w  w. j  a va  2 s .  co  m*/
        if (newConversions != null) {
            conversions = newConversions;
        }
    }
    if (conversions.put(target, rate) == null) {
        // Added something to the map, so increase the target's reference count
        AtomicInteger targetCount = _targets.get(target);
        if (targetCount == null) {
            targetCount = new AtomicInteger(1);
            targetCount = _targets.putIfAbsent(target, targetCount);
            if (targetCount != null) {
                // Another thread already inserted the reference count
                if (targetCount.incrementAndGet() == 1) {
                    // Another thread may have removed the last reference, confirm and re-insert atomically against "remove"
                    synchronized (targetCount) {
                        if (targetCount.get() > 0) {
                            _targets.putIfAbsent(target, targetCount);
                        }
                    }
                }
            }
        } else {
            if (targetCount.incrementAndGet() == 1) {
                // Another thread may have removed the last reference, confirm and re-insert atomically against "remove"
                synchronized (targetCount) {
                    if (targetCount.get() > 0) {
                        _targets.putIfAbsent(target, targetCount);
                    }
                }
            }
        }
    }
}

From source file:com.astamuse.asta4d.web.util.timeout.DefaultSessionAwareTimeoutDataManager.java

@Override
public void start() {
    // init fields
    dataMap = new ConcurrentHashMap<>();
    dataCounter = new AtomicInteger();
    service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {
        @Override//from  ww w. j av  a2s  .c om
        public Thread newThread(Runnable r) {
            return new Thread(r, checkThreadName);
        }
    });

    // start check thread
    service.scheduleAtFixedRate(new Runnable() {
        @Override
        public void run() {
            List<Entry<String, DataHolder>> entries = new ArrayList<>(dataMap.entrySet());
            long currentTime = System.currentTimeMillis();
            int removedCounter = 0;
            Object existing;
            for (Entry<String, DataHolder> entry : entries) {
                if (entry.getValue().isExpired(currentTime)) {
                    existing = dataMap.remove(entry.getKey());
                    if (existing != null) {// we removed it successfully
                        removedCounter++;
                    }
                }
            }
            if (removedCounter > 0) {
                dataCounter.addAndGet(-removedCounter);
            }
        }
    }, expirationCheckPeriodInMilliseconds, expirationCheckPeriodInMilliseconds, TimeUnit.MILLISECONDS);
}

From source file:com.openteach.diamond.network.waverider.WaveriderServer.java

@Override
public void initialize() {
    super.initialize();
    callback = new ResponseCallback() {
        @Override/* www . j  av a2 s  .  co  m*/
        public void completed(NetworkRequest request, Object response) {
            NetworkResponse r = new NetworkResponse(request.getId(), response);
            PendingRequest pr = pendingRequestMap.remove(request.getId());
            pr.end = System.currentTimeMillis();
            System.out.println(String.format("Request execute in server consume:%d ms", pr.end - pr.start));
            pr.session.execute(CommandFactory.createCommand(COMMAND_HSF_RESPONSE, r.marshall()));
        }
    };
    pendingRequestMap = new ConcurrentHashMap<String, PendingRequest>();
    config.setPort(getServerPort());
    masterNode = WaveriderFactory.newInstance(config).buildMaster();
    masterNode.addCommandHandler(COMMAND_HSF_INVOKE, new CommandHandler() {

        @Override
        public Command handle(Command command) {
            NetworkRequest request = NetworkRequest.unmarshall(command.getPayLoad());
            PendingRequest pr = new PendingRequest(request, command.getSession());
            pendingRequestMap.put(request.getId(), pr);
            pr.start = System.currentTimeMillis();
            // async
            handler.handle(request, callback);
            return null;
        }

    });
    masterNode.init();
    masterNode.start();
}

From source file:net.vleu.par.android.rpc.PersistentCookieStore.java

/**
 * Construct a persistent cookie store.//from w  ww  .j av a2 s  . c  om
 */
public PersistentCookieStore(final SharedPreferences cookiePrefs) {
    this.cookiePrefs = cookiePrefs;
    this.cookies = new ConcurrentHashMap<String, Cookie>();

    // Load any previously stored cookies into the store
    final String storedCookieNames = this.cookiePrefs.getString(COOKIE_NAME_STORE, null);
    if (storedCookieNames != null) {
        final String[] cookieNames = TextUtils.split(storedCookieNames, ",");
        for (final String name : cookieNames) {
            final String encodedCookie = this.cookiePrefs.getString(COOKIE_NAME_PREFIX + name, null);
            if (encodedCookie != null) {
                final Cookie decodedCookie = decodeCookie(encodedCookie);
                if (decodedCookie != null)
                    this.cookies.put(name, decodedCookie);
            }
        }

        // Clear out expired cookies
        clearExpired(new Date());
    }
}