Java - multithreading increment - java

I have the following class in my application
public class InsertErrorLinesHandler {
private int currentCount;
public void insertErrorLine() {
//do something...
currentCount++;
}
}
And I have multiple threads that are using the same instance of InsertErrorLinesHandler, particulary calling insertErrorLine method. After all these threads are stopped, I get the currentCount from this instance.
The question is - how to rewrite this class to be sure that there won't be any concurrency problems? What I want is to be sure, that currentCount value will be the count of method callings from threads. Should I use static method and static variable? Make method synchronize? Make variable volatile?
Thanks!

I suggest using an AtomicInteger, which has a thread-safe increment method

Simple fix, make the method call synchronized:
public class InsertErrorLinesHandler {
private int currentCount;
public void synchronized insertErrorLine() {
//do something...
currentCount++;
}
}

Use AtomicInteger or use LongAdder when number of threads are more for better performance.
Here is the example on how to use AtomicInteger,
public class InsertErrorLinesHandler {
AtomicInteger counter = new AtomicInteger();
public void insertErrorLine() {
counter.incrementAndGet();
}
public int get() {
return counter.get();
}
}

So far, nobody's addressed this part of your question:
Should I use static...?
The choice of whether or not to use static is completely independent of the choice of whether to use synchronized or AtomicInteger or not. The answer depends on what you want to count.
A static field in Java is what some other languages call a global variable: There is only one of it for the entire program. A non-static field (a.k.a., an instance variable) exists in multiple copies---one for each instance of the class to which it belongs.
How many instances of the InsertErrorLineHandler class does your program create? If more than one, then do you want each instance to have its own counter, or do you want all of them to share the same counter? Declaring the field static means that they will all share the same, and leaving out the static keyword means that each instance will have its own counter.
If your program only ever creates one InsertErrorLineHandler instance (i.e., if you are using it as a singleton class) then you should not use static. Making fields static or not static won't change the behavior of a singleton, but using static in a singleton would be bad style.

Related

Synchronization getter and setter

I want to ask you for help with advanced synchronization.
I have class like this:
public class Manager{
private ClassMatcher classMatcher;
public ClassMatcher getClassMatcher(){
return this.classMatcher;
}
public void setClassMatcher(ClassMatcher classMatcher){
this.classMatcher = classMatcher;
}
}
Object Manager can be called from more Threads, so methods: getClassMatcher and setClassMatcher should be synchronized.
But in that case method getClassMatcher can be accessed only by one Thread in the same time.
Is there some way how to solve it ? Well perhaps I can use Locks or AtomicReferences.
Thank you for any advice, it will be really helpful
You don't need to synchronize those methods, but class ClassMatcher should be thread-safe.
Call get or set won't cause problems in your case because set method only replaces the reference of class member to a new object.
I can't see any reason why you need synchronization in such example because your accessors don't do much work with shared state which really can cause some concurrent issues.
For instance, here we have race condition and synchronization needed:
public int get() {
if (a == b) {
return a;
} else {
return b;
}
}
PS: as #shmosel mentioned you may mark your variable as volatile to be sure that you get() the most actual version of your classMatcher

Why is this class not thread safe?

class ThreadSafeClass extends Thread
{
private static int count = 0;
public synchronized static void increment()
{
count++;
}
public synchronized void decrement()
{
count--;
}
}
Can anyone explain why above class is not thread safe?
Since the increment method is static it will synchronize on the class object for the ThreadSafeClass. The decrement method is not static and will synchronize on the instance used to call it. I.e., they will synchronize on different objects and thus two different threads can execute the methods at the same time. Since the ++ and -- operations are not atomic the class is not thread safe.
Also, since count is static, modifying it from decrement which is a synchronized instance method is unsafe since it can be called on different instances and modify count concurrently that way.
You have two synchronized methods, but one of them is static and the other is not. When accessing a synchronized method, based on it's type (static or non-static), a different object will be locked. For a static method, a lock will be put on the Class object, while for the non-static block, a lock will be put on the instance of the class that runs the method. Because you have two different locked objects, you can have two threads that modify the same object simultaneously.
Can anyone explain why above class is not thread safe?
increment being static, synchronization will be done on the class itself.
decrement being not static, synchronization will be done on the object instantiation, but that doesn't secure anything as count is static.
I'd like to add that to declare a thread-safe counter, I believe the simplest way is to use AtomicInteger instead of a primitive int.
Let me redirect you to the java.util.concurrent.atomic package-info.
Others' answers are pretty good explained the reason. I just add something to summarize synchronized:
public class A {
public synchronized void fun1() {}
public synchronized void fun2() {}
public void fun3() {}
public static synchronized void fun4() {}
public static void fun5() {}
}
A a1 = new A();
synchronized on fun1 and fun2 is synchronized on instance object level. synchronized on fun4 is synchronized on class object level. Which means:
When 2 threads call a1.fun1() at same time, latter call will be blocked.
When thread 1 call a1.fun1() and thread 2 call a1.fun2() at same time, latter call will be blocked.
When thread 1 call a1.fun1() and thread 2 call a1.fun3() at same time, no blocking, the 2 methods will be executed at same time.
When thread 1 call A.fun4(), if other threads call A.fun4() or A.fun5() at same time, latter calls will be blocked since synchronized on fun4 is class level.
When thread 1 call A.fun4(), thread 2 call a1.fun1() at same time, no blocking, the 2 methods will be executed at same time.
decrement is locking on a different thing to increment so they do not prevent each other from running.
Calling decrement on one instance is locking on a different thing to calling decrement on another instance, but they are affecting the same thing.
The first means that overlapping calls to increment and decrement could result in a cancel-out (correct), an increment or a decrement.
The second means that two overlapping calls to decrement on different instances could result in a double decrement (correct) or a single decrement.
Since two different methods, one is instance level and other is class level, so you need to lock on 2 different objects to make it ThreadSafe
As explained in other answers, your code is not Thread safe since static method increment() locks Class monitor and non-static method decrement() locks Object monitor.
For this code example, better solution exists without synchronzed keyword usage.
You have to use AtomicInteger to achieve Thread safety.
Thread safe using AtomicInteger:
import java.util.concurrent.atomic.AtomicInteger;
class ThreadSafeClass extends Thread {
private static AtomicInteger count = new AtomicInteger(0);
public static void increment() {
count.incrementAndGet();
}
public static void decrement() {
count.decrementAndGet();
}
public static int value() {
return count.get();
}
}

Modifying a static variable in non-synchronized static method, is there a danger to thread safety?

I have a class with a static method modifying a static variable as follows, does this method needs to be synchonized for thread safe operations ?
public final class IdManager {
private static int noOfIdsInReserveCurrently = 100;
private static final AtomicInteger allotedUserIdsCount;
public static int getNewId(){
noOfIdsInReserveCurrently--;
....
return allotedUserIdsCount.incrementAndGet();
}
}
Should this method have been synchronized?
Well it's certainly not safe as it is. Two threads could both read the value, but decrement their local copy, then both write. Badness.
You could synchronize it (and all other aspects to the variable) - but it would be better to use AtomicInteger which is designed for exactly this sort of thing. That's fine if the only shared state you're modifying is that one value; if you're trying to modify more shared state atomically (e.g. some "next ID" counter as well as the number of outstanding IDs) then you would need to either thing really, really carefully about the various interleavings, or use a synchronized block instead.

Singleton Vs static variable

I need to use a global counter in my application which increments count for every request made. I am going to put this counter in a separate class something like this:
public class Counter{
private static int count = 0;
public synchronized static update()
{
count += 1;
}
public synchronized static int getCount()
{
return count;
}
}
There exists only one Counter throughout the lifetime of the application. Do I get any benefit by making it a singleton since there is a single one? Does it make more sense to create a single instance instead of having a class with static variables? What would be the benefit
I would make it either static (field and methods) or not. You appear to have a combination which is bound to confuse.
In this case, I would just use an AtomicInteger:
public enum Counter {
public static final AtomicInteger COUNTER = new AtomicInteger();
}
so that you can do
import static Counter.COUNTER;
int num = COUNTER.incrementAndGet();
I don't see any need to make it a singleton or static. Instantiate a new Counter in a logical spot (instance variable of a class that's generating the requests?) and use it from there. That way, the Counter class is still reusable elsewhere if you need it and you don't have to worry about anyone else grabbing and updating your counter...
It is more common to use singleton when the class has state (it has fields). When the class is stateless - it is a utility class and usually its methods are static.
Did not see that this is a question tagged with Java and not C++;
Anyways I will leave it here unless someone wants this removed.
The thing about static class members is that they are closely coupled with a class rather than an class instance. In other words there is only one memory allocation for the static variable, that will be shared among all the instances of this class (class objects).
In your code above, in the getCount() method, you return this.count;
Remember that static members do not have this pointer, meaning they are to be accessed using classname::static_member when accessing from outside of the class, and use just the variable name when defining class methods, like you did above.
So your code should look similar to:
return count;
If you want only one copy of the class members, for any number of class objects created, then you are better off with static methods and - static methods can only operate with static members.
If you do not like static methods and static members, singleton is not a bad approach.

How and where to use Static modifier in Java?

How and where should we use a Static modifier for:
1. Field and
2. Method?
For example in java.lang.Math class, the fields methods like abs(), atan(), cos() etc are static, i.e. they can be accessed as: Math.abs()
But why is it a good practice?
Say, I don't keep it static and create an object of the class and access it, which anyways I can, I will just get a warning that, you are trying to access a static method in a non static way (as pointed out by #duffymo, not in case of Math class).
UPDATE 1:
So, utility method, should be static, i.e. whose work is only dependent on the method parameters. So, for example, can the method updateString(String inputQuery, String highlightDoc) should have been a static method in this question?
You can think of a 'static' method or field as if it were declared outside the class definition. In other words
There is only one 'copy' of a static field/method.
Static fields/methods cannot access non-static fields/methods.
There are several instances where you would want to make something static.
The canonical example for a field is to make a static integer field which keeps a count across all instances (objects) of a class. Additionally, singleton objects, for example, also typically employ the static modifier.
Similarly, static methods can be used to perform 'utility' jobs for which all the required dependencies are passed in as parameters to the method - you cannot reference the 'this' keyword inside of a static method.
In C#, you can also have static classes which, as you might guess, contain only static members:
public static class MyContainer
{
private static int _myStatic;
public static void PrintMe(string someString)
{
Console.Out.WriteLine(someString);
_myStatic++;
}
public static int PrintedInstances()
{
return _myStatic;
}
}
Static uses less memory since it exists only once per Classloader.
To have methods static may save some time, beacuse you do not have to create an object first so you can call a function. You can/should use static methods when they stand pretty much on their own (ie. Math.abs(X) - there really is no object the function needs.) Basically its a convenience thing (at least as far as I see it - others might and will disagree :P)
Static fields should really be used with caution. There are quite a few patterns that need static fields... but the basics first:
a static field exists only once. So if you have a simple class (kinda pseudocode):
class Simple {
static int a;
int b;
}
and now you make objects with:
Simple myA = new Simple();
Simple myB = new Simple();
myA.a = 1;
myA.b = 2;
myB.a = 3;
myB.b = 4;
System.out.println(myA.a + myA.b + myB.a + myB.b);
you will get 3234 - because by setting myB.a you actually overwrite myA.a as well because a is static. It exists in one place in memory.
You normally want to avoid this because really weird things might happen. But if you google for example for Factory Pattern you will see that there are actually quite useful uses for this behaviour.
Hope that clears it up a little.
Try taking a look at this post, it also gives some examples of when to and when not to use static and final modifiers.
Most of the posts above are similar, but this post might offer some other insight. When to use Static Modifiers
Usually when the method only depends on the function parameters and not on the internal state of the object it's a static method (with singletone being the only exception). I can't imagine where static fields are really used (they're the same as global variables which should be avoided).
Like in your example the math functions only depend on the parameters.
For a field you should keep it static if you want all instances of a given class to have access to its value. For example if I have
public static int age = 25;
Then any instance of the class can get or set the value of age with all pointing to the same value. If you do make something static you run the risk of having two instances overwriting each others values and possibly causing problems.
The reason to create static methods is mostly for utility function where all the required data for the method is passed in and you do not want to take the over head of creating an instance of the class each time you want to call the method.
You can't instantiate an instance of java.lang.Math; there isn't a public constructor.
Try it:
public class MathTest
{
public static void main(String [] args)
{
Math math = new Math();
System.out.println("math.sqrt(2) = " + math.sqrt(2));
}
}
Here's what you'll get:
C:\Documents and Settings\Michael\My Documents\MathTest.java:5: Math() has private access in java.lang.Math
Math math = new Math();
^
1 error
Tool completed with exit code 1
class StaticModifier
{
{
System.out.println("Within init block");//third
}
public StaticModifier()
{
System.out.println("Within Constructor");//fourth
}
public static void main(String arr[])
{
System.out.println("Within Main:");//second
//StaticModifier obj=new StaticModifier();
}
static
{
System.out.print("Within static block");//first
}
}

Categories

Resources