Is this code thread safe for unique id in java - java

I have a simple code where I want to have objects generated with unique id. Here is the code snippet
public class Test {
private static long counter = 0;
private long id;
private Test() {
// Don't worry about overflow
id = counter++;
}
// Will this method always Test Object with unique id?
public static Test getTest() {
return new Test();
}
public long getId() {
return id;
}
}
Would like to know if getTest method is called by multiple threads will all TestObjects have unique id's?

It's not thread-safe because two threads can execute counter++ at same time and you can get unexpected results.
You should use AtomicInteger:
public class Test {
private static AtomicLong counter = new AtomicLong(0);
private long id;
private Test() {
// Don't worry about overflow
id = counter.incrementAndGet();
}
// Will this method always Test Object with unique id?
public static Test getTest() {
return new Test();
}
public long getId() {
return id;
}
}

No, it is not thread-safe for generating unique IDs. It may well happen that objects will receive non-unique IDs. You could use AtomicInteger/AtomicLong to make this work (i.e., private static AtomicLong counter = (new AtomicLong())) and then counter.getAndIncrement() in the constructor of Test.
The reason it is not thread-safe is that each processor/core has its own set of registers and without synchronization the variable may have inconsistent copies in the different processors/cores. Even on a single-processor system, preemptive multi-threading introduces the same problem. Synchronization would not be needed in non-preemptive threading systems.

you can also use synchronize block in your constructor if you want to lock class-level variable (Not the instance variable because for instance variable there is no need of synchronization . only one thread will be able to create object at a time).
so you can try this also as your constructor.
private Test() {
// Don't worry about overflow
synchronized(Test.class){
id = counter++;
}
}

Related

Which class should take care of doing a get on an AtomicLong

I have a multithreaded application where I need to ensure all threads are referring to the latest version of a long. I was thinking of using AtomicLong for this purpose.
The AtomicLong will be in one class and other classes will need to get the value and also set the value.
private final AtomicLong key;
public ClassHoldingLong(){
this.key = new AtomicLong(System.currenttimemillis());
}
public long getKey() {
return key.get();
}
public void setKey(long key) {
this.key.set(key);
}
Is this fine to do or should the getter be AtomicLong itself and someone calls .get() on the AtomicLong rather than this class holding the variable calling it for another class. From what I read, these getters setters don't need to be synchronized but not sure if that is only if AtomicLong is the return type.
This class does have additional information it holds such as statistics and additional functionality. I just included this snippet of code for an example

Why use a static declaration when initializing a new non-static object

I apologize if this is redundant, but I was not able to find a similar question. And, TBH, I don't even know how to frame the question properly.
This is a from a review question from the Java 8 OCA study guide. The question is about static initializers, which I understand just fine. There is however a line of code that I don't get, and because the question isn't about it, there is not a very good explanation of it.
private static Rope rope = new Rope();
So this isn't about Singletons or static classes. I don't understand why you would initialize an object like this. And, if there is a good reason why you can and would do this, what is the reason?
Would someone kindly point me in the direction of an explanation? Like I said, I'm not even sure what this is properly called, so am having a hard time finding a good answer on my own.
Edit to put in the entire class:
import rope.*;
import static rope.Rope.*;
public class RopeSwing
{
private static Rope rope1 = new Rope("rope 1");
private static Rope rope2 = new Rope("rope 2");
{
System.out.println(rope1.length);
}
public static void main(String[] args) {
rope1.length = 2;
rope2.length = 8;
System.out.println(rope1.length);
}
}
This makes a single Rope instance available to the whole class - it will be shared by all instances of the class this is declared in. This can be useful when there's some shared information or state all instances should rely on.
Often, private static fields are also declare final, which makes them constants (assuming the type of the field is immutable). Looking at your full example, I suspect the author should have made them private static final.
For example:
public class Foo {
private static Rope rope = new Rope();
private int value;
public Foo(int value) { this.value = value; }
#Override public String toString() {
return "static rope: " + rope + " instance value: " + value;
}
}
If you create several instances of Foo (new Foo(1);, 'new Foo(2), etc.) they will all share the same rope instance, and new Rope() will only have been invoked once (when the class is first loaded).
An example of a non-constant static field might be a shared counter. Suppse you want to uniquely identify every instance of an object that gets constructed, anywhere in your application. You can do so with an AtomicInteger, which is essentially a thread-safe int:
public class Unique {
// despite being final this is not a "constant" because it's mutable
private static final AtomicInteger counter = new AtomicInteger();
private final int id;
public Unique() {
id = counter.getAndIncrement();
}
#Override public String toString() { return "ID: " + id; }
}
Give it a try - every instance of Unique will have a unique ID.
In your example code there's an instance initializer, which will be invoked when creating a new instance (hence after the static fields have been initialized).

how to use singleton pattern for sequence number creation in java

I have an Orders class and i need to have a singleton pattern to be able to create a sequence number for each order processed. How do i implement this?
My order class has an Order_ID, Customer_ID, Order_desc and Ordered_qty. There needs to be a sequence number created for each order processed using the singleton pattern.
This may be one of those X/Y problems, where you think Y is a solution to X, so you ask for help with Y, but perhaps there is a better solution.
Strictly speaking, to implement a singleton, all you need is a class whose only constructors are private, a static reference to an instance of the class as a class field, and a public getInstance method. Then create an instance method which returns the next number in line.
public class MySingleton {
private static MySingleton instance = new MySingleton();
private volatile int next = 0;
private MySingleton() {
// prevent external instantiation of a singleton.
}
public static MySingleton getInstance() {
return instance;
}
public synchronized int getNextSequence() {
return next++;
}
}
There are many flaws with this solution to your problem, some are just basic OOP design and some are more systemic:
A singleton that does not implement or extend any types is worthless. You could just use all static methods instead. Singletons are useful if you are writing a class that implements an interface and that interface is used by somebody else, but you only want a single instance as an implementation detail. This type of singleton is an attempt to make a global variable look like it is not a global variable.
This will not survive application restarts. If these sequences are being used to identify data that is stored externally or shared, you will end up repeating the same numbers when the application is restarted.
If you deploy multiple instances of the application who read and write to a common persistent storage, like a database, they will re-use the same numbers because the sequence is only tracked within the JVM.
Databases are already exceptionally good at this. Trying to re-invent it in the application tier seems.... inappropriate.
Although I agree #Elliott Frisch that the question itself sounds strange. However if you indeed have to generate IDs yourself here is the prototype that implements classic version of Singleton pattern.
public class IdGenerator {
private static IdGenerator instance;
private int id = 0;
private IdGenerator(){}
private static IdGenerator getInstance() {
synchronized(IdGenerator.class) {
if (instance == null) {
instance = new IdGenerator();
}
return instance;
}
}
public int nextId() {
return id++;
}
}
Please note that word "classic". There are a lot of possible improvements of Singleton pattern and there are hundreds of articles that explain them.
The key aspect is to use a single AtomicLong as the singleton. You may model it like this:
class Orders {
private static final AtomicLong NEXT_ID = new AtomicLong();
static Order newOrder(Customer customer, String description, int quantity) {
return new Order(orderId(), customer, description, quantity);
}
private static long orderId() {
return NEXT_ID.incrementAndGet();
}
}
class Order {
private final long orderId;
private final long customerId;
private final String description;
private final int quantity;
Order(long orderId, Customer customer, String description, int quantity) {
this.orderId = orderId;
this.quantity = quantity;
this.customerId = customer.getCustomerId();
this.description = description;
}
}
class Customer {
public long getCustomerId() {
throw new UnsupportedOperationException("not yet implemented");
}
}

Synchronize write access to Volatile field (Cheap read-write block)

Let's say I have the following class that will be read heavily, but only written to occasionally. It will be used in a multi-threaded web app, so it needs to be thread safe:
public class Foo {
private volatile String foo;
public String getFoo() {
return foo;
}
public synchronized String setFoo(String in) {
this.foo = in;
}
}
Java Concurrency (http://www.ibm.com/developerworks/java/library/j-jtp06197/index.html) states that this is a fragile way to protect write access while improving read access. What is a stronger alternative to this pattern? Or any alternative if foo will need to mutable in a read-heavy environment? Thank you.
Volatile provides fast thread-safe lock-free access to a field without synchronization
private volatile String foo;
public String getFoo() {
return foo;
}
public void setFoo(String in) {
this.foo = in;
}
volatile solves 3 problems 1) memory visibility 2) atomic writes for double and long fields 3) forbids instructions reordering. But it's not enough if you need several operations over a field as one atomic transaction, such as increment. This code is broken
private volatile int id;
public void incrementId() {
id++;
}
because if 2 threads simulataneously read and increment it and save the result then the result of the first increment will be overwritten with the result of the second increment. To prevent this from happening we need to use synchronization
private int id;
public synchronized int nextId() {
return ++id;
}
or java.util.concurrent.atomic package
private AtomicInteger id = new AtomicInteger();
public void incrementId() {
return id.incrementAndGet();
}
If all you are doing is setting foo, then you don't need to synchronize the method. making the reference volatile is sufficient.
At the link you said there is this code for "infrequent updates" usage:
#ThreadSafe
public class CheesyCounter {
// Employs the cheap read-write lock trick
// All mutative operations MUST be done with the 'this' lock held
#GuardedBy("this") private volatile int value;
public int getValue() { return value; }
public synchronized int increment() {
return value++;
}
}
The increment method is only using synchronized because it is doing more than just setting the value of value as stated in the description, if all you are doing is this.foo = in; that is atomic.
In the text the "fragility of this pattern" means things can get messy very fast when you mix volatile and other synchronization methods to do more than just simple examples.
See package java.util.concurrent.locks for the interfaces Condition and Lock and the class ReentrantLock. I think that, and using synchronized is what the author means by "stronger alternatives". You should also see Object.wait, Object.notify and Object.notifyAll if you don't know that yet.

The pattern of final array instead of non-final variable for boolean flag in inner class

I often have a situation in my Java code when I need to set a boolean flag inside an inner class. It is not possible to use primitive boolean type for that, because inner class could only work with final variables from outside, so I use pattern like this:
// class from gnu.trove is not of big importance, just to have an example
private final TIntIntHashMap team = new TIntIntHashMap();
// ....... code ............
final boolean[] flag = new boolean[]{false};
team.forEachValue(new TIntProcedure() {
#Override
public boolean execute(int score) {
if(score >= VICTORY_SCORE) {
flag[0] = true;
}
return true; // to continue iteration over hash map values
}
});
// ....... code ..............
The pattern of final array instead of non-final variable works well, except it is not look beautiful enough to me. Does someone know better pattern in Java ?
Use AtomicBoolean.
Here's a popular StackOverflow question about this issue: Why are only final variables accessible in anonymous class?
How about having a generic holder class which holds object of any type. In your case, it can hold a Boolean type. Something like:
class Holder<T> {
private T genericObj;
public Holder(T genericObj) {
this.genericObj = genericObj;
}
public T getGenericObj() {
return genericObj;
}
public void setGenericObj(T genericObj) {
this.genericObj = genericObj;
}
}
And use it as:
public class Test {
public static void main(String[] args) throws Exception {
final Holder<Boolean> boolHolder = new Holder<Boolean>(Boolean.TRUE);
new Runnable() {
#Override
public void run() {
boolHolder.setGenericObj(Boolean.FALSE);
}
};
}
}
Of course, this has the usual problems that occur with mutable objects that are shared across threads but you get the idea. Plus for applications where memory requirements are tight, this might get crossed off when doing optimizations in case you have a lot of invocations of such methods. Also, using AtomicReference to swap/set references should take care of use from multiple threads though using it across threads would still be a bit questionable.
There are situations where this is the best pattern.
The only improvement I can suggest is return false when you have found a match.
One problem is that the TIntIntHashMap does not have a fold/reduce method so you have to simulate it using foreach. You could try to write your own class extending TIntIntHashMap adding a reduce method.
Other solution is to just extend TIntProcedure to have a value. Something like:
abstract class TIntProcedureWithValue<T> implements TIntProcedure {
private T accumulator;
public T getValue() {return accumulator;}
}
Then you can pass an instance of this class to foreach, set the internal accumulator instead of the external flag array, and get the resulting value afterwards.
I am not familiar with gnu.trove, but generally it's better for the "algortihm" function to be more specific, leaving less code here.
private final IntIntHashMap team = new IntIntHashMap();
boolean found = team.value().containsMatch(new IntPredicate() {
public boolean is(int score) {
return score >= VICTORY_SCORE;
}
});
(More concise syntax should be available in Java SE 8.)
maybe something like that? (implements or extends... I don't know what is TIntProcedure, unfortunately) :
class FlagResult implements TIntProcedure {
boolean flag = false;
#Override
public boolean execute(int score) {
flag = score >= VICTORY_SCORE;
return !flag;
}
};
FlagResult result = new FlagResult();
team.forEachValue(result);
boolean flag = result.flag;

Categories

Resources