Synchronization getter and setter - java

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

Related

ExecutorService taking a runnable which is still under construction

I would like to know if this piece of code is correct or not. Will this not lead to issues as I am submitting the runnable object to the executor service while constructing the object itself?
public class A implements Runnable {
public A() {
Executors.newSingleThreadExecutor().execute(this);
// some other initializations
}
}
Will this lead to any issues as we are trying to submit the object to the executor even before creating it completely? If the run() method is called even before all the initializing is done (if at all it's possible), will the variables still be null which were not yet initialized?
Please do not ask me to come up with the complete code, as I have been asking this as a general question which requires clarification.
Yes, there may be issues. The Executor might read a field that you set in the constructor, even before the corresponding code in the constructor was executed. In general you should not expose this from inside a constructor. Java provides useful guarantees for objects after their constructor finished, but in order to benefit from those you have to wait for the result of new X(...) before using it.
Will this lead to any issues as we are trying to submit the object to
the executor even before creating it completely?
For one thing, you can get final variable that are still changing value - that is quite bad per the semantics of final. It can lead to very hard-to-trace concurrency bugs in multi-threaded code.
This code will usually print a few zeros and even the occasional 4, even though the final field a is only ever assigned the value 4 and should never been seen having any other value than 4.
public class A implements Runnable {
private static ExecutorService threads = Executors.newSingleThreadExecutor();
final int a;
public A() {
threads.execute(this);
Thread.yield();
a = 4;
}
#Override
public void run() {
if (a != 4) {
System.out.println(a);
}
}
public static void main(String[] args) {
for (int i = 0; i < 50_000; i++) {
new A();
}
threads.shutdown();
}
}
If the run() method is called even before all the initializing is done
(if at all it's possible), will the variables still be null which were
not yet initialized?
Yes, the ones not yet initialized will be null for reference variables, or the default value (0, false, '\0', 0d, 0f, etc.) for the primitive types. It is even possible according to the specifications with long and double fields to see only 32 of the 64 bits initialized (although on 64 bit architectures it is unlikely that you will ever observe this)
There will almost certainly be issues. What you have is called a "this escape" where you pass a this reference in a ctor to an external method. It's super bad, the object is incompletely constructed at that point and anything could happen.
What you should probably do instead is make the constructor private and use a factory method to get a new instance and execute it, if that's the goal.
public class A implements Runnable {
public A getNew() {
A a = new A();
Executors.newSingleThreadExecutor().execute(a);
return a;
}
private A() {
// some other initializations
}
}

Java - multithreading increment

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.

Can someone give an example of the situation described here about thread-safe variables?

I'm learning about Java multi-threading and came across a very good tutorial online. But I am not sure if I understand a part where the writer explains about thread-safe objects, variables and such. To quote him,
public void someMethod(){
LocalObject localObject = new LocalObject();
localObject.callMethod();
method2(localObject);
}
public void method2(LocalObject localObject){
localObject.setValue("value");
}
...the whole method someMethod() is thread safe. Even if the LocalObject instance is passed as parameter to other methods in the same class, or in other classes, the use of it is thread safe. The only exception is of course, if one of the methods called with the LocalObject as parameter, stores the LocalObject instance in a way that allows access to it from other threads.
I understand why the LocalObject instance is thread-safe. But I would like to see an example of the exception case (the last line in the above block quote). If someone could write a code snippet that fits what's written in the last line, that would be very helpful. Thank you!
public class SomeClass {
private LocalObject cachedLocalObject;
public void someMethod() {
LocalObject localObject = new LocalObject();
localObject.callMethod();
method2(localObject);
}
public void method2(LocalObject localObject) {
this.cachedLocalObject = localObject;
localObject.setValue("value");
}
public LocalObject getCachedLocalObject() { return cachedLocalObject; }
}
The combination of caching the object in method2() and then exposing it for external use in getCachedLocalObject() breaks threadsafety: some other thread can use getCachedLocalObject() to obtain and modify cachedLocalObject.
The contrast is demonstrated in the next part: "Object Members". As long as the object remains local to thread, it will be inherently thread-safe. But as soon as the reference is assigned to an object's field, any thread with a reference to the parent object can gain access to its fields, rendering them (potentially) not thread-safe.

Which is a better singleton implementation?

I was looking at these two implementations of the Singleton Pattern:
Class Customer {
int x;
static int count = 0;
private Customer()
{
x = 1;
}
public static Customer GetCustomer()
{
if(count==0)
{
count++;
return new Customer();
}
else
{
return null;
}
}
}
Implementation 1 in which the constructor is not called if the class is already instantiated once. OR
Class Customer{
int x;
static int count = 0;
public Customer()
{
if(count == 0)
{
x = 1;
count++;
}
else
{
return;
}
}
Implementation 2 in which the constructor is called irrespective of weather the class is already instantiated once or not. I watched a video lecture online that says Implementation 2 is not preferred as it allocates memory for the constructor although the object is not instantiated for the second time. I am aware Java has automatic Garbage Collection, but just wanted to know if what I watched in the video lecture is relevant.
There are some that would say that no implementation of a singleton is the correct one, but I'm not quite in that camp.
People often tend to use them badly (as a God object, for example) but they still have their place (in my opinion, which has little to do with this answer).
For the purposes of this answer, I'm going to assume you've made the right decision in needing a singleton, but I do urge you to read up on its potential problems - there may well be a better way to achieve your ends.
Having said that, I'm not sure if your code samples are correct anyway. A singleton is supposed to return one and only one instance, creating one if necessary, giving you the previously created one if not.
I fail to see how your first code sample honors that contract. It'll give you a new one the first time it's called, then it will give you nothing after that.
And your second code sample doesn't seem to prevent multiple objects at all.
So I'd be thinking very carefully about whether you want to continue watching that video, if this is the quality of the education they deliver.
In any case, I prefer the one that only constructs once, since you're only supposed to have one object of that class. In other words, a static getMe() call that is properly synchronised to prevent race conditions allowing creation of more than one Me object, and that creates a new object the first time, returning that same object on subsequent calls.
In pseudo-code, that would be something like:
class Me {
private Me() {};
private static Me *loner = NULL;
public static synchronised Me *getMe() {
if loner == NULL
loner = new Me();
return loner;
}
}
Writing a correct singleton is not that easy. You need to take care of race conditions and to defend against reflection attacks. For example a private constructor might be invoked via reflection to create one more instance of an object. The easiest and safest singleton implementation in java is done with an enum:
enum Singleton {
INSTANCE;
}
That's because enum constants are spedified by JLS to be singletons (section 8.9 of JLS):
An enum type has no instances other than those defined by its enum constants.

Is there a standard class which wraps a reference and provides a getter and setter?

Sorry for the stupid question.
I'm very sure, that the Java API provides a class which wraps a reference,
and provides a getter and a setter to it.
class SomeWrapperClass<T> {
private T obj;
public T get(){ return obj; }
public void set(T obj){ this.obj=obj; }
}
Am I right? Is there something like this in the Java API?
Thank you.
Yes, I could write it y myself, but why should I mimic existing functionality?
EDIT: I wanted to use it for reference
parameters (like the ref keyword in C#), or more specific,
to be able to "write to method parameters" ;)
There is the AtomicReference class, which provides this. It exists mostly to ensure atomicity, especially with the getAndSet() and compareAndSet() methods, but I guess it does what you want.
When I started programming in Java after years of writing C++, I was concerned with the fact that I could not return multiple objects from a function.
It turned out that not only was it possible but it was also improving the design of my programs.
However, Java's implementation of CORBA uses single-element arrays to pass things by reference. This also works with basic types.
I'm not clear what this would be for, but you could use one of the subclasses of the Reference type. They set the reference in the constructor rather than setter.
It' worth pointing out that the Reference subclasses are primarily intended to facilitate garbage collection, for example when used in conjunction with WeakHashMap.
I'm tempted to ask why you'd want one of these, but I assume it's so you can return multiple objects from a function...
Whenever I've wanted to do that, I've used an array or a container object...
bool doStuff(int params, ... , SomeObject[] returnedObject)
{
returnedObject[0] = new SomeObject();
return true;
}
void main(String[] args)
{
SomeObject myObject;
SomeObject[1] myObjectRef = new SomeObject[1];
if(doStuff(..., myObjectRef))
{
myObject = myObjectRef[0];
//handle stuff
}
//could not initialize.
}
... good question, but have not come across it. I'd vote no.
.... hm, after some reflection, reflection might be what comes close to it:
http://java.sun.com/developer/technicalArticles/ALT/Reflection/
there is java.lang.ref.Reference, but it is immutable (setter is missing). The java.lang.ref documentation says:
Every reference object provides methods for getting and clearing the reference. Aside from the clearing operation reference objects are otherwise immutable, so no set operation is provided. A program may further subclass these subclasses, adding whatever fields and methods are required for its purposes, or it may use these subclasses without change.
EDIT
void refDemo(MyReference<String> changeMe) {
changeMe.set("I like changing!");
...
the caller:
String iWantToChange = "I'm like a woman";
Reference<String> ref = new MyReference<String>(iWantToChange)
refDemo(myRef);
ref.get();
I don't like it however, too much code. This kind of features must be supported at language level as in C#.
If you are trying to return multiple values from a function, I would create a Pair, Triple, &c class that acts like a tuple.
class Pair<A,B> {
A a;
B b;
public void Pair() { }
public void Pair(A a,B b) {
this.a=a;
this.b=b;
}
public void Pair( Pair<? extends A,? extends B> p) {
this.a=p.a;
this.b=p.b;
}
public void setFirst(A a) { this.a=a; }
public A getFirst() { return a; }
public void setSecond(B b) { this.b=b; }
public B getSecond() { return b; }
}
This would allow you to return 2 (techically infinite) return values
/* Reads a line from the provided input stream and returns the number of
* characters read and the line read.*/
public Pair<Integer,String> read(System.in) {
...
}
I think there is no Java API Class designed for your intent, i would also prefer your example (the Wrapper Class) then using this "array-trick" because you could insert later some guards or can check several thinks via aspects or reflection and you're able to add features which are cross-cutting-concerns functionality.
But be sure that's what you want to do! Maybe you could redesign and come to another solutions?

Categories

Resources