synchronizing on enum monitor - java

I read that from 1.5 we can use enum for singleton
public enum Singleton {
INSTANCE;
//Singleton method
public void someMethod( ) {...}
}
Singleton.INSTANCE.someMethod( );
Does this mean every entry in an enum type is a instance by itself?
If I define a enum type with a class,can I use block synchronization on every entry in teh enum type?
class smokers extends Thread{
public enum restype{
TOBACCO,MATCH,PAPER
}
public void run(){
if(xxxx){
synchronized(restype.PAPER){
....
}
}
else
{
synchronized(restype.MATCH){
....
}
}
}
Is this valid code?

TOBACCO,MATCH,PAPER each is instance of type restype.
You can't modify enum constants, so don't need to synchronize.
If you want to use them as object locks, yes it is valid.
NOTE: Java naming convention suggests that use first letter as Capital letter for class name.

You can read about Enums here.
Since its a constant and has only one instance you don't need synchronization.
But if you are changing values of members using setters then you will need to add synchronization.
public enum Restype {
TOBACCO(1), MATCH(2), PAPER(3);
private int value = 0;//I have purposefully not declare it as final
private Restype(int value) {
this.setValue(value);
}
public void setValue(int value) {// now I can change value in multiple
// threads.
this.value = value;
}
public int getValue() {
return value;
}
}
Now I will have various ways to achieve synchronization for setValue and getValue easiest will be to declare them synchronized.
But clearly above is Misuse of Enums.
In java you can have syncrhonized block on any object so you can have synchronized block on enum instances also.
synchronized (Restype.TOBACCO) {
// Allowed not recommenced
//every class should define its own mutex
}

The code looks valid, but if you need to do that, put the logic in the enum
public enum RestType{
PAPER{
public synchronized void foo(){ return true };
},
MATCH{
public void foo(){ return false };
};
public abstract boolean foo(); //I've never see an abstract method define a
//synchronized method... so I have not
//idea if it's valid
}

Related

calling method on enum

public enum AgeGroup {
CHILD{
public int get(){
return 10;
}
},
TEEN, YOUNG, MID, OLD;
}
I have an enum AgeGroup and as you are seeing that CHILD has one method get(). Can somebody tell me why we can't call get() from CHILD what is the design approach behind this or why is it designed like this?
Firstly, all instances of an enum are of the same type, which means all instances have the same set of methods.
You need to declare a method on the enum type itself for instances to have a method:
public enum AgeGroup {
CHILD{
public int get(){
return 10;
}
},
TEEN, YOUNG, MID, OLD;
public int get() {
return 0;
}
}
If all instances overrode the get() method as CHILD has, you could declare the method as abstract, which forces the coder to implement the method if new instances are added.
The best approach is to use a final field, initialized via a custom constructor, with a getter:
public enum AgeGroup {
CHILD{10), TEEN(19), YOUNG(35), MID(50), OLD(80);
private final int age;
AgeGroup(int age) {
this.age = age;
}
public int get() {
return
}
}
Javadoc says: "The enum declaration defines a class (called an enum type)."
So, basically you can include some methods into enum declaration, but the methods will be defined for all elements of the enum.
Check the Planet example here: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html
What you have written doesn't qualify as a valid declaration of a class (or enum) because you try to declare a function for only one element of the enum.

Enum static or non-static method

Consider the following enum class
public enum ClassA {
CHECK1("X", 0),
CHECK2("Y", 2),
CHECK3("Z", 1);
private final String id;
private final String cdValue;
private ClsA(String id, String cdValue) {
this.id = id;
this.cdValue = cdValue;
}
private String getId() {
return id;
}
private String getCdValue() {
return cdValue ;
}
private static final List<String> cdValues = new ArrayList<String>();
static {
for (ClassA clsA : ClassA.values()) {
cdValues.add(clsA.getCdValue());
}
}
public boolean isCdValue(String cdValue)
{
if clsValues.contains(cdValue)
return true;
else return false;
}
}
The question that I have is does the method isCdValue has to be static. I have to use this method isCdValue for every input given by the client. Therefore the method parameter cdValue changes for every input.
If it cannot be static then I would like to know how I can access this method. Please note I am primarily interested in learning about static of non-static method call. If it is a non-static call in a enum then how can we call this non static method. I am not trying to resolve the issue of how to get about checking the cdValue exists or not. It is just an example.
does the method isCdValue has to be static.
Yes, the method isCdValue has to be static here.
An enum is a special kind of class. An enum constant defines an instance of the enum type. An enum type has no instances other than those defined by its enum constants. Hence new can not be used to instantiate an enum.
An enum type has no instances other than those defined by its enum
constants. It is a compile-time error to attempt to explicitly
instantiate an enum type (§15.9.1).
Refer this
If you have to put the checking method in the Enum, I think it should be static
you can do this check:
ClassA.isCdValue(para)
Note that, you cannot new an Enum object. So if the method in your Enum, and it is not static, you cannot call it unless you have an Instance. but the goal of your method is checking if the string could be an instance.
another possibility is, use an immutable collection in your Enumm, and make it static and public. Then you could just call ClassA.CD_VALUES.contains(para)
If you want to access it from ClsA, you will have to make it static, if you want to access it from an instance of ClsSa then it doesn't.
A couple of other things: where do you declare clsValues in the first place?
There's no need for the complex if, you may replace this:
public boolean isCdValue(String cdValue)
{
if clsValues.contains(cdValue)
return true;
else return false;
}
with this
public boolean isCdValue(String cdValue){
return clsValues.contains(cdValue)
}
Last little thing, I'd strongly suggest you put curly braces around all your if and else's clauses, I've spent many a debugging hour because someone added a second line under the else, fooled by the indent and thinking it would only execute on the else.
You can use something like this, you do not need static List but the method has to be static as answered by Kent,
public static ClassA getClassAByCDValue(String cdValue)
{
for(ClassA value: ClassA.values())
{
if(value.cdValue.contains(cdValue))
{
return value;
}
}
return null;
}
public static boolean isCDValue(String cdValue)
{
for(ClassA value: ClassA.values())
{
if(value.cdValue.contains(cdValue))
{
return true;
}
}
return false;
}
Using above will be more appropriate as you just have to take care with adding/removing items in enum.

Thread-safety idiom for getters in a Java class other than "synchronized"

public class ThreadSafe {
private int aField;
public synchronized void setAField(int value) {
aField = value;
}
public synchronized int getAField() {
return aField;
}
}
public class ThreadSafeToo {
private volatile int aField;
public synchronized void setAField(int value) {
aField = value;
}
public int getAField() {
return aField;
}
}
public class DontKnowIfThreadSafeButMostLikelyYes {
private static int aField;
public synchronized void setAField(int value) {
aField = value;
}
public int getAField() {
return aField;
}
}
Questions:
Is DontKnowIfThreadSafeButMostLikelyYes thread-safe?
What would be the preferred idiom and why?
ThreadSafeToo does not need a synchronized method: volatile assignment is atomic and provides visibility guarantees.
DontKnowIfThreadSafeButMostLikelyYes is not thread safe: you need to synchronize reads AND writes to shared variables.
Preferred idiom is subjective, but in your case, the efficient approach is:
public class ThreadSafeToo {
private volatile int aField;
public void setAField(int value) { aField = value; }
public int getAField() { return aField; }
}
Your class DontKnowIfThreadSafeButMostLikelyYes is not thread safe because a static variable is not different from an instance variable from point of synchronization. Besides this the result will not be the same as in the other cases.
Also the second question is opinion based.
As far as I know DontKnowIfThreadSafeButMostLikelyYes is not thread-safe, because 2 threads could set and get aField at the same moment -> problem
There is no difference if you put the static or not. Both would be not thread-safe.
I think there is no real preferred idom. In this case I would choose the first way. But you can also use the second one or you could use locks.
Is DontKnowIfThreadSafeButMostLikelyYes thread-safe?
No, because when getter & setter are being called the same moment getter might return old value.
What would be the preferred idiom and why?
In this case the 2nd class is correctly synchronized & is thread safe

enum implementation inside interface - Java

I have a question about putting a Java enum in the interface.
To make it clearer, please see the following code:
public interface Thing{
public enum Number{
one(1), two(2), three(3);
private int value;
private Number(int value) {
this.value = value;
}
public int getValue(){
return value;
}
}
public Number getNumber();
public void method2();
...
}
I know that an interface consists of methods with empty bodies. However, the enum I used here needs a constructor and a method to get an associated value. In this example, the proposed interface will not just consist of methods with empty bodies. Is this implementation allowed?
I am not sure if I should put the enum class inside the interface or the class that implements this interface.
If I put the enum in the class that implements this interface, then the method public Number getNumber() needs to return the type of enum, which would force me to import the enum in the interface.
It's perfectly legal to have an enum declared inside an interface. In your situation the interface is just used as a namespace for the enum and nothing more. The interface is used normally wherever you use it.
Example for the Above Things are listed below :
public interface Currency {
enum CurrencyType {
RUPEE,
DOLLAR,
POUND
}
public void setCurrencyType(Currency.CurrencyType currencyVal);
}
public class Test {
Currency.CurrencyType currencyTypeVal = null;
private void doStuff() {
setCurrencyType(Currency.CurrencyType.RUPEE);
System.out.println("displaying: " + getCurrencyType().toString());
}
public Currency.CurrencyType getCurrencyType() {
return currencyTypeVal;
}
public void setCurrencyType(Currency.CurrencyType currencyTypeValue) {
currencyTypeVal = currencyTypeValue;
}
public static void main(String[] args) {
Test test = new Test();
test.doStuff();
}
}
In short, yes, this is okay.
The interface does not contain any method bodies; instead, it contains what you refer to as "empty bodies" and more commonly known as method signatures.
It does not matter that the enum is inside the interface.
Yes, it is legal. In a "real" situation Number would implement Thing, and Thing would probably have one or more empty methods.

How to create an immutable class in Java without using final keyword [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Implement a final class without the “final” keyword
I want to create an immutable class in Java without using the final keyword.
I think smt like should work fine
class Immutable {
private int i;
public static Immutable create(int i){
return new Immutable(i);
}
private Immutable(int i){this.i = i;}
public int getI(){return i;}
}
But final is preferable.
The final keyword won't make your class inmutable. It will avoid your class to be extended from another class.
public final class Foo {
//....
}
public class Bar extends Foo {
//COMPILATION ERROR!
}
An adecuated class design is what will make you class inmutable, as you can see at duffymo answer.
Note that you can declare as final the fields that you will initialize at the constructor:
class Foo {
private final int state
public Foo(int v) {
this.state=v;
}
//....
}
The difference is that, while at duffymo example, the value ccould be changed from inner routines (i.e, a method adds one to the value, kind of a counter), at my example you wouldn't be able to do so.
Let's try to avoid absolutely the use of the final keyword:
public class Foo {
private int state;
private Foo(int v) {
this.state=v;
}
public static Foo getInstance(int value) {
return new Foo(value);
}
}
You only can get an instance of Foo accesing the Foo.getInstance method.
But anyway, you can extend the Foo class and make it mutable
I was wrong here. I won't compile, as you can acceess the Foo constructor.
public class Bar extends Foo {
private int ohNopes;
//COMPILATION ERROR!
public Bar(int v) {
this.ohNopes=v;
}
}
So, it seems it can be done, after all.
The problem with an immutable class not being final is that, subclasses may not be immutable.
Here is an example from the Java API, java.lang.String is immutable and final, if a string is passed to one of your methods you can be sure that it will remain in a consistent state.
the following will not compile because String is final:
public class MyString extends java.Lang.String {
public MyString(String original) {
Super(original);
}
#Override
public String toString() {
return String.valueOf(System.currentTimeMillis());
}
On the other hand, java.ma.BigDecimal itself is immutable, but it is not final and allowed to be subclassed. This opens up a range of issues. If a BigDecimal is passes to one of your methods you can't rely on the fact that no one has overridden BigDecimal like you can with String. subclasses of BigDecimal could potentially replace its methods with others which give unpredictable results.
The following will compile because BigDecimal is not immutable:
public class MyBigDecimal extends java.math.BigDecimal {
public MyBigDecimal(double val) {
super(val);
}
private int count = 0;
// override intValue which changes the state of this instance
#Override
public int intValue() {
return count++;
}
// rinse and repeat for the rest of the BigDecimal methods...
}
You cannot rely on he state of BigDecimal instances passed into your code, you should make Defensive copies of non final classes if you need to rely on their immutability.
I can't imagine why you object to using final, but here's a class that will get the job done. I know there are subtleties regarding serialization and reflection, but this can't be changed without special shenanigans:
public class Immutable
{
private int value;
public Immutable(int v)
{
this.value = v;
}
public int getValue() { return this.value; }
}
The class should set all its values in the constructor, and provide no setters (methods that modify class members).
You can create a class then create a .jar and use the jar as resource.

Categories