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:org.apache.synapse.transport.nhttp.ConnectionPool.java

public ConnectionPool() {
    super();/*  w  w  w  .  j a v a  2  s.  c  om*/
    this.connMap = Collections.synchronizedMap(new HashMap<HttpRoute, List<NHttpClientConnection>>());
}

From source file:org.unesco.jisis.jisisutil.history.JisisHistoryModelSaver.java

/**
 *
 * @param models/*from   ww w . j a  v  a 2 s.  co m*/
 * @return
 */
@Override
public Map<String, HistoryModel> load(Map<String, HistoryModel> models) {

    historyFile = new File(Global.getClientTempPath(), "history");
    if (!historyFile.exists()) {
        return models;
    }

    historyModTime = historyFile.lastModified();

    LOGGER.info("Loading history");

    if (models == null) {
        models = Collections.synchronizedMap(new HashMap<String, HistoryModel>());
    }

    BufferedReader in = null;
    try {
        // Try loading with UTF-8 and fallback to the system
        // default encoding to load a historyFile which was made by
        // an old version as well.
        try {
            // Pass the decoder explicitly to report a decode error
            // as an exception instead of replacing with \xFFFD.
            in = new BufferedReader(new InputStreamReader(new FileInputStream(historyFile),
                    Charset.forName("UTF-8").newDecoder()));
            models.putAll(loadFromReader(in));
        } catch (CharacterCodingException e) {
            if (in != null) {
                in.close();
            }
            LOGGER.info("Failed to load history with UTF-8." + " Fallbacking to the system default encoding.");

            in = new BufferedReader(new FileReader(historyFile));
            models.putAll(loadFromReader(in));
        }
    } catch (FileNotFoundException fnf) {
        //Log.log(Log.DEBUG,HistoryModel.class,fnf);
    } catch (IOException io) {
        LOGGER.error("History IO error", io);
    } finally {
        IOUtils.closeQuietly(in);
    }
    return models;
}

From source file:org.ofbiz.core.entity.MemoryHelper.java

private static <K, V> Map<K, V> getNewCache() {
    return Collections.synchronizedMap(new HashMap<K, V>());
}

From source file:com.offbynull.portmapper.pcp.PcpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {//from   w  w  w . ja  va 2 s .  c om
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                // make sure version is 2 and error isn't ADDRESS_MISMATCH and we're good to go
                if (packet.remaining() < 4
                        || packet.get(0) == 2 && packet.get(4) == PcpResultCode.ADDRESS_MISMATCH.ordinal()) {
                    return;
                }

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                ByteBuffer outBuf = ByteBuffer.allocate(1100);
                MapPcpRequest mpr = new MapPcpRequest(ByteBuffer.allocate(12), 0, 0, 0,
                        InetAddress.getByName("::"), 0L);
                mpr.dump(outBuf, bindMap.get(channel));
                outBuf.flip();

                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:info.magnolia.commands.MgnlCatalog.java

public MgnlCatalog(Map commands) {
    this.commands = Collections.synchronizedMap(commands);
}

From source file:com.offbynull.portmapper.natpmp.NatPmpDiscovery.java

private static Map<InetAddress, InetAddress> discoverLocalAddressesToGateways(Set<InetAddress> gateways)
        throws IOException, InterruptedException {
    Set<InetAddress> localAddresses = NetworkUtils.getAllLocalIpv4Addresses();
    List<DatagramChannel> channels = new ArrayList<>();
    final Map<DatagramChannel, InetAddress> bindMap = Collections
            .synchronizedMap(new HashMap<DatagramChannel, InetAddress>());
    final Map<InetAddress, InetAddress> localAddrToGatewayAddrMap = Collections
            .synchronizedMap(new HashMap<InetAddress, InetAddress>());

    try {/*from w w  w.j  a v  a2s  .  co  m*/
        for (InetAddress localAddress : localAddresses) {
            DatagramChannel unicastChannel = null;
            try {
                unicastChannel = DatagramChannel.open();
                unicastChannel.configureBlocking(false);
                unicastChannel.socket().bind(new InetSocketAddress(localAddress, 0));
            } catch (IOException ioe) {
                IOUtils.closeQuietly(unicastChannel);
                throw ioe;
            }

            channels.add(unicastChannel);
            bindMap.put(unicastChannel, localAddress);
        }
    } catch (IOException ioe) {
        for (DatagramChannel channel : channels) {
            IOUtils.closeQuietly(channel);
        }
        throw ioe;
    }

    UdpCommunicator communicator = null;
    try {
        communicator = new UdpCommunicator(channels);
        communicator.startAsync().awaitRunning();
        communicator.addListener(new UdpCommunicatorListener() {

            @Override
            public void incomingPacket(InetSocketAddress sourceAddress, DatagramChannel channel,
                    ByteBuffer packet) {
                new ExternalAddressNatPmpResponse(packet); // should error out if not valid

                InetAddress localAddress = bindMap.get(channel);
                if (localAddress == null) {
                    return;
                }
                localAddrToGatewayAddrMap.put(localAddress, sourceAddress.getAddress());
            }
        });

        ByteBuffer outBuf = ByteBuffer.allocate(16);
        ExternalAddressNatPmpRequest eanpr = new ExternalAddressNatPmpRequest();
        eanpr.dump(outBuf);

        outBuf.flip();

        for (DatagramChannel channel : bindMap.keySet()) {
            for (InetAddress gateway : gateways) {
                communicator.send(channel, new InetSocketAddress(gateway, 5351), outBuf.asReadOnlyBuffer());
            }
        }

        Thread.sleep(5000L);
    } finally {
        if (communicator != null) {
            communicator.stopAsync().awaitTerminated();
        }
    }

    return new HashMap<>(localAddrToGatewayAddrMap);
}

From source file:net.big_oh.common.web.listener.session.SimpleSessionTrackingListener.java

private static synchronized Map<HttpSession, Object> getSessionsCollectionForServletContext(
        ServletContext servletContext) {
    String servletContextKey = getKeyForServletContext(servletContext);

    Map<HttpSession, Object> sessions = contextToSessionCollectionMap.get(servletContextKey);

    if (sessions == null) {
        // Sessions map must be synchronized because multiple threads will
        // add/remove sessions concurrently.
        ///*from   w w w. j  ava  2  s .c  om*/
        // Sessions map is an instance of WeakHashMap so that this data
        // structure will never prevent the Session from being garbage
        // collected.
        sessions = Collections.synchronizedMap(new WeakHashMap<HttpSession, Object>());
        contextToSessionCollectionMap.put(servletContextKey, sessions);
    }

    return sessions;
}

From source file:org.mule.session.DefaultMuleSession.java

public DefaultMuleSession() {
    id = UUID.getUUID();
    properties = Collections.synchronizedMap(new CaseInsensitiveHashMap/* <String, Object> */());
}

From source file:org.springframework.util.CachingMapDecorator.java

/**
 * Create a CachingMapDecorator,/*from w  w w. j a v  a  2 s  .  c  om*/
 * using an underlying synchronized Map.
 * @param weakKeys whether to use weak references for keys
 */
public CachingMapDecorator(boolean weakKeys) {
    Map internalMap = weakKeys ? (Map) new WeakHashMap() : new HashMap();
    this.targetMap = Collections.synchronizedMap(internalMap);
}

From source file:com.google.code.guice.repository.configuration.PersistenceUnitsConfigurationManager.java

protected PersistenceUnitsConfigurationManager() {
    configurations = Collections.synchronizedMap(new LinkedHashMap<String, PersistenceUnitConfiguration>());
}