Setting and accessing a varibale by two different threads - java

I have two threads, one setting a variable of a class, and the other one accessing the variable by a get method.
public class Parent {
private int value = -1
public int getValue()
return this.value;
}
public void setValue(int value){
this.value = value;
}
private class UpdatingVaribale extends Thread {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
setValue(2);
Thread.currentThread().interrupt();
}
}
}
}
private class GettingVaribale extends Thread {
public void run() {
while (getValue == -1) {
try{
System.out.println(getValue);
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
System.out.println(getValue);
}
}
The problem is that the condition of the while loop in the second thread is always true. The System.out.println(getValue) always prints -1. I am wondering why the second thread doesn't get the new value of value which is 2. I don't think the synchronized matters here since one thread is setting a variable and the other one just accessing the variable.

There are some solutions here:
use standard Java class AtomicInteger for storing your value in multi-threaded safe way. Actually it's the best and fastest way.
add synchronized keyword to your getValue and setValue methods
add volatile java keyword to i field definition
The source of your problem is i variable value actually looks different in different threads cause of CPU speed and memory optimization and you have to specify JVM somehow don't to do this optimization and - opposite - makes the latest i value visible in all threads.
UPDATE code for testing
public class SyncProblem {
public static void main(String[] args) {
Parent parent = new Parent();
new Thread(parent.new GettingVaribale()).start();
new Thread(parent.new UpdatingVaribale()).start();
}
}
class Parent {
private volatile int value = -1;
public int getValue() {
return this.value;
}
public void setValue(int value) {
this.value = value;
}
class UpdatingVaribale implements Runnable {
#Override
public void run() {
while (!Thread.currentThread().isInterrupted()) {
setValue(2);
Thread.currentThread().interrupt();
}
}
}
class GettingVaribale implements Runnable {
#Override
public void run() {
while (getValue() == -1) {
try {
System.out.println(getValue());
Thread.sleep(500);
} catch (InterruptedException e) {
}
}
System.out.println(getValue());
}
}
}

Related

Inline runnable with constructor?

I'm looking to use a thread to process something in the background. Since this code isn't used anywhere else & is not complex I'd like to use an inline function. However the function needs a copy of an attribute at the time the thread was created i.e.: I'd like it if the output from the following example 'true' instead of 'false'
public class InlineThreadTest {
boolean value;
public static void main(String[] args) {
new InlineThreadTest();
}
InlineThreadTest() {
value = true;
java.util.concurrent.Executors.newSingleThreadExecutor().execute(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
System.out.println(value);
}
});
value = false;
}
}
... I can do what I'm looking to do by creating a separate class that implements Runnable, but having this inline seems like something that might be good.
I had a look # https://stackoverflow.com/a/362443/64696 , but cannot figure out how to mold this to my use case.
Runnable implementation is a thread and thread won't return any value. The ExecutorService.execute method just runs the thread and you have no way to get the state of the thread whether it was executed or not.
If you want to check for the task (not thread) executed by ExecutorService you should use Callable and work with sumbit(). Your modified example:
public class InlineThreadTest {
boolean value;
public static void main(String[] args) {
new InlineThreadTest();
}
InlineThreadTest() {
value = true;
java.util.concurrent.Future<Boolean> f =
java.util.concurrent.Executors.newSingleThreadExecutor().submit(new Callable<Boolean>() {
public Boolean call() {
System.out.println(value);
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
value = false;
return value;
}
});
try {
System.out.println(f.get()+" or value="+value);
} catch (Exception ex) { }
}
}
You'll get 2 lines
true
false or value=false

Read field stale value after object construction

I'm reading a book "Java concurrency in practice" by Brian Goetz. Paragraphs 3.5 and 3.5.1 contains statements that I can not understand.
Consider the following code:
public class Holder {
private int value;
public Holder(int value) {
this.value = value;
}
public void assertValue() {
if (value != value) throw new AssertionError("Magic");
}
}
class HolderContainer {
// Unsafe publication
public Holder holder;
public void init() {
holder = new Holder(42);
}
}
Author states that:
In Java, Object constructor first writes default values to all fields before subclass constructor run.
Therefore it's possible to see field default value as a stale value.
Thread may see stale value the first time it reads a field and then a more up-to-date value the next time, which is why assertNĀ  can throw AssertionError.
So, according to the text, with some unlucky timing it is possible that value = 0; and in the next moment value = 42.
I agree with point 1 that Object constructor firstly fills fields with default values. But I don't understand points 2 & 3.
Let's update authors code and consider the following example:
public class Holder {
int value;
public Holder(int value) {
//Sleep to prevent constructor to finish too early
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.value = value;
}
public void assertValue() {
if(value != value) System.out.println("Magic");
}
}
I've added Thread.sleep(3000), to force thread to wait before object will be fully constructed.
public class Tests {
private HolderContainer hc = new HolderContainer();
class Initialization implements Runnable {
public void run() {
hc.init();
}
}
class Checking implements Runnable {
public void run() {
hc.holder.assertValue();
}
}
public void run() {
new Thread(new Initialization()).start();
new Thread(new Checking()).start();
}
}
In example:
first thread inits holder object
second thread calls assertValue
Main Thread runs two threads:
new Thread(new Initialization()).start(); It tooks 3 seconds to fully construct Holder object
new Thread(new Checking()).start(); since Holder object still not constructed code will throw an NullPointerException
Therefore, it's impossible to emulate situation when field has default value.
My Questions:
Author was wrong about this concurrency problem?
Or It it impossible to emulate behaviour for fields default values?
I tried to test the problem with the following code.
Test:
public class Test {
public static boolean flag =true;
public static HolderContainer hc=new HolderContainer();
public static void main (String args[]){
new Thread(new Initialization()).start();
new Thread(new Checking()).start();
}
}
class Initialization implements Runnable {
public void run() {
while (Test.flag){
Test.hc=new HolderContainer();
Test.hc.init();
}
}
}
class Checking implements Runnable {
public void run() {
try{
Test.hc.holder.assertValue();
}
catch (NullPointerException e) {
}
}
}
Holder:
public class Holder {
private int value;
public Holder(int value) {
this.value = value;
}
public void assertValue() {
if (value != value) {
System.out.println("Magic");
Test.flag=false;
}
}
}
class HolderContainer {
public Holder holder;
public void init() {
holder = new Holder(42);
}
}
I never got the program to evaluate value!=value to true.
I don't think this proves anything and didn't run it for more than a couple minutes, but I hope this will be a better starting point for a well designed test or at least help to figure out some possible flaws in the tests.
I tried to insert a sleep between Test.hc=new HolderContainer(); and Test.hc.init();, between public Holder holder; and public void init() { and after public void init() {.
I am also concerned that checking if a value is null or catching the NullPoiterException may affect the timing too much.
Please note that the currently accepted answer to Improper publication of Java Object Reference says this problem is probably impossible under an x86 architecture. It may also be JVM dependent.
You are probably trying to simulate a concurrency scenario, which I believe is very hard to simulate using a couple of threads.
The following test-case which you have written is not correct at all is more likely to throw a NullPointerException.
public class Tests {
private HolderContainer hc = new HolderContainer();
class Initialization implements Runnable {
public void run() {
hc.init();
}
}
class Checking implements Runnable {
public void run() {
hc.holder.assertValue();
}
}
public void run() {
new Thread(new Initialization()).start();
new Thread(new Checking()).start();
}
}
What if your Checking Thread executes before Initialization one??
Also putting a sleep there simply means that executing thread will sleep and does tell you about the internal atomic operations being performed by then.
Did not reproduce it with your code. Here is an example to emulate un-safe publication. The strategy is let one thread publication Holder and let another check its value.
class Holder {
private volatile int value;
public Holder(int value, HolderContainer container) {
container.holder = this; // publication this object when it is not initilized properly
try {
Thread.sleep(10);
} catch (Exception e) {
}
this.value = value; // set value
}
public int getValue() {
return value;
}
}
class HolderContainer {
public Holder holder;
public Holder getHolder() {
if (holder == null) {
holder = new Holder(42, this);
}
return holder;
}
}
public class Tests {
public static void main(String[] args) {
for (int loop = 0; loop < 1000; loop++) {
HolderContainer holderContainer = new HolderContainer();
new Thread(() -> holderContainer.getHolder()).start();
new Thread(() -> {
Holder holder = holderContainer.getHolder();
int value1 = holder.getValue(); // might get default value
try {
Thread.sleep(10);
} catch (Exception e) {
}
int value2 = holder.getValue(); // might get custom value
if (value1 != value2) {
System.out.println(value1 + "--->" + value2);
}
}).start();
}
}
}
Sleeping 3 seconds before assigning the field in the constructor does not matter because for value != value to be true, the first read of value must produce a different result than the second one, which happens immediately after.
The Java Memory Model does not guarantee that values assigned to fields in constructors are visible to other threads after the constructor finishes.
To have this guarantee, the field must be final.
Here's a program that produces the bug on x86.
It must be run with the VM option: -XX:CompileCommand=dontinline,com/mypackage/Holder.getValue
package com.mypackage;
public class Test {
public static void main(String[] args) {
new Worker().start();
int i = 1;
while (true) {
new Holder(i++);
}
}
}
class Holder {
private int value;
Holder(int value) {
Worker.holder = this;
this.value = value;
}
void assertSanity() {
if (getValue() != getValue()) throw new AssertionError();
}
private int getValue() { return value; }
}
class Worker extends Thread {
static Holder holder = new Holder(0);
#Override
public void run() {
while (true) {
holder.assertSanity();
}
}
}
By disallowing Holder#getValue() to be inlined, we prevent the two subsequent reads of value to be collapsed into a single one.
This optimization prevents the code in the book from producing the bug.
However, the book author is still correct, since this optimization is not mandatory, so from the Java Memory Model perspective, the code is incorrect.
The assertSanity() method is equal to:
int snapshot1 = getValue();
// <--- window of vulnerability, where the observed value can change
// if you chose to sleep 3 seconds, you would want to do it here
// takes very little time, less than 1 nanosecond
int snapshot2 = getValue();
if (snapshot1 != snapshot2) throw new AssertionError();
So the first read of value could produce the default value of int which is 0 (called the stale value and assigned in the Object() constructor), and the second read could produce the value assigned in the Holder(int) constructor.
This would happen if for example the value assigned in the constructor were propagated to the thread calling assertSanity() in the exact moment between the two loads of value (window of vulnerability).
The same would happen if we delayed the second read in some other way, like:
int snapshot1 = this.value;
Thread.interrupted();
int snapshot2 = this.value;
if (snapshot1 != snapshot2) throw new AssertionError();

How notify second thread of variable's change

I have two threads. The first changes the value of variable Data. And second one print the value if its value has changed. I am trying to do that second thread just print each time that the variable's value changed, but I don't reach success. Someone can help me?
thread 1
class someservice{
volatile int data;
Boolean Flag = false;
public void mymethod(){
flag = true;
for (Integer i = 1; i < sheet.getRows(); i++) {
data = someMethod(); //this method when called return a new
//value
}
flag = false;
...
}
}
thread 2
Promise p = task {
try {
while (true) {
if (engineService.getFlag()) {
print(someservice.data);
}else{
break;
}
}
} catch(Throwable t) {
...
}
}
Since you mention Promises, I infer you are familiar with future/ promise in +C++11
in java there is a similar approach, with future callable...
public class HW5 {
public static void main(String[] argv) throws InterruptedException, ExecutionException {
FutureTask<Boolean> myFutureTask = new FutureTask<>(new Callable<Boolean>() {
#Override
public Boolean call() throws Exception {
// implement the logic here and return true if everything was
// ok, false otherwise.
Thread.sleep(5000);
System.out.println("dddd");
return System.currentTimeMillis() % 2 == 0;
}
});
ExecutorService executor = Executors.newFixedThreadPool(1);
executor.execute(myFutureTask);
Boolean result = myFutureTask.get();
System.out.println("Done!");
}
}
FutureTask in a class that takes a callable which can return an Object after its job is done... in Order to execute the Future task you can use a Executor service, especifically calling the method execute, since you need to wait for the thread to do the job then is necessary that you call Future.get, that will basically blocks the main thread until the future is done, to verify the result, just read the variable result..
You could use the notify() and notifyAll() methods within thread. Check out this link: https://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
public synchronized notifyJoy() {
joy = true;
notifyAll();
}
You have to look up more data about Concurrent programming,I can tell you now some basics,well,not so so basic,but i will do my best:
Here,you have a Monitor,it is an abstract concept,in resume,a Monitor is a
class with all it's
method using"syncronized"
as modifier, it means,
that only
one thread
can access
the method
at once.So,
in the
monitor is
the variable
that you
want to print,
and the"flag",
that tells you if
the variable
was modified.Finally,
you can
see the
most important thing,the"wait()"and"notify()"methods,
those method
stops the thread,or"play"
them again.
You ask
here in
the printValue() method, if your variable was changed, if the variable was'nt change, put the thead to sleep with the wait() method, and when the other
method changeValue() is executed, the value is modified, and the notify() method is called, waking up the thread, so, doing all this, you can guarantee three things:
Safety: meaning that the threads will do that you want
Absence of deadlock: meaning that the thread that is put to sleep, will be awake in the future.
Mutex: meaning that only one thread is executing the critical code, for example, the op. "++" is not atomic, is Subdivided inside in more the one action, create a local var, read the var, sum, and asign, so, if more than one thread are in the game, the value may not be consecutive, example:
i = 0;
i ++;
output: 1;
output: 2;
output: 3;
output: 5;
output: 4;
output: 7;
That could happen, and even so, that will happen in the next code, because there a more than one thread executing. Well, this is the way to program with several threads, more or less
public class Monitor {
private int value = 0;
public static boolean valueHasChanged = false;
public synchronized int changeValue(int newValue){
this.value = newValue;
Monitor.valueHasChanged = true;
this.notify();
return this.value + 1;
}
public synchronized void printValue(){
while(!Monitor.valueHasChanged){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(this.value);
Monitor.valueHasChanged = false;
}
public static void main(String[] args) {
Monitor ac = new Monitor();
BClass t1 = new BClass(ac);
AClass t2 = new AClass(ac);
t1.start();
t2.start();
}
public int getValue() {
return this.value;
}
}
Now the threads:
public class AClass extends Thread{
private Monitor ac;
public AClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
while(true){
this.ac.printValue();
}
}
}
And finally:
public class BClass extends Thread{
private Monitor ac;
public BClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
int v = 0;
while(true){
this.ac.changeValue(v);
v++; // this sum is not secure, if you want to print an
// ascending order, the code is diferent, I will show in
// above.
}
}
Now, if you want an ordered print:
the monitor will look like:
public class Monitor {
private int value = 0;
public boolean valueHasChanged = false;
private boolean hasPrint = true;
public synchronized void changeValue(int newValue) {
this.value = newValue;
this.valueHasChanged = true;
this.notify();
}
public synchronized void changeValuePlusOne() {
while (!hasPrint) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.value++;
this.valueHasChanged = true;
this.hasPrint = false;
this.notifyAll();
}
public synchronized void printValue() {
while (!this.valueHasChanged) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(this.value);
this.valueHasChanged = false;
this.hasPrint = true;
this.notifyAll();
}
public static void main(String[] args) {
Monitor ac = new Monitor();
BClass t1 = new BClass(ac);
AClass t2 = new AClass(ac);
t1.start();
t2.start();
}
public int getValue() {
return this.value;
}
}
And the Threads:
public class BClass extends Thread{
private Monitor ac;
public BClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
while(true){
this.ac.changeValuePlusOne();
}
}
}
The other Thread look equals:
public class AClass extends Thread{
private Monitor ac;
public AClass(Monitor ac) {
this.ac = ac;
}
#Override
public void run() {
while(true){
this.ac.printValue();
}
}
}

Why doesn't my consumer consume Integer values? (Producer-Consumer with wait and notify)

I have two threads. One is a producer (class Deliver), second is consumer (class Produce). I want to simulate door producer. So producer deliver wood that consumer can produce a door. But i do not real get how to communicate between those two threads. Now when i run my program only wood is delivered but doors are not produced. I do not get why.
public class Deliver implements Runnable {
private static int MAX_STOCKPILE = 15;
private Integer wood;
public Deliver(Integer wood) {
this.wood = wood;
new Thread(this, "Deliver").start();
}
public synchronized void deliver() throws InterruptedException{
Thread.sleep(500);
if (wood < MAX_STOCKPILE) {
wood++;
System.out.println("Wood delivered" + " | Wood stockpile: " + wood);
notify();
}
else {
wait();
}
}
#Override
public void run() {
while (true) {
try {
deliver();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Produce implements Runnable{
private Integer wood;
public Produce(Integer wood) {
this.wood = wood;
new Thread(this, "Produce").start();
}
public synchronized void produce() throws InterruptedException{
Thread.sleep(1000);
if (wood == 10) {
wood -= 10; //produce
System.out.println("Doors produced");
notify();
}
else {
wait();
}
}
#Override
public void run() {
while (true) {
try {
produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Main {
public static void main(String[] args) {
Integer wood = 0;
new Deliver(wood);
new Produce(wood);
}
}
Now when i run my program only wood is delivered but doors are not produced. I do not get why
There are multiple issues with your code :
When you mark an instance method as synchronized, any thread entering that method will obtain a lock on this (i.e the instance on which the method was called). Since this in Deliver refers to a Deliver instance and this in Produce refers to a Produce instance, the wait and notify calls are practically useless in this case as they are not interested in the same objects.
The golden rule to remember in Java is that it uses pass-by-value semantics. Primitives and references are therefore always passed by value. While you may assume that both Deliver and Produce will be modifying the same Integer passed to them from main, that is not the case.
That said, I would highly recommend that you consider using something like an ArrayBlockingQueue for solving this instead of reinventing the wheel with wait and notify.
Change
if (wood == 10) {
to
if (wood >= 10) {
in case the thread doesn't catch it when it == 10
Something to note is that Integer is immutable.
When you change the reference to the Integer you are creating a new object which has no relationship to the previous object.
What you want this an object which is shared between the two threads so when you change the value (but not the reference) they are looking at the same value.
e.g.
wood -= 10;
is the same as
wood = Integer.valueOf(wood.intValue() - 10);
I suggest using AtomicInteger and making the reference to it final to ensure you don't accidentally try to change the reference.
As Andrew Jenkins suggests; if you lock, notify/wait on unrelated objects, you don't have any thread safety. Once you have a shared object, you have to lock, notify/wait on that shared object.
I'll throw my solution into the mix, taking into account Peter Lawrey's advice about using AtomicInteger.
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) {
AtomicInteger wood = new AtomicInteger(0);
new Deliver(wood);
new Produce(wood);
}
}
public class Deliver implements Runnable {
private static int MAX_STOCKPILE = 15;
private final AtomicInteger wood;
public Deliver(AtomicInteger wood) {
this.wood = wood;
new Thread(this, "Deliver").start();
}
public void deliver() throws InterruptedException{
Thread.sleep(500);
synchronized(wood) {
if (wood.intValue() < MAX_STOCKPILE) {
wood.addAndGet(1);
System.out.println("Wood delivered" + " | Wood stockpile: " + wood);
wood.notify();
} else {
wood.wait();
}
}
}
#Override
public void run() {
while (true) {
try {
deliver();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class Produce implements Runnable{
private final AtomicInteger wood;
public Produce(AtomicInteger wood) {
this.wood = wood;
new Thread(this, "Produce").start();
}
public void produce() throws InterruptedException{
synchronized(wood) {
if (wood.intValue() >= 10) {
wood.addAndGet(-10); //produce
System.out.println("Doors produced");
wood.notify();
}
else {
wood.wait();
}
}
}
#Override
public void run() {
while (true) {
try {
produce();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Key changes:
We use a mutable object to communicate between threads (AtomicInteger).
We synchronize on the mutable object, not the thread being run.

Synchronization doesnt quite work

I have the following code which I'm trying to write a LRU Cache. I have a runner class that I'm running against random capacity of the cache. However, Cache size is exceeding it is capacity. When I make the FixLRU method synchronized, it becomes more accurate when the cache size is more than 100 however it gets slower. When I remove the synchronized keyword, cache is becoming less accurate.
Any ideas how to make this work properly? more accurate?
import java.util.concurrent.ConcurrentHashMap;
public abstract class Cache<TKey, TValue> implements ICache<TKey,TValue>{
private final ConcurrentHashMap<TKey,TValue> _cache;
protected Cache()
{
_cache= new ConcurrentHashMap<TKey, TValue>();
}
protected Cache(int capacity){
_cache = new ConcurrentHashMap<TKey, TValue>(capacity);
}
#Override
public void Put(TKey key, TValue value) {
_cache.put(key, value);
}
#Override
public TValue Get(TKey key) {
TValue value = _cache.get(key);
return value;
}
#Override
public void Delete(TKey key) {
_cache.remove(key);
}
#Override
public void Purge() {
for(TKey key : _cache.keySet()){
_cache.remove(key);
}
}
public void IterateCache(){
for(TKey key: _cache.keySet()){
System.out.println("key:"+key+" , value:"+_cache.get(key));
}
}
public int Count()
{
return _cache.size();
}
}
import java.util.concurrent.ConcurrentLinkedQueue;
public class LRUCache<TKey,TValue> extends Cache<TKey,TValue> implements ICache<TKey, TValue> {
private ConcurrentLinkedQueue<TKey> _queue;
private int capacity;
public LRUCache(){
_queue = new ConcurrentLinkedQueue<TKey>();
}
public LRUCache(int capacity){
this();
this.capacity = capacity;
}
public void Put(TKey key, TValue value)
{
FixLRU(key);
super.Put(key, value);
}
private void FixLRU(TKey key)
{
if(_queue.contains(key))
{
_queue.remove(key);
super.Delete(key);
}
_queue.offer(key);
while(_queue.size() > capacity){
TKey keytoRemove =_queue.poll();
super.Delete(keytoRemove);
}
}
public TValue Get(TKey key){
TValue _value = super.Get(key);
if(_value == null){
return null;
}
FixLRU(key);
return _value;
}
public void Delete(TKey key){
super.Delete(key);
}
}
public class RunningLRU extends Thread{
static LRUCache<String, String> cache = new LRUCache<String, String>(50);
public static void main(String [ ] args) throws InterruptedException{
Thread t1 = new RunningLRU();
t1.start();
Thread t2 = new RunningLRU();
t2.start();
Thread t3 = new RunningLRU();
t3.start();
Thread t4 = new RunningLRU();
t4.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(cache.toString());
cache.IterateCache();
System.out.println(cache.Count());
}
#Override
public void run() {
for(int i=0;i<100000;i++)
cache.Put("test"+i, "test"+i);
}
}
I would clean up additional entries after adding your entry. This minimises the time that the cache will be larger than you wanted. You can also trigger size() to perform a cleanup.
Any ideas how to make this work properly?
Does your test reflect how your application behaves? It may be that the cache behaves properly (or much closer to it) when you have not hammering it. ;)
If this test does reflect your application behaviour then perhaps an LRUCache is not the best choice.
Your problem seems to be that you aren't using the special synchronized version of the put method putIfAbsent(). If you don't use it, a ConcurrentHashMap behaves as if not synchronized - like a normal Map eg HashMap.
When you use it, you must continue to use only the returned value, so your Put() method doesn't have the correct signature (it should return TValue) to support concurrency. You'll need to redesign your interface.
Also, in java land, unlike .Net land, we name our methods with a leading lowercase, eg put(), not Put(). It would behove you to rename your methods thus.

Categories