Concurrent Programming Fundamentals — Sharing Objects (Part 2)

public class UnsafeStates {
private String [] states = new String [] {"AK", "AL", ...};
public String [] getStates () {return states;}
}
public class ThisEscape {

public ThisEscape(EventSource source) {
source.registerListener(
new EventListener() {
public void onEvent(Event e) {
//doSomething
}
}
);
}

}

Do not allow the this reference to escape during construction.

3. Thread confinement

private long numberOfPeopleNamedGowthamy(List<Person> people) {                                        List<Person> localPeople = new ArrayList<>();                             
localPeople.addAll(people);
return localPeople
.stream()
.filter(person ->
person.getFirstName().equals("Gowthamy"))
.count();
}

It’s better, if we document or comment when defining this variable, since generally it’s only in the current developer’s mind to not let it escape, and in future another developer may mess up.

public class ThreadConfinementUsingThreadLocal {                                                         
public static void main(String[] args) {
ThreadLocal<String> stringHolder = new ThreadLocal<>();

Runnable runnable1 = () -> {
stringHolder.set("Thread in runnable1");
try {
Thread.sleep(5000);

System.out.println(stringHolder.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Runnable runnable2 = () -> {
stringHolder.set("Thread in runnable2");
try {
Thread.sleep(2000);
stringHolder.set("string in runnable2 changed");
Thread.sleep(2000);
System.out.println(stringHolder.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
};

Runnable runnable3 = () -> {
stringHolder.set("Thread in runnable3");
try {
Thread.sleep(5000);
System.out.println(stringHolder.get());
} catch (InterruptedException e) {
e.printStackTrace();
}
};
Thread thread1 = new Thread(runnable1);
Thread thread2 = new Thread(runnable2);
Thread thread3 = new Thread(runnable3);
thread1.start();
thread2.start();
thread3.start();
}
}
string in runnable2 changed
Thread in runnable1
Thread in runnable3

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store