How does initialization on demand holder idiom work with parameters? - java

Here is the link to initialization on demand holder idiom
I've created a class with Singleton design pattern and double locking strategy. I want to change this class to use initialization on demand holder, but I couldn't accross examples where this is parameterized.
How should I pass the parameters basePath1, basePath2 while using initialization on demand holder pattern ?
Would the present code and code with initialization on demand holder pattern cause any concurrency issues ?
public class Api {
private String basePath1;
private String basePath2;
private StringBuilder temporalEndpoint;
private StringBuilder spatialEndpoint;
private StringBuilder fileUploadEndpoint;
private StringBuilder fileDownloadEndpoint;
private StringBuilder fileDeleteEndpoint;
private StringBuilder listMetaDataEndpoint;
private static final Logger LOG = LogManager.getLogger(Api.class);
private static volatile Api apiInstance;
private Api(String basePath1, String basePath2) {
this.basePath1 = basePath1;
this.basePath2 = basePath2;
buildEndpoints();
}
public static Api getInstance(String basePath1, String basePath2)
{
if(apiInstance == null)
{
synchronized(Api.class)
{
if(apiInstance == null)
{
apiInstance = new Api(basePath1, basePath2);
}
}
}
return apiInstance;
}
public void buildEndpoints() {
temporalEndpoint = new StringBuilder(basePath1).append(API_TEMPORAL);
spatialEndpoint = new StringBuilder(basePath1).append(API_SPATIAL);
fileUploadEndpoint = new StringBuilder(basePath1).append(API_FILE_UPLOAD);
fileDownloadEndpoint = new StringBuilder(basePath1).append(API_FILE_DOWNLOAD);
fileDeleteEndpoint = new StringBuilder(basePath2).append(API_FILE_DELETE);
listMetaDataEndpoint = new StringBuilder(basePath2).append(API_LIST_METADATA);
}

Related

A way of accessing Windows MMDevice API from Java?

I would like to use the MMDevice API from my Java app. What are my options?
I tried to use JNA. Looks like I can't use JNA Typelib parsing because there no types for this API (Is there a COM type library for Windows Core Audio). As suggested, I need to provide my own declarations of the API.
So I also tried both JNA examples with manual declarations but they give "Interface not supported HRESULT=80004002" error:
public class MMDeviceAPITest {
public static void test1() {
try {
Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
var obj = new Test1.MMDeviceEnumerator(); // exception E_NOINTERFACE (HRESULT: 80004002)
// ...
} finally {
Ole32.INSTANCE.CoUninitialize();
}
}
public static void test2() {
try {
Ole32.INSTANCE.CoInitializeEx(Pointer.NULL, Ole32.COINIT_MULTITHREADED);
var factory = new Factory();
var obj = factory.createObject(Test2.MMDeviceEnumerator.class); // exception E_NOINTERFACE (HRESULT: 80004002)
var in = obj.queryInterface(Test2.IMMDeviceEnumerator.class);
// ...
} finally {
Ole32.INSTANCE.CoUninitialize();
}
}
}
interface Test1 {
class MMDeviceEnumerator extends COMLateBindingObject {
public MMDeviceEnumerator() {
super(new Guid.CLSID("bcde0395-e52f-467c-8e3d-c4579291692e"), true);
}
}
}
interface Test2 {
#ComObject(clsId = "bcde0395-e52f-467c-8e3d-c4579291692e")
interface MMDeviceEnumerator extends IUnknown {} // doesn't extend IUnknown in C sources, probably it's the problem...
#ComInterface(iid = "a95664d2-9614-4f35-a746-de8db63617e6")
interface IMMDeviceEnumerator extends IUnknown {}
}
Any ideas how I could access this API from Java? Can I somehow create working declarations for JNA? Or use another framework maybe?
My last idea is to create/find a micro native app/library that wraps the needed COM calls, so I could call this app/library easily (via subprocesses or simple JNA declarations). I'm new to COM world, but it sounds working for me...
The docs you linked show how to create using CoCreateInstance:
const CLSID CLSID_MMDeviceEnumerator = __uuidof(MMDeviceEnumerator);
const IID IID_IMMDeviceEnumerator = __uuidof(IMMDeviceEnumerator);
hr = CoCreateInstance(
CLSID_MMDeviceEnumerator, NULL,
CLSCTX_ALL, IID_IMMDeviceEnumerator,
(void**)&pEnumerator);
This should get you somewhere close with JNA.
class MMDeviceEnumerator extends Unknown {
public static final CLSID CLSID_MMDeviceEnumerator = new CLSID("bcde0395-e52f-467c-8e3d-c4579291692e");
public static final GUID IID_IMMDeviceEnumerator = new GUID("a95664d2-9614-4f35-a746-de8db63617e6");
public MMDeviceEnumerator(Pointer p) {
super(p);
}
public static MMDeviceEnumerator create() {
PointerByReference pEnumerator = new PointerByReference();
HRESULT hres = Ole32.INSTANCE.CoCreateInstance(
CLSID_MMDeviceEnumerator, null,
WTypes.CLSCTX_ALL, IID_IMMDeviceEnumerator,
pEnumerator);
if (COMUtils.FAILED(hres)) {
return null;
}
return new MMDeviceEnumerator(pEnumerator.getValue());
}
// map functions as needed
}
I used the implementation of IWbemContext in JNA as a template above. You can consult that class for example COM function mappings.
For some reason I can't suggest edits to the answer of Daniel Widdis. The answer worked for me, many thanks! Just wanted to show how to map one method as an example:
class MMDeviceEnumerator extends Unknown {
public static final CLSID CLSID_MMDeviceEnumerator = new CLSID("bcde0395-e52f-467c-8e3d-c4579291692e");
public static final GUID IID_IMMDeviceEnumerator = new GUID("a95664d2-9614-4f35-a746-de8db63617e6");
public MMDeviceEnumerator(Pointer p) {
super(p);
}
public static MMDeviceEnumerator create() {
PointerByReference pEnumerator = new PointerByReference();
HRESULT hres = Ole32.INSTANCE.CoCreateInstance(
CLSID_MMDeviceEnumerator, null,
WTypes.CLSCTX_ALL, IID_IMMDeviceEnumerator, pEnumerator);
if (COMUtils.FAILED(hres)) {
return null;
}
return new MMDeviceEnumerator(pEnumerator.getValue());
}
public static final int EDataFlow_eRender = 0;
public static final int EDataFlow_eCapture = 1;
public static final int EDataFlow_eAll = 2;
public static final int EDataFlow_enum_count = 3;
public static final int DEVICE_STATE_ACTIVE = 0x1;
public static final int DEVICE_STATE_DISABLED = 0x2;
public static final int DEVICE_STATE_NOTPRESENT = 0x4;
public static final int DEVICE_STATE_UNPLUGGED = 0x8;
public static final int DEVICE_STATEMASK_ALL = 0xF;
public void EnumAudioEndpoints(int dataFlow, int dwStateMask, PointerByReference ppDevices) {
WinNT.HRESULT res = (WinNT.HRESULT) _invokeNativeObject(
3, // `EnumAudioEndpoints` is the 3rd method of `IMMDeviceEnumeratorVtbl` in `mmdeviceapi.h`
new Object[] { getPointer(), dataFlow, new WinDef.DWORD(dwStateMask), ppDevices},
WinNT.HRESULT.class
);
COMUtils.checkRC(res);
}
// map other functions as needed
}

How to fetch data from different sources (device cache, web server and sqlite database) synchronously?

and happy new year!
I am Learning android development using java, and I started by creating my first application using architecture components following this tutorial:
Guide to app architecture
I have a good understanding about android architecture design and the other basic stuff. But, I still have a problem in handling background tasks because there are many classes that provide multi-threading like : Executor, IntentService and asynctask..
My code :
Repository class:
public class MovieRpository {
private IWebService m_webService;
private Movie _movie;
private AppExecuters m_executers;
private MovieRpository(AppExecuters executers, TMDB webService){
this.m_executers = executers;
this.m_webService = webService;
}
private static MovieRpository m_singleInstance;
public static MovieRpository getInstance(){
if(m_singleInstance == null){
m_singleInstance = new
MovieRpository(AppExecuters.getInstance(), new TMDB(new JsonParser<Movie>()));
}
return m_singleInstance;
}
public LiveData<Movie> getMovie( String movieId){
final MutableLiveData<Movie> _liveDataMovie = new MutableLiveData<Movie>();
m_executers.networkIO().execute(()->{
_movie =(Movie)m_webService.getObject(movieId);});
_liveDataMovie.setValue(_movie);
return _liveDataMovie;
}
}
My problem :
In Repository class when i use debugger inside the second thread which is created by m_executers.networkIO() _movie has a value inside the network thread. but, it is always null outside execute method.
The rest of my code:
-IWebService interface
public interface IWebService<T> {
public T getObject(String url);
}
TMDB:
public class TMDB implements IWebService<Movie> {
private JsonParser<Movie> m_jsonParser;
private Movie _movie;
public TMDB(JsonParser<Movie> jsonParser){
m_jsonParser = jsonParser;
}
#Override
public Movie getObject(String url) {
try {
HttpURLConnection _connection = (HttpURLConnection) (new URL(url)).openConnection();
_connection.setRequestMethod(Settings.CONNECTION_GET_METHOD);
_connection.setConnectTimeout(Settings.CONNECTION_TIMEOUT);
_connection.setReadTimeout(Settings.DATA_READ_TIMEOUT);
_connection.connect();
InputStreamReader _streamReader = new InputStreamReader(_connection.getInputStream());
BufferedReader _bufferedReader = new BufferedReader(_streamReader);
StringBuilder _data = new StringBuilder();
String _line;
while((_line = _bufferedReader.readLine()) != null ){
_data.append(_line);
}
_bufferedReader.close();
_streamReader.close();
Gson _gson = new Gson();
_movie = _gson.fromJson(_data.toString(), Movie.class);
}
catch(MalformedURLException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
return _movie;
}
}
AppExecuters singleton class for managing threads:
public class AppExecuters {
private static AppExecuters m_singltonInstance;
private Executor m_NetworkIO;
private Executor m_diskIO;
private Executor m_mainThread;
private static final Object LOCK = new Object();
private AppExecuters(Executor diskThread, Executor networkThread, Executor mainThread){
this.m_diskIO = diskThread;
this.m_mainThread = mainThread;
this.m_NetworkIO = networkThread;
}
public static AppExecuters getInstance(){
if(m_singltonInstance == null){
// In-order to make the singleton instance synchronized between all threads.
synchronized (LOCK){
m_singltonInstance = new AppExecuters(Executors.newSingleThreadExecutor(), Executors.newFixedThreadPool(3), new MainThread());
}
}
return m_singltonInstance;
}
public Executor networkIO(){
return m_NetworkIO;
}
public Executor diskIO(){
return m_diskIO;
}
public Executor mainThread(){
return m_mainThread;
}
private static class MainThread implements Executor{
private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
#Override
public void execute(Runnable command) {
mainThreadHandler.post(command);
}
}
}
I also need to know the best practice for managing
threads in such case.

Adding Java final keyword to working method that builds instances inside a loop

Take the following POJOs:
public class Widget {
private String fizz;
private Long buzz;
private List<Fidget> collaborators;
// Constructor, getters & setters
}
public class Fidget {
private String fizz;
private String foo;
// Constructor, getters & setters
}
And the following (working) method:
public void compriseWidgets(List<Fidget> fidgetList) {
List<Widget> widgets = new ArrayList<Widget>();
Widget currentWidget = null;
for (Fidget fidget : fidgetList) {
if (currentWidget == null ||
!currentWidget.getFizz().equals(fidget.getFizz())) {
currentWidget = new Widget();
widgets.add(currentWidget);
currentWidget.setFizz(fidget.getFizz());
currentWidget.setBuzz(fidget.getFoo().length());
}
currentWidget.getCollaborators().add(fidget);
}
return widgets;
}
Here we want to return a List<Widget> and populate that list only:
From the first Fidget in the input list (hence currentWidget == null); and
If the Fidget and currentWidget have the same fizz value
Furthermore, we want to keep appending collaborators to the currentWidget regardless of whether the fizzes match or not.
My problem
A new code style guideline is requiring that we declare ALL variables with final...meaning I need to get the above code refactored to look like so:
public void compriseWidgets(final List<Fidget> fidgetList) {
final List<Widget> widgets = new ArrayList<Widget>();
final Widget currentWidget = null;
for (final Fidget fidget : fidgetList) {
...
}
return widgets;
}
Because it requires both the creation of a new Widget inside the loop, but an external (outside the loop) reference to a Widget that we can add collaborators to, I'm at a total loss for how to rewrite this with final. Any ideas? Also, please note, this is nothing that I can "push back" on, I just need to figure it out and get it working with the new coding standard.
To expand on my comment, you could convert your example code more or less mechanically, like so:
public List<Widget> compriseWidgets(final List<Fidget> fidgetList) {
final List<Widget> widgets = new ArrayList<Widget>();
final Widget[] currentWidget = new Widget[] {null};
for (final Fidget fidget : fidgetList) {
if (currentWidget[0] == null ||
!currentWidget[0].getFizz().equals(fidget.getFizz())) {
currentWidget[0] = new Widget();
widgets.add(currentWidget);
currentWidget.setFizz(fidget.getFizz());
currentWidget.setBuzz(fidget.getFoo().length());
}
currentWidget.getCollaborators().add(fidget);
}
return widgets;
}
Many variables can be made final without any particular impact, including the lists of Fidgets and Widgets, and the loop variable in the enhanced for loop. The only other variable in the original method was currentWidget, which the implementation modifies. This can be replaced with a (final) array of length 1, whose zeroth element can then be used as a drop-in replacement for the original variable.
A more troublesome requirement along the same lines would be that you may not use assignment statements (initializers in variable declarations not being considered "assignments"). This is pushing toward a more functional style of programming, which I suppose may be the intent of your new guideline. You might, then, approach it something like this:
public List<Widget> compriseWidgets(final List<Fidget> fidgetList) {
final List<Widget> widgets = new ArrayList<Widget>();
final ListIterator<Fidget> fidgets = fidgetList.listIterator();
while (addWidget(widgets, fidgets)) { /* empty */ }
return widgets;
}
private boolean addWidget(final List<Widget> widgets, final ListIterator<Fidget> fidgets) {
if (fidgets.hasNext()) {
final Fidget firstFidget = fidgets.next();
final Widget currentWidget = new Widget();
widgets.add(currentWidget);
currentWidget.setFizz(firstFidget.getFizz());
currentWidget.setBuzz(firstFidget.getFoo().length());
currentWidget.getCollaborators().add(firstFidget);
while (fidgets.hasNext()) {
final nextFidget = fidgets.next();
if (currentWidget.getFizz().equals(nextFidget.getFizz())) {
currentWidget.getCollaborators().add(nextFidget);
} else {
fidgets.previous();
return true;
}
}
}
return false;
}
This is pretty much the same trick, just a little less obvious. The mutable state is hidden in the call stack (each invocation of addWidget() stands in for a mutation of the original method's currentWidget()) and in a container object, this time a ListIterator.
One could go further in the functional programming direction. In general, for example, you could look toward Stream-based approaches, though I don't think that works out completely cleanly in this particular case. More general functional programming does not have the constraints that apply to Streams, however.
The Builder design pattern is a great way to build immutable objects.
Source:
https://stackoverflow.com/a/15461337/4245294
What I love about this version of this design pattern is how it gives you the perfect spot for validation rules before object creation.
Example applied to this problem:
public class Widget {
private final String fizz;
private final Long buzz;
private final List<Fidget> collaborators;
private Widget(Builder builder) {
this.fizz = builder.fizz;
this.buzz = builder.buzz;
this.collaborators = builder.collaborators;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String fizz;
private Long buzz;
private List<Fidget> collaborators = new ArrayList<>();
public Builder addFizz(String fizz) {
this.fizz = fizz;
return this;
}
public Builder addBuzz(Long buzz) {
this.buzz = buzz;
return this;
}
public Builder addCollaborators(List<Fidget> fidgets) {
collaborators.addAll(fidgets);
return this;
}
public Builder addCollaborator(Fidget fidget) {
collaborators.add(fidget);
return this;
}
private void validate() throws InvalidArgumentException{
ArrayList<String> invalidArguments = new ArrayList<>();
boolean failedValidation = false;
if (collaborators.isEmpty()) {
invalidArguments.add("collaborators");
failedValidation = true;
}
if (this.fizz == null) {
invalidArguments.add("fizz");
failedValidation = true;
}
if (this.buzz == null) {
invalidArguments.add("buzz");
failedValidation = true;
}
if (failedValidation) {
throw new InvalidArgumentException(invalidArguments.toArray(new String[0]));
}
}
public Widget build() {
validate();
return new Widget(this);
}
}
}
And you create a valid Widget object like so:
Widget widget = Widget.builder().addFizz("test").addBuzz(999).addCollaborators(fidgets).build();
Your compriseWidget method has problems that I mentioned in a comment to the Question, otherwise I would provide an example for that as well.

Akka: Testing Supervisor Recommendations

I am very new to Akka and using Java to program my system.
Problem definition
- I have a TenantMonitor which when receives TenantMonitorMessage(), starts a new actor DiskMonitorActor.
- The DiskMonitorActor may fail for various reasons and may throw DiskException. The DiskMonitorActor has been Unit Tested.
What I need?
- I want to test behavior TenantMonitorActor, so that when DiskException happens, it takes correct action like stop(), resume() or any (depending upon what my application may need)
What I tried?
Based on the documentation, the closest I could perform is the section called Expecting Log Messages.
Where I need help?
- While I understand the expecting the correct error log is important, it just asserts first part, that exception is thrown and is logged correctly, but does not help in asserting that right strategy is called
Code?
TenantMonitorActor
public class TenantMonitorActor extends UntypedActor {
public static final String DISK_MONITOR = "diskMonitor";
private static final String assetsLocationKey = "tenant.assetsLocation";
private static final String schedulerKey = "monitoring.tenant.disk.schedule.seconds";
private static final String thresholdPercentKey = "monitoring.tenant.disk.threshold.percent";
private final LoggingAdapter logging = Logging.getLogger(getContext().system(), this);
private final Config config;
private TenantMonitorActor(final Config config) {
this.config = config;
}
private static final SupervisorStrategy strategy =
new OneForOneStrategy(1, Duration.create(1, TimeUnit.SECONDS),
new Function<Throwable, Directive>() {
public Directive apply(final Throwable param) throws Exception {
if (param instanceof DiskException) {
return stop();
}
return restart();
}
});
public static Props props(final Config config) {
return Props.create(new Creator<TenantMonitorActor>(){
public TenantMonitorActor create() throws Exception {
return new TenantMonitorActor(config);
}
});
}
#Override
public void onReceive(final Object message) throws Exception {
if (message instanceof TenantMonitorMessage) {
logging.info("Tenant Monitor Setup");
setupDiskMonitoring();
}
}
#Override
public SupervisorStrategy supervisorStrategy() {
return strategy;
}
private void setupDiskMonitoring() {
final ActorRef diskMonitorActorRef = getDiskMonitorActorRef(config);
final FiniteDuration start = Duration.create(0, TimeUnit.SECONDS);
final FiniteDuration recurring = Duration.create(config.getInt(schedulerKey),
TimeUnit.SECONDS);
final ActorSystem system = getContext().system();
system.scheduler()
.schedule(start, recurring, diskMonitorActorRef,
new DiskMonitorMessage(), system.dispatcher(), null);
}
private ActorRef getDiskMonitorActorRef(final Config monitoringConf) {
final Props diskMonitorProps =
DiskMonitorActor.props(new File(monitoringConf.getString(assetsLocationKey)),
monitoringConf.getLong(thresholdPercentKey));
return getContext().actorOf(diskMonitorProps, DISK_MONITOR);
}
}
Test
#Test
public void testActorForNonExistentLocation() throws Exception {
final Map<String, String> configValues =
Collections.singletonMap("tenant.assetsLocation", "/non/existentLocation");
final Config config = mergeConfig(configValues);
new JavaTestKit(system) {{
assertEquals("system", system.name());
final Props props = TenantMonitorActor.props(config);
final ActorRef supervisor = system.actorOf(props, "supervisor");
new EventFilter<Void>(DiskException.class) {
#Override
protected Void run() {
supervisor.tell(new TenantMonitorMessage(), ActorRef.noSender());
return null;
}
}.from("akka://system/user/supervisor/diskMonitor").occurrences(1).exec();
}};
}
UPDATE
The best I could write is to make sure that the DiskMonitor is stopped once the exception occurs
#Test
public void testSupervisorForFailure() {
new JavaTestKit(system) {{
final Map<String, String> configValues =
Collections.singletonMap("tenant.assetsLocation", "/non/existentLocation");
final Config config = mergeConfig(configValues);
final TestActorRef<TenantMonitorActor> tenantTestActorRef = getTenantMonitorActor(config);
final ActorRef diskMonitorRef = tenantTestActorRef.underlyingActor().getContext()
.getChild(TenantMonitorActor.DISK_MONITOR);
final TestProbe testProbeDiskMonitor = new TestProbe(system);
testProbeDiskMonitor.watch(diskMonitorRef);
tenantTestActorRef.tell(new TenantMonitorMessage(), getRef());
testProbeDiskMonitor.expectMsgClass(Terminated.class);
}};
}
Are there better ways?
I have the feeling that testing supervisor strategy is some sort of grey area -- it is up to personal opinion where we start testing Akka itself, instead of one's understanding of how the framework works. Testing validation of entities in ORM frameworks strikes me as a similar problem. We don't want to test whether email validation logic is correct (e.g. in Hibernate), but rather if our rule is correctly declared.
Following this logic, I would write the test as follows:
final TestActorRef<TenantMonitorActor> tenantTestActorRef =
getTenantMonitorActor(config);
SupervisorStrategy.Directive directive = tenantTestActorRef.underlyingActor()
.supervisorStrategy().decider().apply(new DiskException());
assertEquals(SupervisorStrategy.stop(), directive);

Lazy initialization of static variables in Java - execute around?

That's how I do it (android code)
private volatile static WifiManager wm;
private static WifiManager wm(Context ctx) {
WifiManager result = wm;
if (result == null) {
synchronized (WifiMonitor.class) { // the enclosing class
result = wm;
if (result == null) {
result = wm = (WifiManager) ctx
.getSystemService(Context.WIFI_SERVICE);
if (result == null) throw new WmNotAvailableException();
}
}
}
return result;
}
Bloch in Effective Java recommends :
// Lazy initialization holder class idiom for static fields
private static class FieldHolder {
static final FieldType field = computeFieldValue();
}
static FieldType getField() {
return FieldHolder.field;
}
This has the advantages of dispensing with the synchronization and that the JVM optimizes out the field access. The problem is that I need a Context object in my case. So :
Is there a way to adapt Bloch's pattern to my case (computeFieldValue() needs a param) ?
If not, is there a way to execute around ? The code is subtle and I'd rather have it in one place and pass only required behavior in
Last but not least - is there a way to enforce access to the cache field (wm) only via the wm() method ? So I can avoid NPEs and such. Other languages use properties for this
You can do the following
static int param1;
static String param2;
public static void params(int param1, String param2) {
this.param1 = param1;
this.param2 = param2;
}
private static class FieldHolder {
static final FieldType field = new FieldType(param1, param2);
}
static FieldType getField() {
return FieldHolder.field;
}
Note: even simpler than this is to use an enum,
enum Singleton {
INSTANCE;
}
or
class SingletonParams {
static X param1;
}
enum Singleton implements MyInterface {
INSTANCE(SingletonParams.param1, ...);
}

Categories

Resources