In a not thread-safe class you must avoid to use class variables at they can be shared by different threads end executing contexts.
But if you instanciate an external class which itself has class variables, will these be thread-safe ?
In this example, is there any risk to share the counter variable between threads ?
class MyNotThreadSafeClass()
{
private integer sharedvariable;
public void callAnOtherClass()
{
myClass o = new myClass();
System.out.println(o.increment(counter));
}
}
class myClass()
{
private integer counter;
public void increment() { return(counter++); }
}
Thank you if you have an idea (documentation is not very clear in this thread-safe topic).
This works since you never pass o to another thread. So no other thread can ever access this instance.
The general pattern is: If you share one instance between several threads, then you need to have some sort of synchronization.
If you don't share an instance, it doesn't matter if there are more threads.
Related
I have a class defined as:
class Artifacts {
private static boolean isThreadStarted = false;
private SomeClass someClass;
public static void startThread() {
isThreadStarted = true;
}
public static void setSomeClass(SomeClass = someClass1) {
if(isThreadStarted) {
someClass = someClass1;
}
}
public static SomeClass getSomeClass() {
return someClass;
}
}
Now the use case is that a method will make the value of isThreadStarted to be true. After that, a thread will start and using the value of someClass.There can be multiple threads setting and getting the value of someClass. I want to make this thread safe.
There is an annotation #ThreadSafe and there is a function synchronized static which I guess will do the thing. Please help in deciding the right approach.
Two simple improvements you can make to make this class more threadsafe for the intended purpose are to make the someClass field volatile, and to use AtomicBoolean for the isThreadStarted field.
class Artifacts {
private static AtomicBoolean isThreadStarted = new AtomicBoolean(false);
private volatile SomeClass someClass;
The volatile will ensure that any other thread that has a reference to an Artifact instance, does not cache the someClass instance. The JVM will always retrieve the someClass field from one main source. If volatile is not used, then other threads may cache someClass and changes it it may not be reflected across all the threads that are using it.
AtomicBoolean gives you volatile feature plus atomic operations, like check and set in the same operation. Here is a excerpt from the Javadoc.
A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:
So, your main concern is that multiple threads will read and write the someClass field (and maybe the isThreadStarted field, as well).
I don't know what the #ThreadSafe annotation does, it's not part of Java Standard Edition 8.
The basic way to make that thread-safe is to use the synchronized keyword. Typically, you'd encapsulate access to your field in getter and setter methods and make them synchronized.
public class Test {
private String someText;
public synchronized String getSomeText() {
return someText;
}
public synchronized void setSomeText(String someText) {
this.someText = someText;
}
}
But typically the multi-thread problems aren't tied to a single field.
If different threads of your program use a (thread-shared) object, you run into the risk that one thread modifies two fields A and B (e.g. moves money from A to B by subtracting from A and adding to B), and in-between some other thread reads A and B (e.g. calculates the current amount of A plus B) and sees an inconsistent state (amount subtracted from A, but not yet added to B).
The classical solution is to ensure that of all these code sections where the instance is read or modified, only one at a time is allowed to run. And that's what synchronized does.
Life_Hacker,
1st way
use static synchronized keyword with function to make Class Level lock in multithreading environment.
example :
public static synchronized void setSomeClass(Artifacts.class) {
if(isThreadStarted) {
someClass = someClass1;
}
}
2nd way
inside function definition, you can create Synchronize Block
example:
public static void setSomeClass(SomeClass = someClass1) {
synchronized(this){
if(isThreadStarted) {
someClass = someClass1;
}
}
}
2nd way is best approach
In this oracle example of intrinsic locks and many more, the monitor object is never declared as volatile, final or nor it has any distinction from any other regular object
public class MsLunch {
private long c1 = 0;
private long c2 = 0;
private Object lock1 = new Object();
private Object lock2 = new Object();
public void inc1() {
synchronized(lock1) {
c1++;
}
}
public void inc2() {
synchronized(lock2) {
c2++;
}
}
}
There are plenty of questions that debate volatile versus synchronization blocks
volatile fields and synchronized blocks,
difference between volatile and synchronized in java
when to use volatile vs synchronization in multithreading in java,
do you ever use the volatile keyword in java
and immutable objects
what are immutable objects,
immutability and synchronization in java
immutable objects java concurreny)in multithreading.
As a side note, I understand this subtle difference between declaring an object final versus immutability why-can-final-object-be-modified and why declaring the lock object as final would not make it immutable.
However, we have the famous pattern of the singleton class lazy initialization where the use of the volatile variables is essential.
public class SingletonDemo {
private static volatile SingletonDemo instance;
private SingletonDemo() { }
public static SingletonDemo getInstance() {
if (instance == null ) {
synchronized (SingletonDemo.class) {
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
}
which in the above code example uses the Class object as lock.
Since for an object which is accessed by multiple threads you need to use some mechanism as above to ensure atomic access, why is that for intrinsic lock object there is no need for any special treatment?
These locks don't need special treatment because the MsLunch object itself needs to be published before it can be seen by any additional threads.
public class MyMain {
public static void main(String... args) {
MsLunch lunch = new MsLunch();
// ...
This is thread safe because local variables ("lunch") are not visible to more than one thread.
Next the class below makes the local reference visible to all threads in the system. When that happens we need to use volatile. The volatile keyword effectively creates a memory barrier that publish the object safely. This includes all writes made before the assignement including writes made internally when constructing the object.
C.f. Safe Publication
public class MyMain {
public static volatile MsLunch publicLunch;
public static void main(String... args) {
MsLunch lunch = new MsLunch();
publicLunch = lunch;
//...
}
}
It probably should be final. But final isn't anything really special- its only required in one special case (referencing a variable declared inside a function into an anonymous class). Any other case final is simply a reminder for the programmer to not overwrite the variable- you can remove every other use of the word final in your program and it will work perfectly. You're right, a programmer could assign to it and then cause problems. But if he doesn't, there's no issue. So go ahead and use final when you create one, but it isn't necessary for the program to compile.
As for static- depends on the usecase. Do you want to monitor all instances of a class, or each instance independently? In the first case, you use static in the second case you don't.
Volatile isn't needed because the object isn't actually being changed by the multiple threads. Its being synchronized on. This is completely different, and an older part of the Java language than volatile. There's no need to make the variable volatile as you won't be altering it, and the internal data structures used to monitor on an object already know they need to be thread safe (and in a stronger manner than volatile promises).
In this oracle example of intrinsic locks and many more, the monitor object is never declared as volatile, final or nor it has any distinction from any other regular object.
That's not true. See below.
Since for an object which is accessed by multiple threads you need to use some mechanism as above to ensure atomic access, why is that for intrinsic lock object there is no need for any special treatment?
It does have special treatment. It is synchronised on.
Had there been a
public synchronized void deletePerson(Person p)
{ mySet.remove();}
then too it would remain threadsafe?
This class is threadsafe because there is only one mutable field in it (mySet) , it is private and all accesses to it are synchronized.
Yes, public synchronized void deletePerson(Person p) { mySet.delete();} would still keep this class thread-safe.
Also, note that the reference to mySet is not escaping from this class. Which is also important.
Since mySet is private and not exposed outside the class through a getMySet method, you can access to the state of the object only with the methods addPerson, containsPerson and deletePerson.
Since these 3 methods are synchronized, only one of them can access to the instance of the class (and change its state) at any given time, so the class is Thread Safe.
I am working on the following piece of code. Two threads requiring their own instance of a singleton. Thread Local is an obvious solution to this. However I am still facing issues running the threads with their own local copy. I have an example of the scenario in a couple of java classes.
public class Singleton1 {
private int i = 0;
private static Singleton1 instance;
private Singleton1() {
}
public static final Singleton1 getInstance() {
if (instance == null) {
instance = new Singleton1();
}
return instance;
}
public int increment() {
return i++;
}
}
public class Holder1 {
private final Singleton1 instance;
public Holder1() {
ThreadLocalSingleton1 singleton1 = new ThreadLocalSingleton1();
instance = singleton1.get();
}
public int increment() {
return instance.increment();
}
private class ThreadLocalSingleton1 extends ThreadLocal<Singleton1> {
#Override
protected Singleton1 initialValue() {
return Singleton1.getInstance();
}
}
}
public class HolderTest {
/**
* #param args
*/
public static void main(String[] args) {
HolderTest test = new HolderTest();
HolderThread thread1 = test.getHolderThread("thread1");
HolderThread thread2 = test.getHolderThread("thread2");
thread1.run();
thread2.run();
}
public HolderThread getHolderThread(String name) {
return new HolderThread(name);
}
private class HolderThread implements Runnable {
String name;
Holder1 holder1 = new Holder1();
public HolderThread(String name) {
this.name = name;
}
#Override
public void run() {
while (true) {
System.out.println(name + " " + holder1.increment());
}
}
}
When the ThreadLocal wrappers call getInstance on the Singleton classes I do not get a new instance each time? How do I make this work for my purposes?
The code above is a simple version of the actual code I am working with. I have Singleton classes which I cannot change from being singletons. I am creating a test client which needs to run as a single process but with many threads. Each of these threads needs to have its own instance of these singletons.
Your target class shall not be singleton, but you must access it just using the ThreadLocal, and creating a new instance if ThreadLocal instance is empty (doesn't hold a reference to an instance of your target object).
Another solution is to make your Target class singleton, and hold its state in ThreadLocal variables.
You seem to be painted into a corner.
On the one hand, you have an existing codebase that you need to test and that code uses (genuine, properly implemented) singleton objects. In particular, the declaration of the Singleton1() constructor as private in your examplar class Singleton1 makes it impossible to declare a subclass.
On the other hand, your testing requires you to write a client with lots of these Singleton1 instances.
On the face of it, that is impossible. There is no way to make two instances of the Singleton1 class in the JVM, and there is no way to declare a (compilable / loadable) subclass of Singleton1.
This is per design; i.e. it is what the designer of the Singleton1 class intended. (And if not, then the answer is to change Singleton1 to make it easier to test. For example, by making the Singleton1 constructor not private so that multiple instances can be created for test purposes. )
(For instance, your current attempt at implementing ThreadLocalSingleton1 fails because the Singleton1.getInstance() returns the global instance of Singleton1. No matter what you do, there is no way to create any other instance of the Singleton1 class.)
However, I can think of two workarounds for your particular use-case.
I am writing a test client which needs to run as as single java process. The test client is used for load testing will have X threads accessing a server using a core project (that I cannot change too much) which has many singletons. The singletons hold state which will be required per thread.
Here are the workarounds:
Instead of running one JVM with N instances of your test thread, run N separate JVMs each with a single test thread. Each JVM / test thread can have its own instance of Singleton.
Have each of your test threads create a new classloader, and use that classloader to dynamic load the Singleton1 class and everything with a direct or indirect static dependency on the Singleton1 type. The idea is for each classloader to load its own copy of the Singleton1 class. Since each copy will be a distinct type1, it will have its own private static Singleton1 instance variable.
Note that these workarounds do provide not "thread-local" instances of your Singleton1 class. That is both technically impossible ... and a contradiction of the definition of singleton.
In both cases you have true singleton instances, but they are instances of different Singleton1 types ... for different reasons.
1 - At runtime, the type of a class instance is conceptually a pair consisting of the fully qualified name of the class and the identity of the classloader that loaded the class. If the same bytecode file is loaded by different classloaders, then you get different runtime types.
Do you mean something like this?
private static final ThreadLocal<AtomicInteger> COUNTER = new ThreadLocal<AtomicInteger>() {
#Override
protected AtomicInteger initialValue() {
return new AtomicInteger();
}
};
public static int incrementAndGet() {
return COUNTER.get().incrementAndGet();
}
Please, take a look at the ThreadLocal working example below:
public class YourDataHolder {
private static ThreadLocal dataVariable = new ThreadLocal();
private static YourDataHolder dataHolderVar;
private YourDataHolder() { }
public void storeDataToThreadLocal (String userName) {
dataVariable.set(userName);
}
public String readDataFromThreadLocal () {
if (dataVariable.get() != null) {
return (String) dataVariable.get();
}
}
public static ServiceVersionHolder getInstance () {
if (dataHolderVar == null) {
dataHolderVar = new YourDataHolder();
}
return dataHolderVar;
}
}
Use synchronized for multithreading.
public static synchronized final Singleton getInstance() {
This way the threads will "lock" the method: only one thread will be allowed to enter the method at a time, other threads will block until the method is unlocked (the thread executing it leaves). You won't have those concurrency issues.
Also you don't need 2 singletons (which IMHO actually makes no sense and defeats the very own purpose of a singleton...).
I know when you want to lock method to be executed by only one thread you declare it with synchronized keyword.
What about classes, how to provide a lock on an entire class of objects when a thread
is executing some code on an instance of that class?
In other words, when a thread is executing a method on an object, no other thread should be
allowed to execute the same method even on a different instance of the same class.
You synchronize on a specific object, either some designated static lock object, or the class object (which happens when static methods are declared to be synchronized):
class X {
private static final Object lock = new Object();
public void oneAtATime() {
synchronized (lock) {
// Do stuff
}
}
}
class Y {
public void oneAtATime() {
synchronized (Y.class) {
// Do stuff
}
}
}
Each variant has its own pros and cons; locking on the class allows other code, outside of the class, to use the same lock for its own reasons (which allows it to orchestrate more high-level synchronization than what you provide) while the static final Object lock approach lets you prohibits it by making the lock field private (which makes it easier to reason about the locking and avoid your code from deadlocking because someone else wrote bad code).
You could of course also use some synchronization mechanism from java.util.concurrent, like explicit Locks, which provide more control over locking (and ReentrantLock currently performs a little better than implicit locks under high contention).
Edit: Note that static/global locks aren't a great way to go - it means every instance of the class ever created will essentially be tied to every other instance (which, aside from making it harder to test or read the code, can severely harm scalability). I assume you do this to synchronize some kind of global state? In that case, I'd consider wrapping that global/static state in a class instead, and implement synchronization per-instance rather than globally.
Instead of something like this:
class Z {
private static int state;
public void oneAtATime(){
synchronized (Z.class) {
state++;
}
}
}
Do it like this:
class State {
private int value;
public synchronized void mutate(){ value++; }
}
class Z {
private final State state;
public Z(State state){
this.state = state;
}
public void oneAtATime(){
state.mutate();
}
}
// Usage:
State s1 = new State(), s2 = new State();
Z foo = new Z(s1);
Z bar = new Z(s1);
Z frob = new Z(s2);
Z quux = new Z(s2);
Now foo and bar are still tied to each other, but they can work independently from frob and quux.
If you use static synchronized methods, they are locked via the Class Lock. You can also declare a static Object in the class and lock that in a method I believe via something like:
private static final Object STATIC_LOCK = new Object();
private void foo() {
synchronized (STATIC_LOCK) {
//do stuff...
}
}
You could use a static Mutex inside that method. So any concurrent thread is blocking inside the method while another is running it no matter what object of the class it belongs to. I don't think there is any special single keyword to produce the same effect like synchronized.
It is a rather aggressive synchronization, I would avoid it as much as possible.
Synchronize on static field of your class, or the class itself:
synchronized(MyClass.class) {
// mutually excluded method body
}
Both threads must use this construction
public void someMethod() {
synchronized(ClassThatShouldBeProtected.class) {
someSynchronizedCode();
}
}
This approach benefits from the fact, that class itself is an object and therefore it has a monitor. Then you don't need any artificial static instance.
There is no built-in mechanism for this. Create your own static lock attribute, and make sure you lock it and unlock it in every method. Don't forget about exceptions - make sure you unlock it in the "finally" sections.
This should work:
public class MyClass {
void synchronizedMethod() {
synchronized (MyClass.class) {
// synchronized on static level
}
}
}
Which 'missuses' the class's runtime-representation for locking. This is possible as any object can be used as a mutex in Java.
http://www.janeg.ca/scjp/threads/synchronization.html
talks about several ways to achieve it.
in general, locks are prohibitive and hinder benefits of threading. so the critical code should be minimized as much as its possible.
do you want a class lever lock to access static variables of the class or is it for protecting access to a common external resource the class? in which case you should proly have a separate lock while accessing it.