Singleton is instantiated twice in Glassfish Server - java

My singleton is called Resources. It should only be instantiated once by this Singleton standard I used:
package site.kevindhu.models;
import site.kevindhu.entity.Player;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
public class Resources {
public static Resources resources;
public Map<String, Object> data;
static {
resources = new Resources();
}
private Resources() {
data = new HashMap<>();
data.put("players", new HashSet<Player>());
data.put("newPlayers", new HashSet<Player>());
}
public static Resources getInstance() {
return resources;
}
}
However, it is not working correctly!
When I deploy a .ear to run my glassfish server, it goes into this block twice:
static {
resources = new Resources();
}
As a result, the "singleton" actually creates two different Resources each time I run the server.
I know I do twice because I debug it calls two different Resources objects whenever I attempt to call Resources.resources.
Is this possibly because I am deploying a .ear file? How do the specifics of this double instantiation work?

The best way to go is to let the compiler handle it for you:
/** Singleton. */
public enum Resources {
RESOURCES;
private final Map<String, Team> teams = new HashMap<>();
public boolean add(Team team) {
return team != null
&& teams.put(team.getName(), team) == null;
}
public Team find(String name) {
return name == null ? null : teams.get(name);
}
public Team find(Team team) {
return team == null ? null : get(team.getName());
}
public Map<String, Team> getTeams() {
return Collections.unmodifiableMap(teams);
}
// remove, iterators, etc.
}
public class TeamImpl implements Team {
private final String name;
private final Map<String, Player> roster = new HashMap<>();
public TeamImpl(String name) {
if (name == null) {
throw new IllegalArgumentException("name must not be null");
}
this.name = name;
assert this.name != null;
}
#Override
public boolean equals(Object other) {
// base comparison on team name
}
#Override
public int hashCode() {
assert this.name != null;
return name.hashCode();
}
// methods from interface Team:
#Override
public String getName() {
return name;
}
#Override
public Set<Player> getRoster() {
return Collections.unmodifiableSet(new HashSet<>(roster.values()));
}
#Override
public boolean add(Player player) {
return player != null
&& roster.put(player.getName(), player) == null;
}
#Override
public Player find(String name) {
return name == null ? null : roster.get(name);
}
// remove, iterators, etc.
}

Related

How to run a method inside an object with different threads simultaneously?

My setup is as described. What I want to accomplish is have the aMethod in each of my implemented classes to run in parallel. I have looked into using Futures and Runnable and I am unsure how to proceed with either process.
My first thought was try to return a Future<Boolean> instead of a regular boolean, but I am unsure as to how would I associate the result with the name that it was initially called with.
The reason why I want aMethod to run in parallel/asynchronous is because aMethod might have a http request. If there is a request, I do not want to wait for a reply to continue. I want it to do that in a separate thread and continue on to the next method.
With a lot of http requests, aClass.doMethod() takes a while to accomplish. I want to run them in parallel so I don't have to wait for each http request before continuing.
Anyone have tips on how to accomplish this?
import java.util.ArrayList;
import java.util.List;
//Strategy.java
public interface Strategy {
boolean aMethod();
}
//AStrategy.java
public class AStrategy implements Strategy {
#Override
public boolean aMethod() {
// Do a couple http requests
return true;
}
}
//BStrategy.java
public class BStrategy implements Strategy {
#Override
public boolean aMethod() {
// Do some other requests
return true;
}
}
//SomeClass.java
public class SomeClass {
String name;
Strategy aStrategy;
public SomeClass(String name, Strategy strategy) {
this.name = name;
this.aStrategy = strategy;
}
public boolean doMethod() {
return aStrategy.aMethod();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
//Just a regular pojo
//ResultsClass.java
public class ResultsClass {
String name;
boolean result;
public ResultsClass(String name, boolean result) {
this.name = name;
this.result = result;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public boolean isResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
}
public class AClass {
public static void main(String args[]) {
List<SomeClass> classes = new ArrayList<>();
classes.add(new SomeClass("Class 1", new AStrategy()));
classes.add(new SomeClass("Class 2", new BStrategy()));
List<ResultsClass> results = new ArrayList<>();
classes.forEach(aClass -> results.add(new ResultsClass(aClass.getName(), aClass.doMethod())));
}
}
The simplest way for you to do this is probably to use a ThreadPoolExecutor, make your strategy classes runnable or wrap them in runnables, and submit them to the executor. Once all are submitted, you can block on the futures until the threads complete and you can retrieve the results from the futures.

java duplicated code in enum

I have duplicated code in my program, I have enums that load values from a property file, I want make my code to be cleaner.
Maybe an Interface can be the solution but I can't declare a non final variable.
This is an example:
public enum AlertMessageEnum{
//
OUTPUT_FOLDER_EXISTS,
...
CONFIG_FILE_IS_MISSING;
// the file path to load properties
private static final String PATH= "/i18n/alertDialogText.properties";
private static Properties properties;
private String value;
public void init() {
if (properties == null) {
properties = new Properties();
try {
properties.load(AlertMessageEnum.class.getResourceAsStream(PATH));
}
catch (Exception e) {
throw new RthosRuntimeException(e);
}
}
value = (String) properties.get(this.toString());
}
public String getValue() {
if (value == null) {
init();
}
return value;
}
}
public enum ConverterErrorEnum{
INVALID_EXTRACTION_PATH,
...
PATIAL_DATA_GENERATED;
private static final String PATH= "/i18n/converterErrorText.properties";
private static Properties properties;
private String value;
...
}
It's impossible to generate enums from property file with normal java code. You need a workaround, like:
use a class that publishes these constants aws immutable values
generate java source code from property file
generate java code with reflection
I suggest option 1. E.g. with singleton:
package com.example;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
public class Props {
private static Props INSTANCE;
public synchronized Props getInstance() {
if (INSTANCE == null) {
INSTANCE = new Props();
}
return INSTANCE;
}
private static final String PATH = "/i18n/converterErrorText.properties";
private Properties properties;
private List<String> keys;
public Props() {
properties = new Properties();
keys = new ArrayList<>();
try {
properties.load(getClass().getResourceAsStream(PATH));
for (Object key : properties.keySet()) {
keys.add(key.toString());
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Enumeration<Object> getKeys() {
return properties.keys();
}
public String getProperty(String key) {
return properties.getProperty(key);
}
}
Delegate to another class that holds Properties for all the enums:
public class PropertyProvider {
private static Map<Class<?>, Properties> pMap = new HashMap<>();
public static String getValue(Enum<?> enumValue, final String path) {
Properties properties = pMap.get(enumValue.getClass());
if (properties == null) {
properties = new Properties();
try {
properties.load(PropertyProvider.class.getResourceAsStream(path));
}
catch (Exception e) {
throw new RthosRuntimeException(e);
}
pMap.put(enumValue.getClass(), properties);
}
return (String) properties.get(enumValue.toString());
}
}
public enum ConverterErrorEnum{
INVALID_EXTRACTION_PATH,
...
PATIAL_DATA_GENERATED;
private static final String PATH= "/i18n/converterErrorText.properties";
private String value;
...
public String getValue() {
if (value == null) {
value = PropertyProvider.getValue(this, PATH);
}
return value;
}
}

JAVA: Choosing algorithm based on multiple dimensions

I have an instance of class Address, which I have to change according to environment:
1) Region: base class with sub-classes RegionA and RegionB
2) Site: base class with sub-classes SiteA, SiteB and SiteC
3) Language: base class with sub-classes LanguageA and LanguageB
Each subclass defines constraints about Address modification.
The problem is that each tuple (Region, Site, Language) has to define its own modifier.
So, I have a method adjust(Address a, Region r, Site s, Language l):
void adjust(Address a, Region r, Site s, Language l){
if(r instanceof Russia && s instanceof MailRu && Language instanceof Russian){
a.set_street("abc")
}
else if(r instanceof Russia && s instanceof MailRu && Language instanceof English){
a.set_street("fgh")
}
}
What is the best design patter to use in this case?
Use polymorphism to loose the ifs and instanceofs!
Use the abstract factory pattern for easier creation of the street info.
Region and Language are the (sub)products (resp. their factories, when you consider the way I did it), which are used to create the street in Address.
package address.example;
public class AddressExample
{
public static void main(String[] args)
{
LanguageFactoryProvider lfp = new LanguageFactoryProvider.LanguageFactoryProviderImpl();
RegionFactoryProvider rfp = new RegionFactoryProvider.RegionFactoryProviderImpl();
AddressProvider provider = new AddressProvider(lfp, rfp);
Address a = provider.createAddress("RU", "USA", "Famous Street");
System.out.println(a.getStreet());
System.out.println("-----");
Address b = provider.createAddress("EN", "RUS", "Good Street");
System.out.println(b.getStreet());
}
}
Output is
Address format: RU
Famous Street
USA
-----
Address format: EN
Good Street
RUS
This is the Address class, as you can see it delegates parts of the street creation to region and language (it's nothing fancy, but you get the point).
package address.example;
import address.example.LanguageFactoryProvider.Language;
import address.example.RegionFactoryProvider.Region;
public interface Address
{
public String getStreet();
static class AddressImpl implements Address
{
private final Region region;
private final Language language;
private final String street;
public AddressImpl(Region region, Language language, String street)
{
this.region = region;
this.language = language;
this.street = street;
}
#Override
public String getStreet()
{
StringBuilder sb = new StringBuilder();
sb.append(String.format("Address format: %s", language.getSpecifier()));
sb.append(String.format("%n"));
sb.append(street);
sb.append(String.format("%n"));
sb.append(region.getSpecifier());
return sb.toString();
}
}
}
And here are the other used classes. I'll add some more thoughts to it another time.
package address.example;
import address.example.LanguageFactoryProvider.Language;
import address.example.RegionFactoryProvider.Region;
public class AddressProvider
{
private final LanguageFactoryProvider lfp;
private final RegionFactoryProvider rfp;
public AddressProvider(LanguageFactoryProvider lfp, RegionFactoryProvider rfp)
{
this.lfp = lfp;
this.rfp = rfp;
}
public Address createAddress(String language, String region, String street)
{
Language _language = lfp.getLanguageFactory(language).createLanguage();
Region _region = rfp.getRegionFactory(region).createRegion();
return new Address.AddressImpl(_region, _language, street);
}
}
package address.example;
import java.util.HashMap;
import java.util.Map;
public interface LanguageFactoryProvider
{
public LanguageFactory getLanguageFactory(String language);
static interface LanguageFactory
{
public Language createLanguage();
}
static interface Language
{
public String getSpecifier();
}
static class LanguageImpl implements Language
{
private final String specifier;
public LanguageImpl(String specifier)
{
this.specifier = specifier;
}
#Override
public String getSpecifier()
{
return specifier;
}
}
static class LanguageFactoryProviderImpl implements LanguageFactoryProvider
{
private static final Map<String, LanguageFactory> factories = new HashMap<>();
static
{
factories.put("EN", new EnglishLanguageFactory());
factories.put("RU", new RussianLanguageFactory());
}
#Override
public LanguageFactory getLanguageFactory(String language)
{
if (!factories.containsKey(language))
throw new IllegalArgumentException();
LanguageFactory factory = factories.get(language);
return factory;
}
}
static class RussianLanguageFactory implements LanguageFactory
{
#Override
public Language createLanguage()
{
return new LanguageImpl("RU");
}
}
static class EnglishLanguageFactory implements LanguageFactory
{
#Override
public Language createLanguage()
{
return new LanguageImpl("EN");
}
}
}
package address.example;
import java.util.HashMap;
import java.util.Map;
public interface RegionFactoryProvider
{
public RegionFactory getRegionFactory(String region);
static interface RegionFactory
{
public Region createRegion();
}
static interface Region
{
public String getSpecifier();
}
static class RegionImpl implements Region
{
private final String specifier;
public RegionImpl(String specifier)
{
this.specifier = specifier;
}
#Override
public String getSpecifier()
{
return specifier;
}
}
static class RegionFactoryProviderImpl implements RegionFactoryProvider
{
private static final Map<String, RegionFactory> factories = new HashMap<>();
static
{
factories.put("RUS", new RussianRegionFactory());
factories.put("USA", new UsRegionFactory());
}
#Override
public RegionFactory getRegionFactory(String region)
{
if (!factories.containsKey(region))
throw new IllegalArgumentException();
RegionFactory factory = factories.get(region);
return factory;
}
}
static class RussianRegionFactory implements RegionFactory
{
#Override
public Region createRegion()
{
return new RegionImpl("RUS");
}
}
static class UsRegionFactory implements RegionFactory
{
#Override
public Region createRegion()
{
return new RegionImpl("USA");
}
}
}
This is typical business "logic" with many cases/rules. It pays to make a declarative solution for this.
<rule>
<when category="Region" value="Russia"/>
<when category="Site" value="MailRu"/>
<action category="Address" value="abc"/>
</rule>
This allows to build in diagnostics, integrity checks, log uncovered cases, make historical logs for future analysis on future bug reports.
It might even be more readable. Transformable in a nice HTML table hierarchy for manager level documentation.
It boils down to the fact that your code is procedural, without possibility to store the control-flow path taken. A model-driven approach can alleviate that. A DSL would be feasible, but I find a free form data approach to be a bit more creative, direct.

Override expectations in JMockit

I want to override a previously defined expectation in JMockit. This is what I tried (see code below) -- I have a private class where I record all the common expectations and I replay it in various test methods. However, one of my method needs most of the common expectations except for few. First, I am calling the CommonNonStrictExpectations private class and then defining test specific expectations in my testMethod1 with a hope that what I defined here overrides what I have defined earlier. I dont think this way of overriding works, is there a way that works?
//MyClassTest.java
import MyClass;
public class MyClassTest {
#Mocked Someobject object;
#Test
public void testMethod1() throws Exception {
new CommonNonStrictExpectations() {};
new NonStrictExpectations() {
{
object.getInt(anyInt); returns (-1);
object.getString(anyInt); returns ("failure");
}
};
System.out.println("position: " + object.getInt(1));
System.out.println("exec status: " + object.getString(1));
MyClass m = new MyClass();
m.method(object, -1);
}
private class CommonNonStrictExpectations extends NonStrictExpectations {
public CommonNonStrictExpectations () throws Exception {
object.getInt(anyInt); returns (anyInt);
object.getString(anyInt); returns ("success");
}
}
}
//MyClass.java
import Someobject;
public class MyClass {
public void method (Someobject someobject, int i) {
String status = someobject.getString(i);
if (status.equalsIgnoreCase("success")) {
print(someobject, "success");
} else if (status.equalsIgnoreCase("failure")) {
print(someobject, "failure");
} else
print(someobject, "");
}
private String print(Someobject someobject, String status) {
return someobject.printMessage (status);
}
}
// Someobject.java
public class Someobject {
public String getString(int i) {
if (i < 0)
return "failure";
else if (i > 0)
return "success";
else
return "";
}
public int getInt(int k) {
return k;
}
public String printMessage (String status) {
return "status is: " + status;
}
}

Converting String to BigDecimal in GWT

In my GWT web application I have a textbox that holds a price.
How can one convert that String to a BigDecimal?
The easiest way is to create new text box widget that inherits ValueBox.
If you do it this way, you won't have to convert any string values manually. the ValueBox takes care of it all.
To get the BigDecimal value entered you can just go:
BigDecimal value = myTextBox.getValue();
Your BigDecimalBox.java:
public class BigDecimalBox extends ValueBox<BigDecimal> {
public BigDecimalBox() {
super(Document.get().createTextInputElement(), BigDecimalRenderer.instance(),
BigDecimalParser.instance());
}
}
Then your BigDecimalRenderer.java
public class BigDecimalRenderer extends AbstractRenderer<BigDecimal> {
private static BigDecimalRenderer INSTANCE;
public static Renderer<BigDecimal> instance() {
if (INSTANCE == null) {
INSTANCE = new BigDecimalRenderer();
}
return INSTANCE;
}
protected BigDecimalRenderer() {
}
public String render(BigDecimal object) {
if (null == object) {
return "";
}
return NumberFormat.getDecimalFormat().format(object);
}
}
And your BigDecimalParser.java
package com.google.gwt.text.client;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.text.shared.Parser;
import java.text.ParseException;
public class BigDecimalParser implements Parser<BigDecimal> {
private static BigDecimalParser INSTANCE;
public static Parser<BigDecimal> instance() {
if (INSTANCE == null) {
INSTANCE = new BigDecimalParser();
}
return INSTANCE;
}
protected BigDecimalParser() {
}
public BigDecimal parse(CharSequence object) throws ParseException {
if ("".equals(object.toString())) {
return null;
}
try {
return new BigDecimal(object.toString());
} catch (NumberFormatException e) {
throw new ParseException(e.getMessage(), 0);
}
}
}
Take a look at GWT-Math.

Categories