Should instance fields access be synchronized in a Tapestry page or component? - concurrency

If a page or component class has one instance field which is a non-synchronized object, f.ex. an ArrayList, and the application has code that structurally modifies this field, should the access to this field be synchronized ?
F.ex.:
public class MyPageOrComponent
{
#Persist
private List<String> myList;
void setupRender()
{
if (this.myList == null)
{
this.myList = new ArrayList<>();
}
}
void afterRender(MarkupWriter writer)
{
// Should this be synchronized ?
if (someCondition)
{
this.myList.add(something);
}
else
{
this.myList.remove(something);
}
}
}
I'm asking because I seem to understand that Tapestry creates only one instance of a page or component class and it uses this instance for all the connected clients (but please correct me if this is not true).

In short the answer is no, you don't have to because Tapestry does this for you. Tapestry will transform your pages and classes for you at runtime in such a way that wherever you interact with your fields, they will not actually be working on the instance variable but on a managed variable that is thread safe. The full inner workings are beyond me, but a brief reference to the transformation can be found here.
One warning, don't instantiate your page/component variables at decleration. I have seen some strange behaviour around this. So don't do this:
private List<String> myList = new ArrayList<String>;

Tapestry uses some runtime byte code magic to transform your pages and components. Pages and components are singletons but the properties are transformed so that they are backed by a PerThreadValue. This means that each request gets it's own copy of the value so no synchronization is required.
As suggested by #joostschouten you should never initialize a mutable property in the field declaration. The strange behaviour he discusses is caused beacause this will be shared by all requests (since the initializer is only fired once for the page/component singleton). Mutable fields should instead be initialized in a render method (eg #SetupRender)

Related

OOP for global system/task monitoring class

I'm trying to create a performance monitor of sorts to run on a Particle board (STM32 based). I'm used to programming in c so the OOP approach is a bit new but I think it would fit well here.
For the purpose of this question let's assume I have two types of monitors:
Frequency. The application can call a "tick" method of the monitor to calculate the time since it last ran and store it.
Period- call a "start" and "stop" method of the monitor to calculate how long a process takes to run and store it.
What I would like to do is to create instances of these monitors throughout my application and be able to report on the stats of all monitors of all types from the main module.
I've read about the singleton design pattern which seems like it might be what I need but I'm not sure and I'm also concerned about thread safety with that.
I'm thinking I will create a "StatMonitor" class and a derived class "FrequencyMonitor" and "PeriodMonitor". Monitor would be a singleton and everywhere I wanted to create a new monitor I would request an instance of "Monitor" and use that like so:
freqMonitor * task1FreqMonitor = StatMonitor::GetInstance()->Add_Freq_Monitor("Task1");
The StatMonitor would track all monitors I've added and when I wanted to print the stats I could just call the printAll method which would iterate it's array of monitors and request their results like so:
StatMonitor::GetInstance()->PrintAllStats();
Am I going down the right path?
Your path sounds good, except that FrequencyMonitor and PeriodMonitor should not derive from the class that "manages" all these monitors (let's call it MonitorPrinter).
MonitorPrinter should be a singleton and could look like this:
class MonitorPrinter
{
public:
static MonitorPrinter& getInstance()
{
static MonitorPrinter monitorPrinter;
return monitorPrinter;
}
void printAllStats()
{
for (const auto& [_, frequencyMonitor] : _frequencyMonitors)
frequencyMonitor.print();
for (const auto& [_, periodMonitor] : _periodMonitors)
periodMonitor.print();
}
FrequencyMonitor& getFrequencyMonitor(std::string name)
{ return _frequencyMonitors[name]; }
PeriodMonitor& getPeriodMonitor(std::string name)
{ return _periodMonitors[name]; }
private:
MonitorPrinter() = default;
std::map<std::string, FrequencyMonitor> _frequencyMonitors;
std::map<std::string, PeriodMonitor> _periodMonitors;
};
Demo
(The const auto& [_, frequencyMonitor] is a structured binding).
FrequencyMonitor and PeriodMonitor should not have anything to do with singletons, and from your description, they need not be part of a class hierarchy either (as they have different interfaces). If you want, you can prevent users (other than the MonitorPrinter) from instantiating these classes using other techniques, but I won't elaborate on that here.
In short, there is no need to use OOP here. Use a singleton to provide (and keep track of) the monitors, and implement the monitors to your liking. Be wary of thread safety if this is relevant (the above is not thread-safe!).

D8 - I need to use many services on my block, is this code right?

Developing a Drupal 8 example site, I have declared block in a module, and I want to do a few things with this block, like check the route and show this block only on nodes, also check if the user has permissions to see this block, and the content of the block is a form which I had defined in another place of the module.
I don't want to get the classes/services that I need in a static way, I want to use dependency injection to get those classes because it is technically better to decouple code and allow better testing.
Now "create" method and the "constructor" method on the block are like so:
<?php
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('current_user'),
$container->get('form_builder'),
$container->get('current_route_match'),
$container->get('access_check.permission')
);
}
public function __construct(
array $configuration, $plugin_id,
$plugin_definition,
AccountProxyInterface $user,
FormBuilderInterface $formBuilder,
ResettableStackedRouteMatchInterface $route,
AccessInterface $access
) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->user = $user;
$this->formBuilder = $formBuilder;
$this->route = $route;
$this->access = $access;
}
Is this the correct way to do this? Maybe I'm doing too much in the block file? Should I create a service to move the logic to another place? Probably I would need more things, which means using more services, and my "create" and "constructor" methods are growing in parameters. Is this the correct way to do it? Thanks.
When you have to inject many services in one class, be it a controller or a block, it usually tells that the class is not well designed because you are (probably) trying lots of things in just one class.
However, I've seen many controllers which inject multiple services in their constructors, so it doesn't seem an unusual practice anyway. "Every rule has an exception".
In the end, I think it is a matter of balance, build a class that is responsible for doing one logical thing, and its dependencies in the same way.

How are aggregates instantiated to test other aggregates with?

Suppose I have an aggregate that, for some operation, requires the existence of another aggregate. Let's assume I have a car and a garage. There might be a command called ParkInGarage that looks like this:
public class ParkInGarage {
#TargetAggregateIdentifier
public final UUID carId;
public final Garage garage;
//... constructor omitted
}
I've read that to validate the existence of an aggregate, it is good practice to use the loaded aggregate in commands since that already implies its existence (as opposed to passing a garageId).
Now when unit-testing the Car using Axon's fixtures, I can not simply instantiate my Garage by saying new Garage(buildGarageCmd). It will say:
java.lang.IllegalStateException: Cannot request current Scope if none is active
Because no infrastructure was set up.
How would I test such a case, or should I design the aggregate differently?
Abstracted, real-world example
The aggregate root I am working with may have a reference to itself to form a tree-structure of said aggregate root. Let's call it Node.
#Aggregate
public class Node {
private Node parentNode;
}
Upon creation, I can pass an Optional<Node> as parent, or set the parent at a later time using a separate command. Whether the parent should be defined as instance or by ID is part of the question.
public class AttachNodeCmd {
#TargetAggregateIdentifier
public final UUID nodeId;
public final Optional<Node> parentNode;
}
In the command handler, I need to check if attaching the node to given parent would introduce a cycle (the structure is supposed to be a tree, not a common graph).
#CommandHandler
public Node(AttachNodeCmd command) {
if (command.parentNode.isPresent()) {
Node currentNode = command.parentNode.get();
while (currentNode != null) {
if (currentNode.equals(this)) throw new RecursionException();
currentNode = currentNode.parentNode.orElse(null);
}
}
//Accept the command by applying() an Event
}
At some point, the parent needs to be instantiated to perform those checks. This could either be done by supplying the aggregate instance in the command (discouraged), or by supplying a Repository<Node> and the nodeId to the command handler, which is the aggregate itself and also discouraged. Currently I don't see a right way to do this and further down the road a way to test it.
I wouldn't put AR instances in commands. Command schemas should be stable and easy to serialize/reserialize as they are message contracts.
What you could do instead is resolving the dependency in the command handler.
//ParkInGarage command handler
Garage garage = garageRepository.garageOfId(command.garageId);
Car car = carRepository.carOfId(command.carId);
car.parkIn(garage);
I don't know Axon Framework at all, but that should be relatively easy to test now.
I think #plalx is putting you on the right track. Commands are part of your API/Message Contract and exposing the Aggregate in there isn't that great an idea.
Additionally I'd like to note that the AggregateFixtures in Axon are there to test a single Aggregate, not the coordination of operations between Aggregates.
Coordination between aggregates/bounded contexts is typically where you see sagas coming in to play. Now to be honest, I am a bit in doubt whether this use case justifies a Saga, but I could imagine that if the ParkCarInGarageCommand fails because the Garage Aggregate is full (for example), that you need to instruct the Car Aggregate through another command telling it it's a no-go. The Saga set up in Axon might help you with this as you can easily catch (1) the exception from handling the command or (2) handle the event notifying the operation wasn't successful.

Sitecore: Glass Mapper Code First

It is possible to automatically generate Sitecore templates just coding models? I'm using Sitecore 8.0 and I saw Glass Mapper Code First approach but I cant find more information about that.
Not sure why there isn't much info about it, but you can definitely model/code first!. I do it alot using the attribute configuration approach like so:
[SitecoreType(true, "{generated guid}")]
public class ExampleModel
{
[SitecoreField("{generated guid}", SitecoreFieldType.SingleLineText)]
public virtual string Title { get; set; }
}
Now how this works. The SitecoreType 'true' value for the first parameter indicates it may be used for codefirst. There is a GlassCodeFirstDataprovider which has an Initialize method, executed in Sitecore's Initialize pipeline. This method will collect all configurations marked for codefirst and create it in the sql dataprovider. The sections and fields are stored in memory. It also takes inheritance into account (base templates).
I think you first need to uncomment some code in the GlassMapperScCustom class you get when you install the project via Nuget. The PostLoad method contains the few lines that execute the Initialize method of each CodeFirstDataprovider.
var dbs = global::Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
Furthermore I would advise to use code first on development only. You can create packages or serialize the templates as usual and deploy them to other environment so you dont need the dataprovider (and potential risks) there.
You can. But it's not going to be Glass related.
Code first is exactly what Sitecore.PathFinder is looking to achieve. There's not a lot of info publicly available on this yet however.
Get started here: https://github.com/JakobChristensen/Sitecore.Pathfinder

c# programmer tries for events in c++

Hi all: I'm an experienced c# programmer trying to do some work in c++, and I'm not sure about the right way to do this:
I am authoring a class that needs to notify a consuming class that something has happened.
If I were writing this in c#, I would define an event on my class.
No events in c++, so I am trying to figure out what is the correct way to do this. I have thought about callback functions, but how do I handle a case where I want to execute a member function (not a static function).
More specifically, what I really need to do is to handle the event, but have access to member state within the object instance that is handling the event.
I have been looking at std::tr1:function, but I am having trouble getting it to work.
I don't suppose that anyone would want to translate the following example c# example into an example of the correct/best practice c++ (I need ANSI c++)?
(please bear in mind that I have almost no c++ experience -- don't assume that I know any long-established c++ conventions -- I don't ;);
A simple c# console app (works on my machine):
using System;
namespace ConsoleApplication1
{
public class EventSource
{
public event EventHandler<EchoEventArgs> EchoEvent;
public void RaiseEvent(int echoId)
{
var echoEvent = this.EchoEvent;
if (echoEvent != null)
echoEvent(this, new EchoEventArgs() {EchoId = echoId});
}
}
public class EchoEventArgs : EventArgs
{
public int EchoId { get; set; }
}
public class EventConsumer
{
public int Id { get; set; }
public EventConsumer(EventSource source)
{
source.EchoEvent += OnEcho;
}
private void OnEcho(object sender, EchoEventArgs args)
{
// handle the echo, and use this.Id to prove that the correct instance data is present.
Console.WriteLine("Echo! My Id: {0} Echo Id: {1}", this.Id, args.EchoId);
}
}
internal class Program
{
private static void Main(string[] args)
{
var source = new EventSource();
var consumer1 = new EventConsumer(source) { Id = 1 };
var consumer2 = new EventConsumer(source) { Id = 2 };
source.RaiseEvent(1);
Console.ReadLine();
}
}
}
The basic idea is to take function objects, e.g., something like std::function<Signature> as the callbacks. These aren't function pointers but can be called. The standard C++ library (for C++ 2011) contains a number of class and functions, e.g., std::mem_fn() and std::bind() which allow using functions, including member functions, to be used as function objects.
The part what is missing is something supporting multiple events be registered: std::function<Signature> represents one function. However, it is easy to put them, e.g., into a std::vector<std::function<Signature>>. What becomes more interesting (and requires variadic templates to be done easily) is creating an event class which encapsulates the abstraction of multiple events begin registered, potentially unregistered, and called.
C++ has a concept of functor: a callable object. You need to read about them.
Think about an object that has overwritten operator(). You pass an instance of such an object. After that you can call it like a regular function. And it can maintain a state.
There's also Signals2 library in Boost, which provides an API very close to real C# events, at least in idiomatic sense.
Qt has something that might help you called Signals and Slots: http://qt-project.org/doc/qt-4.8/signalsandslots.html
It lets you specify what the signals (the events that you want to listen to) and the slots (the receiving side) an object has, and then you can connect them. More than one object can listen to a signal like you mention you needed.
Qt is a large app framework, so I'm not sure how to use only the signals & slots part of it. But if you're building an entire GUI application the rest of the Qt might benefit you too (a lot of the ui event stuff is based on signals and slots).