Java Code Examples for java.util.Collections.synchronizedMap()

The following are Jave code examples for showing how to use synchronizedMap() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: c4sg-services   File: OrganizationController.java   View Source Code Vote up 6 votes
@CrossOrigin
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ApiOperation(value = "Update an existing organization")
public Map<String, Object> updateOrganization (
		@ApiParam(value = "Updated organization object", required = true) @PathVariable("id") int id,
		@RequestBody @Valid OrganizationDTO organizationDTO) {

   	System.out.println("************** OrganizationController.updateOrganization()" 
               + ": id=" + id  
               + "; organizationDTO=" + organizationDTO 
               + " **************");
   	
	Map<String, Object> responseData = null;
	try {
		OrganizationDTO updatedOrganization = organizationService.updateOrganization(id, organizationDTO);
		responseData = Collections.synchronizedMap(new HashMap<>());
		responseData.put("organization", updatedOrganization);
	} catch (Exception e) {
		System.err.println(e);
	}
	return responseData;
}
 
Example 2
Project: FJ-VDMJ   File: FunctionValue.java   View Source Code Vote up 6 votes
public FunctionValue(INExplicitFunctionDefinition def,
	FunctionValue precondition, FunctionValue postcondition,
	Context freeVariables)
{
	this.location = def.location;
	this.name = def.name.getName();
	this.typeValues = null;
	this.type = (TCFunctionType)def.getType();
	this.paramPatternList = def.paramPatternList;
	this.body = def.body;
	this.precondition = precondition;
	this.postcondition = postcondition;
	this.freeVariables = freeVariables;
	this.checkInvariants = !def.isTypeInvariant;
	this.classdef = def.classDefinition;

	if (Settings.measureChecks && def.measure != null)
	{
		measureName = def.measure;
		measureValues = Collections.synchronizedMap(new HashMap<Long, Stack<Value>>());
	}
}
 
Example 3
Project: javaide   File: GetSynchronizedMapFromHashMapExample.java   View Source Code Vote up 6 votes
public static void main(String[] args) {
  //create HashMap object
  HashMap hashMap = new HashMap();

  /*
    Java HashMap is NOT synchronized. To get synchronized Map from
    HashMap use
    static void synchronizedMap(Map map) method of Collections class.
  */

  Map map = Collections.synchronizedMap(hashMap);

  /*
     Use this map object to prevent any unsynchronized access to original
     HashMap object.
  */

}
 
Example 4
Project: sponge   File: AttributeMapEvent.java   View Source Code Vote up 6 votes
/**
 * Clones this event.
 *
 * @return cloned event.
 */
@SuppressWarnings("unchecked")
@Override
public AttributeMapEvent clone() {
    AttributeMapEvent event = (AttributeMapEvent) super.clone();
    if (attributes != null) {
        switch (clonePolicy) {
        case SHALLOW:
            event.attributes = Collections.synchronizedMap(new LinkedHashMap<>(attributes));
            break;
        case DEEP:
            event.attributes = (Map<String, Object>) SpongeUtils.deepClone((Serializable) attributes);
            break;
        default:
            throw new SpongeException("Unsupported value: " + clonePolicy);
        }
    }

    return event;
}
 
Example 5
Project: Pogamut3   File: WeakHashMapMap.java   View Source Code Vote up 5 votes
@SuppressWarnings("unchecked")
@Override
public Map<SECONDARY_KEY,ITEM> get(Object primaryKey)
{
	Map<SECONDARY_KEY,ITEM> result = super.get( primaryKey );
	if (result != null) return result;
	result = Collections.synchronizedMap( new HashMap<SECONDARY_KEY,ITEM>() );
	super.put( (PRIMARY_KEY)primaryKey, result);
	return result;
}
 
Example 6
Project: GuildBot   File: EngineMap.java   View Source Code Vote up 5 votes
public EngineMap()
{
    this.map = Collections.synchronizedMap(new EnumMap<>(Engine.class));

    final ScriptEngine js = Engine.JAVASCRIPT.newScriptEngine();
    this.map.put(Engine.JAVASCRIPT, js);

    try
    {
        js.eval("engines = {}");
    }
    catch (final ScriptException e)
    {
        throw new RuntimeException(e); // should never happen
    }

    final Bindings engines = (Bindings) js.get("engines");
    engines.put("js", js);

    this.context = js.getContext();
    engines.put("context", this.context);

    for (final Engine engine : Engine.values())
        this.map.computeIfAbsent(engine, e ->
        {
            final ScriptEngine scriptEngine = e.newScriptEngine(this.context);
            ((Bindings) scriptEngine.get("engines")).put(e.getName(), scriptEngine);
            return scriptEngine;
        });
}
 
Example 7
Project: Phoenix-for-VK   File: AccountsSettings.java   View Source Code Vote up 5 votes
@SuppressLint("UseSparseArrays")
AccountsSettings(Context context) {
    this.app = context.getApplicationContext();
    this.tokens = Collections.synchronizedMap(new HashMap<>(1));
    this.preferences = PreferenceManager.getDefaultSharedPreferences(context);

    Collection<Integer> aids = getRegistered();
    for (Integer aid : aids) {
        String token = preferences.getString(tokenKeyFor(aid), null);

        if (nonEmpty(token)) {
            tokens.put(aid, token);
        }
    }
}
 
Example 8
Project: patent-crawler   File: URLPartitionerBolt.java   View Source Code Vote up 5 votes
@Override
public void prepare(Map stormConf, TopologyContext context,
        OutputCollector collector) {

    mode = ConfUtils.getString(stormConf,
            Constants.PARTITION_MODEParamName,
            Constants.PARTITION_MODE_HOST);

    // check that the mode is known
    if (!mode.equals(Constants.PARTITION_MODE_IP)
            && !mode.equals(Constants.PARTITION_MODE_DOMAIN)
            && !mode.equals(Constants.PARTITION_MODE_HOST)) {
        LOG.error("Unknown partition mode : {} - forcing to byHost", mode);
        mode = Constants.PARTITION_MODE_HOST;
    }

    LOG.info("Using partition mode : {}", mode);

    _collector = collector;
    // Register a "MultiCountMetric" to count different events in this bolt
    // Storm will emit the counts every n seconds to a special bolt via a
    // system stream
    // The data can be accessed by registering a "MetricConsumer" in the
    // topology
    this.eventCounter = context.registerMetric("URLPartitioner",
            new MultiCountMetric(), 10);

    final int MAX_ENTRIES = 500;
    cache = new LinkedHashMap(MAX_ENTRIES + 1, .75F, true) {
        // This method is called just after a new entry has been added
        @Override
        public boolean removeEldestEntry(Map.Entry eldest) {
            return size() > MAX_ENTRIES;
        }
    };

    // If the cache is to be used by multiple threads,
    // the cache must be wrapped with code to synchronize the methods
    cache = Collections.synchronizedMap(cache);
}
 
Example 9
Project: Pogamut3   File: HashTriMap.java   View Source Code Vote up 5 votes
/**
 * Removes the requested map. If the map doesn't exist, returns an empty map.
 */
@Override
public Map<SECONDARY_KEY, Map<TERTIARY_KEY,ITEM>> remove(Object primaryKey)
{
	Map<SECONDARY_KEY, Map<TERTIARY_KEY,ITEM>> result = super.remove(primaryKey);
	if (result != null) { return result; };
	return Collections.synchronizedMap( new HashMapMap<SECONDARY_KEY, TERTIARY_KEY, ITEM>(secondaryCapacity, tertiaryCapacity) );
}
 
Example 10
Project: hadoop   File: Configuration.java   View Source Code Vote up 5 votes
/**
 * Load a class by name, returning null rather than throwing an exception
 * if it couldn't be loaded. This is to avoid the overhead of creating
 * an exception.
 * 
 * @param name the class name
 * @return the class object, or null if it could not be found.
 */
public Class<?> getClassByNameOrNull(String name) {
  Map<String, WeakReference<Class<?>>> map;
  
  synchronized (CACHE_CLASSES) {
    map = CACHE_CLASSES.get(classLoader);
    if (map == null) {
      map = Collections.synchronizedMap(
        new WeakHashMap<String, WeakReference<Class<?>>>());
      CACHE_CLASSES.put(classLoader, map);
    }
  }

  Class<?> clazz = null;
  WeakReference<Class<?>> ref = map.get(name); 
  if (ref != null) {
     clazz = ref.get();
  }
   
  if (clazz == null) {
    try {
      clazz = Class.forName(name, true, classLoader);
    } catch (ClassNotFoundException e) {
      // Leave a marker that the class isn't found
      map.put(name, new WeakReference<Class<?>>(NEGATIVE_CACHE_SENTINEL));
      return null;
    }
    // two putters can race here, but they'll put the same class
    map.put(name, new WeakReference<Class<?>>(clazz));
    return clazz;
  } else if (clazz == NEGATIVE_CACHE_SENTINEL) {
    return null; // not found
  } else {
    // cache hit
    return clazz;
  }
}
 
Example 11
Project: hadoop   File: ResourceLocalizationService.java   View Source Code Vote up 5 votes
PublicLocalizer(Configuration conf) {
  super("Public Localizer");
  this.lfs = getLocalFileContext(conf);
  this.conf = conf;
  this.pending = Collections.synchronizedMap(
      new HashMap<Future<Path>, LocalizerResourceRequestEvent>());
  this.threadPool = createLocalizerExecutor(conf);
  this.queue = new ExecutorCompletionService<Path>(threadPool);
}
 
Example 12
Project: Phoenix-for-VK   File: UploadQueueStore.java   View Source Code Vote up 5 votes
@SuppressLint("UseSparseArrays")
UploadQueueStore(@NonNull AppStores base) {
    super(base);
    this.statusUpdatePublishSubject = PublishSubject.create();
    this.queueUpdatesPublishSubject = PublishSubject.create();
    this.timer = Observable.interval(0L, PROGRESS_LOOKUP_DELAY, TimeUnit.MILLISECONDS);
    this.progress = Collections.synchronizedMap(new HashMap<>(0));
}
 
Example 13
Project: fresco_floodlight   File: LearningSwitch.java   View Source Code Vote up 5 votes
/**
 * Adds a host to the MAC/VLAN->SwitchPort mapping
 * @param sw The switch to add the mapping to
 * @param mac The MAC address of the host to add
 * @param vlan The VLAN that the host is on
 * @param portVal The switchport that the host is on
 */
protected void addToPortMap(IOFSwitch sw, MacAddress mac, VlanVid vlan, OFPort portVal) {
	Map<MacVlanPair, OFPort> swMap = macVlanToSwitchPortMap.get(sw);

	if (vlan == VlanVid.FULL_MASK || vlan == null) {
		vlan = VlanVid.ofVlan(0);
	}

	if (swMap == null) {
		// May be accessed by REST API so we need to make it thread safe
		swMap = Collections.synchronizedMap(new LRULinkedHashMap<MacVlanPair, OFPort>(MAX_MACS_PER_SWITCH));
		macVlanToSwitchPortMap.put(sw, swMap);
	}
	swMap.put(new MacVlanPair(mac, vlan), portVal);
}
 
Example 14
Project: Pogamut3   File: WeakHashTriMap.java   View Source Code Vote up 5 votes
/**
 * Returns a HashMap<SECONDARY_KEY,HashMap<TERTIARY_KEY,ITEM>>
 * Never returns null, if the map under primary key doesn't exist, an empty one is added and returned.
 * @param primaryKey
 * @return
 */
@SuppressWarnings("unchecked")
@Override
public Map<SECONDARY_KEY, Map<TERTIARY_KEY,ITEM>> get(Object primaryKey)
{
	Map<SECONDARY_KEY, Map<TERTIARY_KEY,ITEM>> result = super.get(primaryKey);
	if (result != null) { return result; };
	result = Collections.synchronizedMap( new HashMapMap<SECONDARY_KEY,TERTIARY_KEY,ITEM>(secondaryCapacity, tertiaryCapacity) );
	super.put( (PRIMARY_KEY)primaryKey,result);
	return result;
}
 
Example 15
Project: synthea_java   File: Generator.java   View Source Code Vote up 4 votes
private void init(int population, long seed) throws IOException {
  String dbType = Config.get("generate.database_type");

  switch (dbType) {
    case "in-memory":
      this.database = new DataStore(false);
      break;
    case "file":
      this.database = new DataStore(true);
      break;
    case "none":
      this.database = null;
      break;
    default:
      throw new IllegalArgumentException(
          "Unexpected value for config setting generate.database_type: '" + dbType
              + "' . Valid values are file, in-memory, or none.");
  }

  this.numberOfPeople = population;
  this.chws = Collections.synchronizedList(new ArrayList<CommunityHealthWorker>());
  this.seed = seed;
  this.random = new Random(seed);
  this.timestep = Long.parseLong(Config.get("generate.timestep"));
  this.stop = System.currentTimeMillis();
  this.demographics = Demographics.loadByName(Config.get("generate.demographics.default_file"));
  this.logLevel = Config.get("generate.log_patients.detail", "simple");
  this.onlyDeadPatients = Boolean.parseBoolean(Config.get("generate.only_dead_patients"));

  this.totalGeneratedPopulation = new AtomicInteger(0);
  this.stats = Collections.synchronizedMap(new HashMap<String, AtomicInteger>());
  stats.put("alive", new AtomicInteger(0));
  stats.put("dead", new AtomicInteger(0));

  if (Boolean.parseBoolean(
        Config.get("generate.track_detailed_transition_metrics", "false"))) {
    this.metrics = new TransitionMetrics();
  }

  // initialize hospitals
  Hospital.loadHospitals();
  Module.getModules(); // ensure modules load early
  CommunityHealthWorker.workers.size(); // ensure CHWs are set early
  Costs.loadCostData();
}
 
Example 16
Project: guava-mock   File: MapBenchmark.java   View Source Code Vote up 4 votes
@Override Map<Element, Element> create(Collection<Element> keys) {
  return Collections.synchronizedMap(Hash.create(keys));
}
 
Example 17
Project: letv   File: LimitedAgeDiscCache.java   View Source Code Vote up 4 votes
public LimitedAgeDiscCache(File cacheDir, File reserveCacheDir, FileNameGenerator fileNameGenerator, long maxAge) {
    super(cacheDir, reserveCacheDir, fileNameGenerator);
    this.loadingDates = Collections.synchronizedMap(new HashMap());
    this.maxFileAge = 1000 * maxAge;
}
 
Example 18
Project: jaffa-framework   File: JDBCSecurityPlugin.java   View Source Code Vote up 4 votes
/** Flush the cached list of security roles
 */
public static void clearCache() {
    cache = Collections.synchronizedMap(new WeakHashMap<String,List<String>>());
}
 
Example 19
Project: kmanager   File: TaskManager.java   View Source Code Vote up 4 votes
public static void init(AppConfig config) {
	taskFolder = config.getTaskFolder();
	tasks = Collections.synchronizedMap(new HashMap<String, Map<String, TaskContent>>());
}
 
Example 20
Project: fitnotifications   File: TransliteratorRegistry.java   View Source Code Vote up 4 votes
public TransliteratorRegistry() {
    registry = Collections.synchronizedMap(new HashMap<CaseInsensitiveString, Object[]>());
    specDAG = Collections.synchronizedMap(new HashMap<CaseInsensitiveString, Map<CaseInsensitiveString, List<CaseInsensitiveString>>>());
    availableIDs = new ArrayList<CaseInsensitiveString>();
}