提交 6ef840f3 编写于 作者: A Anurag Agarwal 提交者: Ilkka Seppälä

Resolves checkstyle errors for naked-objects null-object object-mother...

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
上级 1e76d919
......@@ -31,7 +31,8 @@ import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.annotation.SemanticsOf;
/**
* HomePage Domain Service
* HomePage Domain Service.
*
* @see HomePageViewModel linked view to HomePage
*/
@DomainService(nature = NatureOfService.VIEW_CONTRIBUTIONS_ONLY)
......
......@@ -23,16 +23,14 @@
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.SimpleObjects;
import java.util.List;
import org.apache.isis.applib.annotation.ViewModel;
/**
* Model linked to the HomePage
* The underlying layout is specified by json
* Model linked to the HomePage The underlying layout is specified by json.
*
* @see HomePageService - Service Linked to the HomePage
*/
@ViewModel
......
......@@ -15,29 +15,29 @@
* limitations under the License.
*/
{
"columns": [
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 12,
"collections": {
"objects": {
"collectionLayout": {
"render": "EAGERLY"
}
}
}
"columns": [
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 12,
"collections": {
"objects": {
"collectionLayout": {
"render": "EAGERLY"
}
}
],
"actions": {}
}
}
],
"actions": {}
}
\ No newline at end of file
......@@ -26,7 +26,6 @@ package domainapp.dom.modules.simple;
import javax.jdo.JDOHelper;
import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.VersionStrategy;
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.Identifier;
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;
/**
* Definition of a Simple Object
* Definition of a Simple Object.
*/
@javax.jdo.annotations.PersistenceCapable(identityType = IdentityType.DATASTORE, schema = "simple",
table = "SimpleObject")
......@@ -87,11 +86,11 @@ public class SimpleObject implements Comparable<SimpleObject> {
// 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 UpdateNameDomainEvent(final SimpleObject source, final Identifier identifier,
final Object... arguments) {
final Object... arguments) {
super(source, identifier, arguments);
}
}
......
......@@ -15,42 +15,42 @@
* limitations under the License.
*/
{
"columns": [
{
"span": 6,
"memberGroups": {
"General": {
"members": {
"name": {
"actions": {
"updateName": {
"actionLayout": {
"position": "BOTTOM"
}
}
}
},
"versionSequence": {
"propertyLayout": {
"name": "version"
}
}
}
"columns": [
{
"span": 6,
"memberGroups": {
"General": {
"members": {
"name": {
"actions": {
"updateName": {
"actionLayout": {
"position": "BOTTOM"
}
}
}
},
"versionSequence": {
"propertyLayout": {
"name": "version"
}
}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 6,
"collections": {}
}
}
],
"actions": {}
}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 0,
"memberGroups": {}
},
{
"span": 6,
"collections": {}
}
],
"actions": {}
}
\ No newline at end of file
......@@ -24,7 +24,6 @@
package domainapp.dom.modules.simple;
import java.util.List;
import org.apache.isis.applib.DomainObjectContainer;
import org.apache.isis.applib.Identifier;
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;
/**
* Domain Service for Simple Objects
* Domain Service for Simple Objects.
*/
@DomainService(repositoryFor = SimpleObject.class)
@DomainServiceLayout(menuOrder = "10")
......@@ -82,18 +81,18 @@ public class SimpleObjects {
// endregion
/**
* Create Domain Event on SimpleObjects
* Create Domain Event on SimpleObjects.
*/
// region > create (action)
public static class CreateDomainEvent extends ActionDomainEvent<SimpleObjects> {
public CreateDomainEvent(final SimpleObjects source, final Identifier identifier,
final Object... arguments) {
final Object... arguments) {
super(source, identifier, arguments);
}
}
/**
* Create simple object
* Create simple object.
*/
@Action(domainEvent = CreateDomainEvent.class)
@MemberOrder(sequence = "3")
......
......@@ -23,14 +23,13 @@
package domainapp.fixture;
import domainapp.fixture.scenarios.RecreateSimpleObjects;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.fixturescripts.FixtureScripts;
import org.apache.isis.applib.services.fixturespec.FixtureScriptsSpecification;
import org.apache.isis.applib.services.fixturespec.FixtureScriptsSpecificationProvider;
import domainapp.fixture.scenarios.RecreateSimpleObjects;
/**
* Specifies where to find fixtures, and other settings.
*/
......
......@@ -23,13 +23,12 @@
package domainapp.fixture.modules.simple;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import domainapp.dom.modules.simple.SimpleObject;
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 {
......@@ -46,7 +45,7 @@ public class SimpleObjectCreate extends FixtureScript {
private String name;
/**
* Name of the object (required)
* Name of the object (required).
*/
public String getName() {
return name;
......
......@@ -27,7 +27,7 @@ import org.apache.isis.applib.fixturescripts.FixtureScript;
import org.apache.isis.applib.services.jdosupport.IsisJdoSupport;
/**
* TearDown/Cleanup for SimpleObjects
* TearDown/Cleanup for SimpleObjects.
*/
public class SimpleObjectsTearDown extends FixtureScript {
......
......@@ -27,19 +27,18 @@ import com.google.common.collect.Lists;
import domainapp.dom.modules.simple.SimpleObject;
import domainapp.fixture.modules.simple.SimpleObjectCreate;
import domainapp.fixture.modules.simple.SimpleObjectsTearDown;
import org.apache.isis.applib.fixturescripts.FixtureScript;
import java.util.Collections;
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 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)
private Integer number;
......
......@@ -23,13 +23,6 @@
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.io.Resources;
import com.google.inject.AbstractModule;
......@@ -37,30 +30,31 @@ import com.google.inject.Module;
import com.google.inject.name.Names;
import com.google.inject.util.Modules;
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.request.IRequestParameters;
import org.apache.wicket.request.Request;
import org.apache.wicket.request.Response;
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.LoggerFactory;
/**
* As specified in <tt>web.xml</tt>.
*
* <p>
* See:
*
*
* <p>See:
*
* <pre>
* &lt;filter&gt;
* &lt;filter-name&gt;wicket&lt;/filter-name&gt;
......@@ -71,7 +65,6 @@ import org.slf4j.LoggerFactory;
* &lt;/init-param&gt;
* &lt;/filter&gt;
* </pre>
*
*/
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:
*
*
* <tt>{@code ?user=sven&pass=pass}</tt>
*
* <p>
* for demos only, obvious.
*
* <p>for demos only, obvious.
*/
private static final boolean DEMO_MODE_USING_CREDENTIALS_AS_QUERYARGS = false;
......
......@@ -24,18 +24,16 @@
package com.iluwatar.nullobject;
/**
*
* Null Object pattern replaces null values with neutral objects. Many times this simplifies
* 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 {
/**
* Program entry point
*
* Program entry point.
*
* @param args command line 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(),
NullNode.getInstance()), NullNode.getInstance()), new NodeImpl("12",
NullNode.getInstance(), new NodeImpl("122", NullNode.getInstance(),
NullNode.getInstance())));
NullNode.getInstance())));
root.walk();
}
......
......@@ -24,9 +24,7 @@
package com.iluwatar.nullobject;
/**
*
* Interface for binary tree node.
*
*/
public interface Node {
......
......@@ -27,9 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Implementation for binary tree's normal nodes.
*
*/
public class NodeImpl implements Node {
......@@ -40,7 +38,7 @@ public class NodeImpl implements Node {
private final Node right;
/**
* Constructor
* Constructor.
*/
public NodeImpl(String name, Node left, Node right) {
this.name = name;
......
......@@ -24,17 +24,16 @@
package com.iluwatar.nullobject;
/**
*
* 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 {
private static NullNode instance = new NullNode();
private NullNode() {}
private NullNode() {
}
public static NullNode getInstance() {
return instance;
......
......@@ -24,7 +24,7 @@
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 {
boolean isDrunk = false;
......@@ -56,6 +56,7 @@ public class King implements Royalty {
/**
* Method to flirt to a queen.
*
* @param queen Queen which should be flirted.
*/
public void flirt(Queen queen) {
......
......@@ -24,7 +24,7 @@
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 {
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.
*
* @param king King who initialized the flirt.
* @return A value which describes if the flirt was successful or not.
*/
......
......@@ -24,7 +24,7 @@
package com.iluwatar.objectmother;
/**
* Interface contracting Royalty Behaviour
* Interface contracting Royalty Behaviour.
*/
public interface Royalty {
void makeDrunk();
......
......@@ -24,12 +24,13 @@
package com.iluwatar.objectmother;
/**
* Object Mother Pattern generating Royalty Types
* Object Mother Pattern generating Royalty Types.
*/
public final class RoyaltyObjectMother {
/**
* 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.
*/
public static King createSoberUnhappyKing() {
......@@ -38,6 +39,7 @@ public final class RoyaltyObjectMother {
/**
* Method of the object mother to create a drunk king.
*
* @return A drunk {@link com.iluwatar.objectmother.King}.
*/
public static King createDrunkKing() {
......@@ -48,6 +50,7 @@ public final class RoyaltyObjectMother {
/**
* Method to create a happy king.
*
* @return A happy {@link com.iluwatar.objectmother.King}.
*/
public static King createHappyKing() {
......@@ -58,6 +61,7 @@ public final class RoyaltyObjectMother {
/**
* Method to create a happy and drunk king.
*
* @return A drunk and happy {@link com.iluwatar.objectmother.King}.
*/
public static King createHappyDrunkKing() {
......@@ -69,6 +73,7 @@ public final class RoyaltyObjectMother {
/**
* Method to create a flirty queen.
*
* @return A flirty {@link com.iluwatar.objectmother.Queen}.
*/
public static Queen createFlirtyQueen() {
......@@ -79,6 +84,7 @@ public final class RoyaltyObjectMother {
/**
* Method to create a not flirty queen.
*
* @return A not flirty {@link com.iluwatar.objectmother.Queen}.
*/
public static Queen createNotFlirtyQueen() {
......
......@@ -27,32 +27,30 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* 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
* entire application may be adversely affected. An object pool design pattern may be deemed
* 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
* needed, it is requested from the pool. If a previously prepared object is available it is
*
* <p>The object pool design pattern creates a set of objects that may be reused. When a new object
* 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
* 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
* computationally expensive instantiation process. It is important to note that once an object has
* 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 {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point
*
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
......
......@@ -27,7 +27,8 @@ import java.util.HashSet;
import java.util.Set;
/**
* Generic object pool
* Generic object pool.
*
* @param <T> Type T of Object in the Pool
*/
public abstract class ObjectPool<T> {
......@@ -38,7 +39,7 @@ public abstract class ObjectPool<T> {
protected abstract T create();
/**
* Checkout object from pool
* Checkout object from pool.
*/
public synchronized T checkOut() {
if (available.isEmpty()) {
......
......@@ -26,9 +26,7 @@ package com.iluwatar.object.pool;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* Oliphaunts are expensive to create
*
* Oliphaunts are expensive to create.
*/
public class Oliphaunt {
......@@ -37,7 +35,7 @@ public class Oliphaunt {
private final int id;
/**
* Constructor
* Constructor.
*/
public Oliphaunt() {
id = counter.incrementAndGet();
......
......@@ -24,9 +24,7 @@
package com.iluwatar.object.pool;
/**
*
* Oliphaunt object pool
*
* Oliphaunt object pool.
*/
public class OliphauntPool extends ObjectPool<Oliphaunt> {
......
......@@ -30,25 +30,23 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* 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
* 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
* model–view–controller (MVC) architectural pattern. The Observer pattern is implemented in
* 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
* {@link Hobbits} register as observers and receive notifications when the {@link Weather} changes.
*
*
* <p>In this example {@link Weather} has a state that can be observed. The {@link Orcs} and {@link
* Hobbits} register as observers and receive notifications when the {@link Weather} changes.
*/
public class App {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
/**
* Program entry point
*
* Program entry point.
*
* @param args command line 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
LOGGER.info("--Running generic version--");
GWeather gWeather = new GWeather();
gWeather.addObserver(new GOrcs());
gWeather.addObserver(new GHobbits());
GWeather genericWeather = new GWeather();
genericWeather.addObserver(new GOrcs());
genericWeather.addObserver(new GHobbits());
gWeather.timePasses();
gWeather.timePasses();
gWeather.timePasses();
gWeather.timePasses();
genericWeather.timePasses();
genericWeather.timePasses();
genericWeather.timePasses();
genericWeather.timePasses();
}
}
......@@ -27,9 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Hobbits
*
* Hobbits.
*/
public class Hobbits implements WeatherObserver {
......
......@@ -27,9 +27,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Orcs
*
* Orcs.
*/
public class Orcs implements WeatherObserver {
......
......@@ -23,17 +23,14 @@
package com.iluwatar.observer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Weather can be observed by implementing {@link WeatherObserver} interface and registering as
* listener.
*
*/
public class Weather {
......@@ -56,7 +53,7 @@ public class Weather {
}
/**
* Makes time pass for weather
* Makes time pass for weather.
*/
public void timePasses() {
WeatherType[] enumValues = WeatherType.values();
......
......@@ -24,9 +24,7 @@
package com.iluwatar.observer;
/**
*
* Observer interface.
*
*/
public interface WeatherObserver {
......
......@@ -24,9 +24,7 @@
package com.iluwatar.observer;
/**
*
* WeatherType enumeration
*
* WeatherType enumeration.
*/
public enum WeatherType {
......
......@@ -28,9 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* GHobbits
*
* GHobbits.
*/
public class GHobbits implements Race {
......
......@@ -28,9 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* GOrcs
*
* GOrcs.
*/
public class GOrcs implements Race {
......
......@@ -28,9 +28,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* GWeather
*
* GWeather.
*/
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() {
WeatherType[] enumValues = WeatherType.values();
......
......@@ -27,7 +27,7 @@ import java.util.List;
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 <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")
public void notifyObservers(A argument) {
......
......@@ -24,7 +24,8 @@
package com.iluwatar.observer.generic;
/**
* Observer
* Observer.
*
* @param <S> Observable
* @param <O> Observer
* @param <A> Action
......
......@@ -26,9 +26,7 @@ package com.iluwatar.observer.generic;
import com.iluwatar.observer.WeatherType;
/**
*
* Race
*
* Race.
*/
public interface Race extends Observer<GWeather, Race, WeatherType> {
}
......@@ -26,69 +26,69 @@ package com.iluwatar.queue.load.leveling;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* Many solutions in the cloud involve running tasks that invoke services. In this environment,
* if a service is subjected to intermittent heavy loads, it can cause performance or reliability issues.
* <p>
* A service could be a component that is part of the same solution as the tasks that utilize it, or it
* could be a third-party service providing access to frequently used resources such as a cache or a storage service.
* If the same service is utilized by a number of tasks running concurrently, it can be difficult to predict the
* volume of requests to which the service might be subjected at any given point in time.
* <p>
* 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.
* The task and the service run asynchronously. The task posts a message containing the data required
* by the service to a queue. The queue acts as a buffer, storing the message until it is retrieved
* by the service. The service retrieves the messages from the queue and processes them.
* Requests from a number of tasks, which can be generated at a highly variable rate, can be passed
* to the service through the same message queue.
* <p>
* 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,
* there is no delay to a task if the service is not available at the time it posts a message to the queue.
* <p>
* In this example we have a class {@link MessageQueue} to hold the message {@link Message} 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.
*
* Many solutions in the cloud involve running tasks that invoke services. In this environment, if a
* service is subjected to intermittent heavy loads, it can cause performance or reliability
* issues.
*
* <p>A service could be a component that is part of the same solution as the tasks that utilize
* it, or it could be a third-party service providing access to frequently used resources such as a
* cache or a storage service. If the same service is utilized by a number of tasks running
* concurrently, it can be difficult to predict the volume of requests to which the service might be
* subjected at any given point in time.
*
* <p>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. The task and the service run asynchronously.
* The task posts a message containing the data required by the service to a queue. The queue acts
* as a buffer, storing the message until it is retrieved by the service. The service retrieves the
* messages from the queue and processes them. Requests from a number of tasks, which can be
* generated at a highly variable rate, can be passed to the service through the same message
* queue.
*
* <p>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, there is no delay to a task if the service is not available at the time it posts a
* message to the queue.
*
* <p>In this example we have a class {@link MessageQueue} to hold the message {@link Message}
* 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 {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
//Executor shut down time limit.
private static final int SHUTDOWN_TIME = 15;
/**
* Program entry point
*
* Program entry point.
*
* @param args command line args
*/
public static void main(String[] args) {
// An Executor that provides methods to manage termination and methods that can
// produce a Future for tracking progress of one or more asynchronous tasks.
ExecutorService executor = null;
try {
// Create a MessageQueue object.
MessageQueue msgQueue = new MessageQueue();
LOGGER.info("Submitting TaskGenerators and ServiceExecutor threads.");
// Create three TaskGenerator threads. Each of them will submit different number of jobs.
Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5);
Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1);
Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2);
final Runnable taskRunnable1 = new TaskGenerator(msgQueue, 5);
final Runnable taskRunnable2 = new TaskGenerator(msgQueue, 1);
final Runnable taskRunnable3 = new TaskGenerator(msgQueue, 2);
// 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
// submit all Runnable task for execution to executor..
......@@ -96,17 +96,18 @@ public class App {
executor.submit(taskRunnable1);
executor.submit(taskRunnable2);
executor.submit(taskRunnable3);
// submitting serviceExecutor thread to the Executor service.
executor.submit(srvRunnable);
// 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();
// Wait for SHUTDOWN_TIME seconds for all the threads to complete
// 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.");
executor.shutdownNow();
}
......
......@@ -24,12 +24,11 @@
package com.iluwatar.queue.load.leveling;
/**
* Message class with only one parameter.
*
*/
* Message class with only one parameter.
*/
public class Message {
private final String msg;
// Parameter constructor.
public Message(String msg) {
this.msg = msg;
......@@ -39,7 +38,7 @@ public class Message {
public String getMsg() {
return msg;
}
@Override
public String toString() {
return msg;
......
......@@ -25,30 +25,27 @@ package com.iluwatar.queue.load.leveling;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* MessageQueue class.
* In this class we will create a Blocking Queue and
* submit/retrieve all the messages from it.
* MessageQueue class. In this class we will create a Blocking Queue and submit/retrieve all the
* messages from it.
*/
public class MessageQueue {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
private final BlockingQueue<Message> blkQueue;
// Default constructor when called creates Blocking Queue object.
public MessageQueue() {
this.blkQueue = new ArrayBlockingQueue<Message>(1024);
}
/**
* All the TaskGenerator threads will call this method to insert the
* Messages in to the Blocking Queue.
* All the TaskGenerator threads will call this method to insert the Messages in to the Blocking
* Queue.
*/
public void submitMsg(Message msg) {
try {
......@@ -59,11 +56,10 @@ public class MessageQueue {
LOGGER.error(e.getMessage());
}
}
/**
* All the messages will be retrieved by the ServiceExecutor by
* calling this method and process them.
* Retrieves and removes the head of this queue, or returns null if this queue is empty.
* All the messages will be retrieved by the ServiceExecutor by calling this method and process
* them. Retrieves and removes the head of this queue, or returns null if this queue is empty.
*/
public Message retrieveMsg() {
Message retrievedMsg = null;
......@@ -72,7 +68,7 @@ public class MessageQueue {
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return retrievedMsg;
}
}
\ No newline at end of file
......@@ -27,10 +27,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* ServiceExecuotr class.
* This class will pick up Messages one by one from
* the Blocking Queue and process them.
* ServiceExecuotr class. This class will pick up Messages one by one from the Blocking Queue and
* process them.
*/
public class ServiceExecutor implements Runnable {
......
......@@ -22,10 +22,10 @@
*/
package com.iluwatar.queue.load.leveling;
/**
* Task Interface.
*
*/
*/
public interface Task {
void submit(Message msg);
}
......@@ -27,28 +27,26 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* TaskGenerator class.
* Each TaskGenerator thread will be a Worker which submit's messages to the queue.
* We need to mention the message count for each of the TaskGenerator threads.
*
*/
* TaskGenerator class. Each TaskGenerator thread will be a Worker which submit's messages to the
* queue. We need to mention the message count for each of the TaskGenerator threads.
*/
public class TaskGenerator implements Task, Runnable {
private static final Logger LOGGER = LoggerFactory.getLogger(App.class);
// MessageQueue reference using which we will submit our messages.
private final MessageQueue msgQueue;
// Total message count that a TaskGenerator will submit.
private final int msgCount;
// Parameterized constructor.
public TaskGenerator(MessageQueue msgQueue, int msgCount) {
this.msgQueue = msgQueue;
this.msgCount = msgCount;
}
/**
* Submit messages to the Blocking Queue.
*/
......@@ -59,25 +57,25 @@ public class TaskGenerator implements Task, Runnable {
LOGGER.error(e.getMessage());
}
}
/**
* Each TaskGenerator thread will submit all the messages to the Queue.
* After every message submission TaskGenerator thread will sleep for 1 second.
* Each TaskGenerator thread will submit all the messages to the Queue. After every message
* submission TaskGenerator thread will sleep for 1 second.
*/
public void run() {
int count = this.msgCount;
try {
while (count > 0) {
String statusMsg = "Message-" + count + " submitted by " + Thread.currentThread().getName();
this.submit(new Message(statusMsg));
LOGGER.info(statusMsg);
// reduce the message count.
count--;
// Make the current thread to sleep after every Message submission.
Thread.sleep(1000);
}
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册