Resolves checkstyle errors for naked-objects null-object object-mother object-pool observer queue-load-leveling (#1082)

* Reduces checkstyle errors in naked-objects

* Reduces checkstyle errors in null-object

* Reduces checkstyle errors in object-mother

* Reduces checkstyle errors in object-pool

* Reduces checkstyle errors in observer

* Reduces checkstyle errors in queue-load-leveling
This commit is contained in:
Anurag Agarwal 2019-11-13 00:56:15 +05:30 committed by Ilkka Seppälä
parent 1e76d91929
commit 6ef840f3cf
41 changed files with 242 additions and 288 deletions

View File

@ -31,7 +31,8 @@ import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.SemanticsOf; import org.apache.isis.applib.annotation.SemanticsOf;
/** /**
* HomePage Domain Service * HomePage Domain Service.
*
* @see HomePageViewModel linked view to HomePage * @see HomePageViewModel linked view to HomePage
*/ */
@DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY) @DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY)

View File

@ -23,16 +23,14 @@
package domainapp.dom.app.homepage; package domainapp.dom.app.homepage;
import java.util.List;
import org.apache.isis.applib.annotation.ViewModel;
import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObject;
import domainapp.dom.modules.simple.SimpleObjects; import domainapp.dom.modules.simple.SimpleObjects;
import java.util.List;
import org.apache.isis.applib.annotation.ViewModel;
/** /**
* Model linked to the HomePage * Model linked to the HomePage The underlying layout is specified by json.
* The underlying layout is specified by json *
* @see HomePageService - Service Linked to the HomePage * @see HomePageService - Service Linked to the HomePage
*/ */
@ViewModel @ViewModel

View File

@ -15,29 +15,29 @@
* limitations under the License. * limitations under the License.
*/ */
{ {
"columns": [ "columns": [
{ {
"span": 0, "span": 0,
"memberGroups": {} "memberGroups": {}
}, },
{ {
"span": 0, "span": 0,
"memberGroups": {} "memberGroups": {}
}, },
{ {
"span": 0, "span": 0,
"memberGroups": {} "memberGroups": {}
}, },
{ {
"span": 12, "span": 12,
"collections": { "collections": {
"objects": { "objects": {
"collectionLayout": { "collectionLayout": {
"render": "EAGERLY" "render": "EAGERLY"
} }
}
}
} }
], }
"actions": {} }
],
"actions": {}
} }

View File

@ -26,7 +26,6 @@ package domainapp.dom.modules.simple;
import javax.jdo.JDOHelper; import javax.jdo.JDOHelper;
import javax.jdo.annotations.IdentityType; import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.VersionStrategy; import javax.jdo.annotations.VersionStrategy;
import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.Identifier; import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.Action;
@ -43,7 +42,7 @@ import org.apache.isis.applib.services.i18n.TranslatableString;
import org.apache.isis.applib.util.ObjectContracts; import org.apache.isis.applib.util.ObjectContracts;
/** /**
* Definition of a Simple Object * Definition of a Simple Object.
*/ */
@javax.jdo.annotations.PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "simple", @javax.jdo.annotations.PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "simple",
table = "SimpleObject") table = "SimpleObject")
@ -87,11 +86,11 @@ public class SimpleObject implements Comparable<SimpleObject> {
// region > updateName (action) // region > updateName (action)
/** /**
* Event used to update the Name in the Domain * Event used to update the Name in the Domain.
*/ */
public static class UpdateNameDomainEvent extends ActionDomainEvent<SimpleObject> { public static class UpdateNameDomainEvent extends ActionDomainEvent<SimpleObject> {
public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier, public UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier,
final Object... arguments) { final Object... arguments) {
super(source, identifier, arguments); super(source, identifier, arguments);
} }
} }

View File

@ -15,42 +15,42 @@
* limitations under the License. * limitations under the License.
*/ */
{ {
"columns": [ "columns": [
{ {
"span": 6, "span": 6,
"memberGroups": { "memberGroups": {
"General": { "General": {
"members": { "members": {
"name": { "name": {
"actions": { "actions": {
"updateName": { "updateName": {
"actionLayout": { "actionLayout": {
"position": "BOTTOM" "position": "BOTTOM"
} }
}
}
},
"versionSequence": {
"propertyLayout": {
"name": "version"
}
}
}
} }
}
},
"versionSequence": {
"propertyLayout": {
"name": "version"
}
} }
}, }
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 6,
"collections": {}
} }
], }
"actions": {} },
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 6,
"collections": {}
}
],
"actions": {}
} }

View File

@ -24,7 +24,6 @@
package domainapp.dom.modules.simple; package domainapp.dom.modules.simple;
import java.util.List; import java.util.List;
import org.apache.isis.applib.DomainObjectContainer; import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.Identifier; import org.apache.isis.applib.Identifier;
import org.apache.isis.applib.annotation.Action; import org.apache.isis.applib.annotation.Action;
@ -40,7 +39,7 @@ import org.apache.isis.applib.services.eventbus.ActionDomainEvent;
import org.apache.isis.applib.services.i18n.TranslatableString; import org.apache.isis.applib.services.i18n.TranslatableString;
/** /**
* Domain Service for Simple Objects * Domain Service for Simple Objects.
*/ */
@DomainService(repositoryFor = SimpleObject.class) @DomainService(repositoryFor = SimpleObject.class)
@DomainServiceLayout(menuOrder = "10") @DomainServiceLayout(menuOrder = "10")
@ -82,18 +81,18 @@ public class SimpleObjects {
// endregion // endregion
/** /**
* Create Domain Event on SimpleObjects * Create Domain Event on SimpleObjects.
*/ */
// region > create (action) // region > create (action)
public static class CreateDomainEvent extends ActionDomainEvent<SimpleObjects> { public static class CreateDomainEvent extends ActionDomainEvent<SimpleObjects> {
public CreateDomainEvent(final SimpleObjects source, final Identifier identifier, public CreateDomainEvent(final SimpleObjects source, final Identifier identifier,
final Object... arguments) { final Object... arguments) {
super(source, identifier, arguments); super(source, identifier, arguments);
} }
} }
/** /**
* Create simple object * Create simple object.
*/ */
@Action(domainEvent = CreateDomainEvent.class) @Action(domainEvent = CreateDomainEvent.class)
@MemberOrder(sequence = "3") @MemberOrder(sequence = "3")

View File

@ -23,14 +23,13 @@
package domainapp.fixture; package domainapp.fixture;
import domainapp.fixture.scenarios.RecreateSimpleObjects;
import org.apache.isis.applib.annotation.DomainService; import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService; import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.fixturescripts.FixtureScripts; import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.apache.isis.applib.services.fixturespec.FixtureScriptsSpecification; import org.apache.isis.applib.services.fixturespec.FixtureScriptsSpecification;
import org.apache.isis.applib.services.fixturespec.FixtureScriptsSpecificationProvider; import org.apache.isis.applib.services.fixturespec.FixtureScriptsSpecificationProvider;
import domainapp.fixture.scenarios.RecreateSimpleObjects;
/** /**
* Specifies where to find fixtures, and other settings. * Specifies where to find fixtures, and other settings.
*/ */

View File

@ -23,13 +23,12 @@
package domainapp.fixture.modules.simple; package domainapp.fixture.modules.simple;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObject;
import domainapp.dom.modules.simple.SimpleObjects; import domainapp.dom.modules.simple.SimpleObjects;
import org.apache.isis.applib.fixturescripts.FixtureScript;
/** /**
* Fixture to create a simple object * Fixture to create a simple object.
*/ */
public class SimpleObjectCreate extends FixtureScript { public class SimpleObjectCreate extends FixtureScript {
@ -46,7 +45,7 @@ public class SimpleObjectCreate extends FixtureScript {
private String name; private String name;
/** /**
* Name of the object (required) * Name of the object (required).
*/ */
public String getName() { public String getName() {
return name; return name;

View File

@ -27,7 +27,7 @@ import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.jdosupport.IsisJdoSupport; import org.apache.isis.applib.services.jdosupport.IsisJdoSupport;
/** /**
* TearDown/Cleanup for SimpleObjects * TearDown/Cleanup for SimpleObjects.
*/ */
public class SimpleObjectsTearDown extends FixtureScript { public class SimpleObjectsTearDown extends FixtureScript {

View File

@ -27,19 +27,18 @@ import com.google.common.collect.Lists;
import domainapp.dom.modules.simple.SimpleObject; import domainapp.dom.modules.simple.SimpleObject;
import domainapp.fixture.modules.simple.SimpleObjectCreate; import domainapp.fixture.modules.simple.SimpleObjectCreate;
import domainapp.fixture.modules.simple.SimpleObjectsTearDown; import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import org.apache.isis.applib.fixturescripts.FixtureScript;
/** /**
* Create a bunch of simple Objects * Create a bunch of simple Objects.
*/ */
public class RecreateSimpleObjects extends FixtureScript { public class RecreateSimpleObjects extends FixtureScript {
public final List<String> names = Collections.unmodifiableList(List.of("Foo", "Bar", "Baz", public final List<String> names = Collections.unmodifiableList(List.of("Foo", "Bar", "Baz",
"Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo")); "Frodo", "Froyo", "Fizz", "Bip", "Bop", "Bang", "Boo"));
// region > number (optional input) // region > number (optional input)
private Integer number; private Integer number;

View File

@ -23,13 +23,6 @@
package domainapp.webapp; package domainapp.webapp;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.io.Resources; import com.google.common.io.Resources;
import com.google.inject.AbstractModule; import com.google.inject.AbstractModule;
@ -37,30 +30,31 @@ import com.google.inject.Module;
import com.google.inject.name.Names; import com.google.inject.name.Names;
import com.google.inject.util.Modules; import com.google.inject.util.Modules;
import com.google.inject.util.Providers; import com.google.inject.util.Providers;
import de.agilecoders.wicket.core.Bootstrap;
import de.agilecoders.wicket.core.settings.IBootstrapSettings;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.isis.viewer.wicket.viewer.IsisWicketApplication;
import org.apache.isis.viewer.wicket.viewer.integration.wicket.AuthenticatedWebSessionForIsis;
import org.apache.wicket.Session; import org.apache.wicket.Session;
import org.apache.wicket.request.IRequestParameters; import org.apache.wicket.request.IRequestParameters;
import org.apache.wicket.request.Request; import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response; import org.apache.wicket.request.Response;
import org.apache.wicket.request.http.WebRequest; import org.apache.wicket.request.http.WebRequest;
import org.apache.isis.viewer.wicket.viewer.IsisWicketApplication;
import org.apache.isis.viewer.wicket.viewer.integration.wicket.AuthenticatedWebSessionForIsis;
import de.agilecoders.wicket.core.Bootstrap;
import de.agilecoders.wicket.core.settings.IBootstrapSettings;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchTheme;
import de.agilecoders.wicket.themes.markup.html.bootswatch.BootswatchThemeProvider;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* As specified in <tt>web.xml</tt>. * As specified in <tt>web.xml</tt>.
* *
* <p> * <p>See:
* See: *
*
* <pre> * <pre>
* &lt;filter&gt; * &lt;filter&gt;
* &lt;filter-name&gt;wicket&lt;/filter-name&gt; * &lt;filter-name&gt;wicket&lt;/filter-name&gt;
@ -71,7 +65,6 @@ import org.slf4j.LoggerFactory;
* &lt;/init-param&gt; * &lt;/init-param&gt;
* &lt;/filter&gt; * &lt;/filter&gt;
* </pre> * </pre>
*
*/ */
public class SimpleApplication extends IsisWicketApplication { public class SimpleApplication extends IsisWicketApplication {
@ -80,11 +73,10 @@ public class SimpleApplication extends IsisWicketApplication {
/** /**
* uncomment for a (slightly hacky) way of allowing logins using query args, eg: * uncomment for a (slightly hacky) way of allowing logins using query args, eg:
* *
* <tt>{@code ?user=sven&pass=pass}</tt> * <tt>{@code ?user=sven&pass=pass}</tt>
* *
* <p> * <p>for demos only, obvious.
* for demos only, obvious.
*/ */
private static final boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false; private static final boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false;

View File

@ -24,18 +24,16 @@
package com.iluwatar.nullobject; package com.iluwatar.nullobject;
/** /**
*
* Null Object pattern replaces null values with neutral objects. Many times this simplifies * Null Object pattern replaces null values with neutral objects. Many times this simplifies
* algorithms since no extra null checks are needed. * algorithms since no extra null checks are needed.
* <p>
* In this example we build a binary tree where the nodes are either normal or Null Objects. No null
* values are used in the tree making the traversal easy.
* *
* <p>In this example we build a binary tree where the nodes are either normal or Null Objects. No
* null values are used in the tree making the traversal easy.
*/ */
public class App { public class App {
/** /**
* Program entry point * Program entry point.
* *
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
@ -44,7 +42,7 @@ public class App {
new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(), new NodeImpl("1", new NodeImpl("11", new NodeImpl("111", NullNode.getInstance(),
NullNode.getInstance()), NullNode.getInstance()), new NodeImpl("12", NullNode.getInstance()), NullNode.getInstance()), new NodeImpl("12",
NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(), NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(),
NullNode.getInstance()))); NullNode.getInstance())));
root.walk(); root.walk();
} }

View File

@ -24,9 +24,7 @@
package com.iluwatar.nullobject; package com.iluwatar.nullobject;
/** /**
*
* Interface for binary tree node. * Interface for binary tree node.
*
*/ */
public interface Node { public interface Node {

View File

@ -27,9 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
*
* Implementation for binary tree's normal nodes. * Implementation for binary tree's normal nodes.
*
*/ */
public class NodeImpl implements Node { public class NodeImpl implements Node {
@ -40,7 +38,7 @@ public class NodeImpl implements Node {
private final Node right; private final Node right;
/** /**
* Constructor * Constructor.
*/ */
public NodeImpl(String name, Node left, Node right) { public NodeImpl(String name, Node left, Node right) {
this.name = name; this.name = name;

View File

@ -24,17 +24,16 @@
package com.iluwatar.nullobject; package com.iluwatar.nullobject;
/** /**
*
* Null Object implementation for binary tree node. * Null Object implementation for binary tree node.
* <p>
* Implemented as Singleton, since all the NullNodes are the same.
* *
* <p>Implemented as Singleton, since all the NullNodes are the same.
*/ */
public final class NullNode implements Node { public final class NullNode implements Node {
private static NullNode instance = new NullNode(); private static NullNode instance = new NullNode();
private NullNode() {} private NullNode() {
}
public static NullNode getInstance() { public static NullNode getInstance() {
return instance; return instance;

View File

@ -24,7 +24,7 @@
package com.iluwatar.objectmother; package com.iluwatar.objectmother;
/** /**
* Defines all attributes and behaviour related to the King * Defines all attributes and behaviour related to the King.
*/ */
public class King implements Royalty { public class King implements Royalty {
boolean isDrunk = false; boolean isDrunk = false;
@ -56,6 +56,7 @@ public class King implements Royalty {
/** /**
* Method to flirt to a queen. * Method to flirt to a queen.
*
* @param queen Queen which should be flirted. * @param queen Queen which should be flirted.
*/ */
public void flirt(Queen queen) { public void flirt(Queen queen) {

View File

@ -24,7 +24,7 @@
package com.iluwatar.objectmother; package com.iluwatar.objectmother;
/** /**
* Defines all attributes and behaviour related to the Queen * Defines all attributes and behaviour related to the Queen.
*/ */
public class Queen implements Royalty { public class Queen implements Royalty {
private boolean isDrunk = false; private boolean isDrunk = false;
@ -61,6 +61,7 @@ public class Queen implements Royalty {
/** /**
* Method which is called when the king is flirting to a queen. * Method which is called when the king is flirting to a queen.
*
* @param king King who initialized the flirt. * @param king King who initialized the flirt.
* @return A value which describes if the flirt was successful or not. * @return A value which describes if the flirt was successful or not.
*/ */

View File

@ -24,7 +24,7 @@
package com.iluwatar.objectmother; package com.iluwatar.objectmother;
/** /**
* Interface contracting Royalty Behaviour * Interface contracting Royalty Behaviour.
*/ */
public interface Royalty { public interface Royalty {
void makeDrunk(); void makeDrunk();

View File

@ -24,12 +24,13 @@
package com.iluwatar.objectmother; package com.iluwatar.objectmother;
/** /**
* Object Mother Pattern generating Royalty Types * Object Mother Pattern generating Royalty Types.
*/ */
public final class RoyaltyObjectMother { public final class RoyaltyObjectMother {
/** /**
* Method to create a sober and unhappy king. The standard parameters are set. * Method to create a sober and unhappy king. The standard parameters are set.
*
* @return An instance of {@link com.iluwatar.objectmother.King} with the standard properties. * @return An instance of {@link com.iluwatar.objectmother.King} with the standard properties.
*/ */
public static King createSoberUnhappyKing() { public static King createSoberUnhappyKing() {
@ -38,6 +39,7 @@ public final class RoyaltyObjectMother {
/** /**
* Method of the object mother to create a drunk king. * Method of the object mother to create a drunk king.
*
* @return A drunk {@link com.iluwatar.objectmother.King}. * @return A drunk {@link com.iluwatar.objectmother.King}.
*/ */
public static King createDrunkKing() { public static King createDrunkKing() {
@ -48,6 +50,7 @@ public final class RoyaltyObjectMother {
/** /**
* Method to create a happy king. * Method to create a happy king.
*
* @return A happy {@link com.iluwatar.objectmother.King}. * @return A happy {@link com.iluwatar.objectmother.King}.
*/ */
public static King createHappyKing() { public static King createHappyKing() {
@ -58,6 +61,7 @@ public final class RoyaltyObjectMother {
/** /**
* Method to create a happy and drunk king. * Method to create a happy and drunk king.
*
* @return A drunk and happy {@link com.iluwatar.objectmother.King}. * @return A drunk and happy {@link com.iluwatar.objectmother.King}.
*/ */
public static King createHappyDrunkKing() { public static King createHappyDrunkKing() {
@ -69,6 +73,7 @@ public final class RoyaltyObjectMother {
/** /**
* Method to create a flirty queen. * Method to create a flirty queen.
*
* @return A flirty {@link com.iluwatar.objectmother.Queen}. * @return A flirty {@link com.iluwatar.objectmother.Queen}.
*/ */
public static Queen createFlirtyQueen() { public static Queen createFlirtyQueen() {
@ -79,6 +84,7 @@ public final class RoyaltyObjectMother {
/** /**
* Method to create a not flirty queen. * Method to create a not flirty queen.
*
* @return A not flirty {@link com.iluwatar.objectmother.Queen}. * @return A not flirty {@link com.iluwatar.objectmother.Queen}.
*/ */
public static Queen createNotFlirtyQueen() { public static Queen createNotFlirtyQueen() {

View File

@ -27,32 +27,30 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
*
* When it is necessary to work with a large number of objects that are particularly expensive to * When it is necessary to work with a large number of objects that are particularly expensive to
* instantiate and each object is only needed for a short period of time, the performance of an * instantiate and each object is only needed for a short period of time, the performance of an
* entire application may be adversely affected. An object pool design pattern may be deemed * entire application may be adversely affected. An object pool design pattern may be deemed
* desirable in cases such as these. * desirable in cases such as these.
* <p> *
* The object pool design pattern creates a set of objects that may be reused. When a new object is * <p>The object pool design pattern creates a set of objects that may be reused. When a new object
* needed, it is requested from the pool. If a previously prepared object is available it is * is needed, it is requested from the pool. If a previously prepared object is available it is
* returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a * returned immediately, avoiding the instantiation cost. If no objects are present in the pool, a
* new item is created and returned. When the object has been used and is no longer needed, it is * new item is created and returned. When the object has been used and is no longer needed, it is
* returned to the pool, allowing it to be used again in the future without repeating the * returned to the pool, allowing it to be used again in the future without repeating the
* computationally expensive instantiation process. It is important to note that once an object has * computationally expensive instantiation process. It is important to note that once an object has
* been used and returned, existing references will become invalid. * been used and returned, existing references will become invalid.
* <p>
* In this example we have created {@link OliphauntPool} inheriting from generic {@link ObjectPool}.
* {@link Oliphaunt}s can be checked out from the pool and later returned to it. The pool tracks
* created instances and their status (available, inUse).
* *
* <p>In this example we have created {@link OliphauntPool} inheriting from generic {@link
* ObjectPool}. {@link Oliphaunt}s can be checked out from the pool and later returned to it. The
* pool tracks created instances and their status (available, inUse).
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point * Program entry point.
* *
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {

View File

@ -27,7 +27,8 @@ import java.util.HashSet;
import java.util.Set; import java.util.Set;
/** /**
* Generic object pool * Generic object pool.
*
* @param <T> Type T of Object in the Pool * @param <T> Type T of Object in the Pool
*/ */
public abstract class ObjectPool<T> { public abstract class ObjectPool<T> {
@ -38,7 +39,7 @@ public abstract class ObjectPool<T> {
protected abstract T create(); protected abstract T create();
/** /**
* Checkout object from pool * Checkout object from pool.
*/ */
public synchronized T checkOut() { public synchronized T checkOut() {
if (available.isEmpty()) { if (available.isEmpty()) {

View File

@ -26,9 +26,7 @@ package com.iluwatar.object.pool;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
/** /**
* * Oliphaunts are expensive to create.
* Oliphaunts are expensive to create
*
*/ */
public class Oliphaunt { public class Oliphaunt {
@ -37,7 +35,7 @@ public class Oliphaunt {
private final int id; private final int id;
/** /**
* Constructor * Constructor.
*/ */
public Oliphaunt() { public Oliphaunt() {
id = counter.incrementAndGet(); id = counter.incrementAndGet();

View File

@ -24,9 +24,7 @@
package com.iluwatar.object.pool; package com.iluwatar.object.pool;
/** /**
* * Oliphaunt object pool.
* Oliphaunt object pool
*
*/ */
public class OliphauntPool extends ObjectPool<Oliphaunt> { public class OliphauntPool extends ObjectPool<Oliphaunt> {

View File

@ -30,25 +30,23 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
*
* The Observer pattern is a software design pattern in which an object, called the subject, * The Observer pattern is a software design pattern in which an object, called the subject,
* maintains a list of its dependents, called observers, and notifies them automatically of any * maintains a list of its dependents, called observers, and notifies them automatically of any
* state changes, usually by calling one of their methods. It is mainly used to implement * state changes, usually by calling one of their methods. It is mainly used to implement
* distributed event handling systems. The Observer pattern is also a key part in the familiar * distributed event handling systems. The Observer pattern is also a key part in the familiar
* modelviewcontroller (MVC) architectural pattern. The Observer pattern is implemented in * modelviewcontroller (MVC) architectural pattern. The Observer pattern is implemented in
* numerous programming libraries and systems, including almost all GUI toolkits. * numerous programming libraries and systems, including almost all GUI toolkits.
* <p> *
* In this example {@link Weather} has a state that can be observed. The {@link Orcs} and * <p>In this example {@link Weather} has a state that can be observed. The {@link Orcs} and {@link
* {@link Hobbits} register as observers and receive notifications when the {@link Weather} changes. * Hobbits} register as observers and receive notifications when the {@link Weather} changes.
*
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/** /**
* Program entry point * Program entry point.
* *
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
@ -64,13 +62,13 @@ public class App {
// Generic observer inspired by Java Generics and Collection by Naftalin & Wadler // Generic observer inspired by Java Generics and Collection by Naftalin & Wadler
LOGGER.info("--Running generic version--"); LOGGER.info("--Running generic version--");
GWeather gWeather = new GWeather(); GWeather genericWeather = new GWeather();
gWeather.addObserver(new GOrcs()); genericWeather.addObserver(new GOrcs());
gWeather.addObserver(new GHobbits()); genericWeather.addObserver(new GHobbits());
gWeather.timePasses(); genericWeather.timePasses();
gWeather.timePasses(); genericWeather.timePasses();
gWeather.timePasses(); genericWeather.timePasses();
gWeather.timePasses(); genericWeather.timePasses();
} }
} }

View File

@ -27,9 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * Hobbits.
* Hobbits
*
*/ */
public class Hobbits implements WeatherObserver { public class Hobbits implements WeatherObserver {

View File

@ -27,9 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * Orcs.
* Orcs
*
*/ */
public class Orcs implements WeatherObserver { public class Orcs implements WeatherObserver {

View File

@ -23,17 +23,14 @@
package com.iluwatar.observer; package com.iluwatar.observer;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
/** /**
*
* Weather can be observed by implementing {@link WeatherObserver} interface and registering as * Weather can be observed by implementing {@link WeatherObserver} interface and registering as
* listener. * listener.
*
*/ */
public class Weather { public class Weather {
@ -56,7 +53,7 @@ public class Weather {
} }
/** /**
* Makes time pass for weather * Makes time pass for weather.
*/ */
public void timePasses() { public void timePasses() {
WeatherType[] enumValues = WeatherType.values(); WeatherType[] enumValues = WeatherType.values();

View File

@ -24,9 +24,7 @@
package com.iluwatar.observer; package com.iluwatar.observer;
/** /**
*
* Observer interface. * Observer interface.
*
*/ */
public interface WeatherObserver { public interface WeatherObserver {

View File

@ -24,9 +24,7 @@
package com.iluwatar.observer; package com.iluwatar.observer;
/** /**
* * WeatherType enumeration.
* WeatherType enumeration
*
*/ */
public enum WeatherType { public enum WeatherType {

View File

@ -28,9 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * GHobbits.
* GHobbits
*
*/ */
public class GHobbits implements Race { public class GHobbits implements Race {

View File

@ -28,9 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * GOrcs.
* GOrcs
*
*/ */
public class GOrcs implements Race { public class GOrcs implements Race {

View File

@ -28,9 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * GWeather.
* GWeather
*
*/ */
public class GWeather extends Observable<GWeather, Race, WeatherType> { public class GWeather extends Observable<GWeather, Race, WeatherType> {
@ -43,7 +41,7 @@ public class GWeather extends Observable<GWeather, Race, WeatherType> {
} }
/** /**
* Makes time pass for weather * Makes time pass for weather.
*/ */
public void timePasses() { public void timePasses() {
WeatherType[] enumValues = WeatherType.values(); WeatherType[] enumValues = WeatherType.values();

View File

@ -27,7 +27,7 @@ import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.CopyOnWriteArrayList;
/** /**
* Generic observer inspired by Java Generics and Collection by {@literal Naftalin & Wadler} * Generic observer inspired by Java Generics and Collection by {@literal Naftalin & Wadler}.
* *
* @param <S> Subject * @param <S> Subject
* @param <O> Observer * @param <O> Observer
@ -50,7 +50,7 @@ public abstract class Observable<S extends Observable<S, O, A>, O extends Observ
} }
/** /**
* Notify observers * Notify observers.
*/ */
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
public void notifyObservers(A argument) { public void notifyObservers(A argument) {

View File

@ -24,7 +24,8 @@
package com.iluwatar.observer.generic; package com.iluwatar.observer.generic;
/** /**
* Observer * Observer.
*
* @param <S> Observable * @param <S> Observable
* @param <O> Observer * @param <O> Observer
* @param <A> Action * @param <A> Action

View File

@ -26,9 +26,7 @@ package com.iluwatar.observer.generic;
import com.iluwatar.observer.WeatherType; import com.iluwatar.observer.WeatherType;
/** /**
* * Race.
* Race
*
*/ */
public interface Race extends Observer<GWeather, Race, WeatherType> { public interface Race extends Observer<GWeather, Race, WeatherType> {
} }

View File

@ -26,69 +26,69 @@ package com.iluwatar.queue.load.leveling;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * Many solutions in the cloud involve running tasks that invoke services. In this environment, if a
* Many solutions in the cloud involve running tasks that invoke services. In this environment, * service is subjected to intermittent heavy loads, it can cause performance or reliability
* if a service is subjected to intermittent heavy loads, it can cause performance or reliability issues. * issues.
* <p> *
* A service could be a component that is part of the same solution as the tasks that utilize it, or it * <p>A service could be a component that is part of the same solution as the tasks that utilize
* could be a third-party service providing access to frequently used resources such as a cache or a storage service. * it, or it could be a third-party service providing access to frequently used resources such as a
* If the same service is utilized by a number of tasks running concurrently, it can be difficult to predict the * cache or a storage service. If the same service is utilized by a number of tasks running
* volume of requests to which the service might be subjected at any given point in time. * concurrently, it can be difficult to predict the volume of requests to which the service might be
* <p> * subjected at any given point in time.
* We will build a queue-based-load-leveling to solve above problem. *
* Refactor the solution and introduce a queue between the task and the service. * <p>We will build a queue-based-load-leveling to solve above problem. Refactor the solution and
* The task and the service run asynchronously. The task posts a message containing the data required * introduce a queue between the task and the service. The task and the service run asynchronously.
* by the service to a queue. The queue acts as a buffer, storing the message until it is retrieved * The task posts a message containing the data required by the service to a queue. The queue acts
* by the service. The service retrieves the messages from the queue and processes them. * as a buffer, storing the message until it is retrieved by the service. The service retrieves the
* Requests from a number of tasks, which can be generated at a highly variable rate, can be passed * messages from the queue and processes them. Requests from a number of tasks, which can be
* to the service through the same message queue. * generated at a highly variable rate, can be passed to the service through the same message
* <p> * queue.
* The queue effectively decouples the tasks from the service, and the service can handle the messages *
* at its own pace irrespective of the volume of requests from concurrent tasks. Additionally, * <p>The queue effectively decouples the tasks from the service, and the service can handle the
* there is no delay to a task if the service is not available at the time it posts a message to the queue. * messages at its own pace irrespective of the volume of requests from concurrent tasks.
* <p> * Additionally, there is no delay to a task if the service is not available at the time it posts a
* In this example we have a class {@link MessageQueue} to hold the message {@link Message} objects. * message to the queue.
* All the worker threads {@link TaskGenerator} will submit the messages to the MessageQueue. *
* The service executor class {@link ServiceExecutor} will pick up one task at a time from the Queue and * <p>In this example we have a class {@link MessageQueue} to hold the message {@link Message}
* execute them. * objects. All the worker threads {@link TaskGenerator} will submit the messages to the
* * MessageQueue. The service executor class {@link ServiceExecutor} will pick up one task at a time
* from the Queue and execute them.
*/ */
public class App { public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
//Executor shut down time limit. //Executor shut down time limit.
private static final int SHUTDOWN_TIME = 15; private static final int SHUTDOWN_TIME = 15;
/** /**
* Program entry point * Program entry point.
* *
* @param args command line args * @param args command line args
*/ */
public static void main(String[] args) { public static void main(String[] args) {
// An Executor that provides methods to manage termination and methods that can // An Executor that provides methods to manage termination and methods that can
// produce a Future for tracking progress of one or more asynchronous tasks. // produce a Future for tracking progress of one or more asynchronous tasks.
ExecutorService executor = null; ExecutorService executor = null;
try { try {
// Create a MessageQueue object. // Create a MessageQueue object.
MessageQueue msgQueue = new MessageQueue(); MessageQueue msgQueue = new MessageQueue();
LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads."); LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads.");
// Create three TaskGenerator threads. Each of them will submit different number of jobs. // Create three TaskGenerator threads. Each of them will submit different number of jobs.
Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5); final Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5);
Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1); final Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1);
Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2); final Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2);
// Create e service which should process the submitted jobs. // Create e service which should process the submitted jobs.
Runnable srvRunnable = new ServiceExecutor(msgQueue); final Runnable srvRunnable = new ServiceExecutor(msgQueue);
// Create a ThreadPool of 2 threads and // Create a ThreadPool of 2 threads and
// submit all Runnable task for execution to executor.. // submit all Runnable task for execution to executor..
@ -96,17 +96,18 @@ public class App {
executor.submit(taskRunnable1); executor.submit(taskRunnable1);
executor.submit(taskRunnable2); executor.submit(taskRunnable2);
executor.submit(taskRunnable3); executor.submit(taskRunnable3);
// submitting serviceExecutor thread to the Executor service. // submitting serviceExecutor thread to the Executor service.
executor.submit(srvRunnable); executor.submit(srvRunnable);
// Initiates an orderly shutdown. // Initiates an orderly shutdown.
LOGGER.info("Intiating shutdown. Executor will shutdown only after all the Threads are completed."); LOGGER.info("Initiating shutdown."
+ " Executor will shutdown only after all the Threads are completed.");
executor.shutdown(); executor.shutdown();
// Wait for SHUTDOWN_TIME seconds for all the threads to complete // Wait for SHUTDOWN_TIME seconds for all the threads to complete
// their tasks and then shut down the executor and then exit. // their tasks and then shut down the executor and then exit.
if ( !executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS) ) { if (!executor.awaitTermination(SHUTDOWN_TIME, TimeUnit.SECONDS)) {
LOGGER.info("Executor was shut down and Exiting."); LOGGER.info("Executor was shut down and Exiting.");
executor.shutdownNow(); executor.shutdownNow();
} }

View File

@ -24,12 +24,11 @@
package com.iluwatar.queue.load.leveling; package com.iluwatar.queue.load.leveling;
/** /**
* Message class with only one parameter. * Message class with only one parameter.
* */
*/
public class Message { public class Message {
private final String msg; private final String msg;
// Parameter constructor. // Parameter constructor.
public Message(String msg) { public Message(String msg) {
this.msg = msg; this.msg = msg;
@ -39,7 +38,7 @@ public class Message {
public String getMsg() { public String getMsg() {
return msg; return msg;
} }
@Override @Override
public String toString() { public String toString() {
return msg; return msg;

View File

@ -25,30 +25,27 @@ package com.iluwatar.queue.load.leveling;
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue; import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * MessageQueue class. In this class we will create a Blocking Queue and submit/retrieve all the
* MessageQueue class. * messages from it.
* In this class we will create a Blocking Queue and
* submit/retrieve all the messages from it.
*/ */
public class MessageQueue { public class MessageQueue {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
private final BlockingQueue<Message> blkQueue; private final BlockingQueue<Message> blkQueue;
// Default constructor when called creates Blocking Queue object. // Default constructor when called creates Blocking Queue object.
public MessageQueue() { public MessageQueue() {
this.blkQueue = new ArrayBlockingQueue<Message>(1024); this.blkQueue = new ArrayBlockingQueue<Message>(1024);
} }
/** /**
* All the TaskGenerator threads will call this method to insert the * All the TaskGenerator threads will call this method to insert the Messages in to the Blocking
* Messages in to the Blocking Queue. * Queue.
*/ */
public void submitMsg(Message msg) { public void submitMsg(Message msg) {
try { try {
@ -59,11 +56,10 @@ public class MessageQueue {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }
} }
/** /**
* All the messages will be retrieved by the ServiceExecutor by * All the messages will be retrieved by the ServiceExecutor by calling this method and process
* calling this method and process them. * them. Retrieves and removes the head of this queue, or returns null if this queue is empty.
* Retrieves and removes the head of this queue, or returns null if this queue is empty.
*/ */
public Message retrieveMsg() { public Message retrieveMsg() {
Message retrievedMsg = null; Message retrievedMsg = null;
@ -72,7 +68,7 @@ public class MessageQueue {
} catch (Exception e) { } catch (Exception e) {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }
return retrievedMsg; return retrievedMsg;
} }
} }

View File

@ -27,10 +27,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* * ServiceExecuotr class. This class will pick up Messages one by one from the Blocking Queue and
* ServiceExecuotr class. * process them.
* This class will pick up Messages one by one from
* the Blocking Queue and process them.
*/ */
public class ServiceExecutor implements Runnable { public class ServiceExecutor implements Runnable {

View File

@ -22,10 +22,10 @@
*/ */
package com.iluwatar.queue.load.leveling; package com.iluwatar.queue.load.leveling;
/** /**
* Task Interface. * Task Interface.
* */
*/
public interface Task { public interface Task {
void submit(Message msg); void submit(Message msg);
} }

View File

@ -27,28 +27,26 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** /**
* TaskGenerator class. * TaskGenerator class. Each TaskGenerator thread will be a Worker which submit's messages to the
* Each TaskGenerator thread will be a Worker which submit's messages to the queue. * queue. We need to mention the message count for each of the TaskGenerator threads.
* We need to mention the message count for each of the TaskGenerator threads. */
*
*/
public class TaskGenerator implements Task, Runnable { public class TaskGenerator implements Task, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class); private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
// MessageQueue reference using which we will submit our messages. // MessageQueue reference using which we will submit our messages.
private final MessageQueue msgQueue; private final MessageQueue msgQueue;
// Total message count that a TaskGenerator will submit. // Total message count that a TaskGenerator will submit.
private final int msgCount; private final int msgCount;
// Parameterized constructor. // Parameterized constructor.
public TaskGenerator(MessageQueue msgQueue, int msgCount) { public TaskGenerator(MessageQueue msgQueue, int msgCount) {
this.msgQueue = msgQueue; this.msgQueue = msgQueue;
this.msgCount = msgCount; this.msgCount = msgCount;
} }
/** /**
* Submit messages to the Blocking Queue. * Submit messages to the Blocking Queue.
*/ */
@ -59,25 +57,25 @@ public class TaskGenerator implements Task, Runnable {
LOGGER.error(e.getMessage()); LOGGER.error(e.getMessage());
} }
} }
/** /**
* Each TaskGenerator thread will submit all the messages to the Queue. * Each TaskGenerator thread will submit all the messages to the Queue. After every message
* After every message submission TaskGenerator thread will sleep for 1 second. * submission TaskGenerator thread will sleep for 1 second.
*/ */
public void run() { public void run() {
int count = this.msgCount; int count = this.msgCount;
try { try {
while (count > 0) { while (count > 0) {
String statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName(); String statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName();
this.submit(new Message(statusMsg)); this.submit(new Message(statusMsg));
LOGGER.info(statusMsg); LOGGER.info(statusMsg);
// reduce the message count. // reduce the message count.
count--; count--;
// Make the current thread to sleep after every Message submission. // Make the current thread to sleep after every Message submission.
Thread.sleep(1000); Thread.sleep(1000);
} }