New answers tagged

1

Availability. There's already a comment that says something similar, but I also answered a similar question about NuGet (.NET's package manager) a few months ago: Should we include Nuget PACKAGE folder in version control? I'm not a Java guy and I don't know Maven, but to me it sounds like it's similar to NuGet: a central package repository where ...


0

This could be a good strategy for a search algorithm. Supose you have recursive algorithm that performs very deep searches. When you found the element that satisfies your search criteria you can just throw an "OnFoundEvent". If you found nothing, you can throw an "OnNotFoundEvent". With this technique you skip all the backtracking mechanism caused by the ...


1

While it is faster to type a call chain like this can be difficult to understand. The optimizer will quickly optimize back to the call chain, but provide a better failure stack. It is better to code for readability. As shown below coding with one function call per line yields your answer. From the Javadoc of BigInteger. static BigInteger ...


3

History. Many of the best practices of computer science are a moving target. Thus any time you work with old code you are working with old ideas. If you ever manage to write code that lasts over a decade you may find yourself explaining why you didn't use foo testing, bar management, or baz omniscience. If you think you know better feel free to fork it, ...


1

Use a Map Map<int, ClientThread> threads = new HashMap<>(); Add thread to map ClientThread thread = new ClientThread(socket); threads.put(thread.serverUniqueId, thread); Remove a thread threads.remove(id); Get a thread by id theads.get(id); Get threads by multiple ids int[] ids = {1,2,3,4}; for (Map.Entry<Integer, ClientThread> ...


1

If you want to find something in an unordered array, iterating over it is the fastest thing you can do. You should store the Sockets in a HashMap. You can put in the id and get the corresponding Socket in constant time.


3

It's largely a matter of personal preference, although some places may make it a formal coding standard. C itself doesn't care. For my part, if I'm defining multiple functions in a single source file, I will define the called functions before the caller: void foo( void ) { ... } void bar( void ) { ... foo(); ... } int main( void ) { ... ...


1

The best place is somewhere that people can find it. In the middle of a very large file is bad. At the top is good, but others might prefer right at the bottom. Forward declaring main() doesn't help, and is often pointless anyway - because it's very unusual to explicitly call main() from within your code.


0

In considering the right approach you should think about how the input data might change over time and where the ultimate source of truth is for that data. For example if it's a list of employees then what happens if a new hire comes on board. Does someone then send an updated CSV file to you, or would you expect (in a future version) to be accessing a ...


1

I'd normally expect you to have some sort of model object separate to the controller. That would manage the handling of your data and perhaps delegate to some sort of persistence layer (a DAO or data access object). Your DAO may well support some sort of query type mechanism e.g. Person getPersonByName(String name); List<Person> getPersons(); etc. (...


0

In layman's terms: I'd suggest you put it in the same package as the class whose method, having initially such a long signature, originated the need for such a paramter object. Parameter classes are classes nonetheless are they belong to the package where the rest of related classes are located. It doesn't matter whether or not they have behavior whichm by ...


1

The same problems exist with a single server too. What if two users connected to the same server update the same balance at the same time? What if the same user opens two tabs in the browser, or two different browsers, or simply connects from two devices such as a PC and a smartphone, at the same time? What happens more often that the application performs ...


0

There are a few things you should ask for: Source code (obviously). This should include any unit tests and integration tests. Complete documentation on the build process, all the way through to delivery of the binaries to the app stores. This should be demonstrated and possibly video'd Any and all keys or accounts necessary to upload the code to the ...


0

I had the same request, and found these references that could help you. Java + MongoDB + Elastic Search = River Plugin you can find at https://github.com/richardwilly98/elasticsearch-river-mongodb/wiki And if you are really going to have a gorgeous amount of data to manage, so please read this interesting experience and the conclusion of the Quark'sLab : ...


2

Function contract comments should be in javadoc comments rather than plain comments (i.e. comments beginning with /**). Many syntax-highlighting editors are able to highlight these with a different colour to other comments (e.g. eclipse). File history/copyright/licence comments should be confined to the top of the file. Work-in-progress/task-related ...


7

You could try creating Custom JavaDoc Tags. Your design decisions could have an @why tag or something. I've always thought comments that answer the question "Why?" tend to be the most useful. That said, I agree with @JohnBode and @BobDalgleish that you don't want to paste pages of your design docs into your code, but an abbridged "TL;DR" summary of those ...


1

I do like David Packer's answer on your other question. But to distill it a bit more: Some Business Logic on front end to reduce round trips. But all Business Logic on back end (which, yes, means you will have duplicated business logic) Also, forget about how difficult or not is to implement it on a language. You are taking an architectural decision ...


1

Suppressing warning for an entire method is suspect. Better to suppress the warnings for the specific line, with a comment. e.g. @SuppressWarnings("unchecked") Foo foo = (Foo)object; // Using old library requires this cast


1

If you are using a database which supports transactions, then just upload the components in the same transaction. They won't be visible to the application until the transaction is committed, which will be an atomic event. Search for "database ACID" for more details. Alternatively, ensure all the resources for the page are in place before adding the HTML ...


8

Whenever two or more threads need to change the same object and potentially at the same time, you need to ensure that the object remains in a consistent state making it synchronized. Apparently, it's not only about the object, but also its containing object, because you mention "if the user made a change to an object while the tick was deleting it". ...


0

I totally agree with statements 1, 2, 3. I also never use block initializers for these reasons and I don't know why it exists in Java. However, I'm forced to use the static block initializer in one case: when I have to instantiate a static field whose constructor can throws a checked exception. private static final JAXBContext context = JAXBContext....


2

Confusing Syntax Looking at this question, there are 3 answers, yet you fooled 4 people with this syntax. I was one of them and I've been writing Java for 16 years! Clearly, the syntax is potentially error prone! I'd stay away from it. Telescoping Constructors For really simple stuff, you can use "telescoping" constructors to avoid this confusion: ...


3

It seems like a batcher. So you could name it like this. public class HeavyWorkBatch { ArrayList<File> myList = new ArrayList<>(); public void AddToBatch(File f) { myList.add(f); } public void DoHeavyWork() { for (File f: myList) { /// ... } } } // Note there is a conspicuous lack of ...


1

As fas as non-static initializer blocks are concerned, their bare function is to act as a default constructor in anonymous classes. That is basically their only right to exist.


0

I don't know what kind of objects you are serializing, but generally speaking, a binary serialization, combined with something like LZ4 compression, makes much more sense than JSON.


1

You can handle exception explicitly in controller method where possible by using @ResponseStatus, @ExceptionHandler, @ControllerAdvice annotation. For more detail please refer : Exception Handling in spring MVC.


4

C++ doesn't have a manual approach to memory management at all. If you're calling free in C++, you're using it wrong. That's the C way that we're proud to be disowning. Really, the predominant models are non-deterministic (GC), deterministic (C++, D), and manual (C).


1

This question states an incorrect premise as fact, then makes an argument about that incorrect premise. Lets dig in to this .. "all their design points to minimizing GC use" - simply isn't true. The innovation in the disruptor has little to do with GC. The disruptor performs because its design cleverly considers how modern computers work - something that's ...


0

Joachim Sauer already did a good job answering you question but only hinted at something I regard as important. Since Lambdas are no classes they are also not compiled as such. All anonymous inner classes result in the creation of a .class file which in turn has to be loaded by the ClassLoader. So using Lambdas instead does not only make your code more ...


2

I'd suggest Threads. Threads are "lighter" than full-blown Processes and Java has far better tools for managing the interactions with/ between Threads than it has for Processes. BTW, if you were to use the script as you described it, your processes would run sequentially, one after the other. You'd need some way of telling your operating system to start ...


10

Suppressing warnings is something that needs to be done with extreme care. A warning means: The compiler found something that looks dodgy. It doesn't mean it is dodgy, it just looks like it to the compiler. Sometimes you have code that is perfectly fine and gives a warning. Sometimes you fix it by slightly modifying your code. Sometimes the compiler has ...


11

To me, the entire point of suppressing warnings is to maintain a "clean bill of health" for your project. If you know that your entire code base compiles cleanly, it's immediately obvious when someone does something wrong that causes the first warning to appear in the issues list. You can then fix the error or suppress it if you can prove that it's spurious. ...


1

I believe a multithreaded approach would be the best one. Also have you thought of using a mix of the two? Launch an application (manager) responsible for managing which files to process and their progress, to process each file you'd then launch the generic processing application in a separate process, a little bit like how browsers work today. This way ...


1

Using CDI injection and JPA together isn't coupling, it's just what they used for dependency injection, AoP, and persistence (JPA). JSF (JavaServer Faces) is a Java specification for building component-based user interfaces for web applications. jax-rs just lets you support REST as a service. websocket is old school TCP in both directions. You've ...


2

I didn't design or write Java's Date-Time API, so I can't definitively say "why did they do it this way." I can however suggest two key reasons they should do it this way: Expressive power Parallel form First, consider the context: Java's dates and time code is a large, complex package dealing with a very tricky subject matter. As common as "time" is, ...


1

The proper HTTP error code on input is 400: Bad Request. In the response you could go with 500. If there is an error in marshalling or unmarshalling, an exception will be thrown which you can handle by registering an ExceptionMapper (scoll down to the Exception Mapping section). You can then determine what kind of error to throw. The JAX-RS package has a ...


7

Factory methods allow simplifying the constructors - the difference which instance in time is represented by the Object can be separated from the calculation of the instant. There are lots of factory methods, some doing String parsing, some converting from some other date or time representation, but all that can happen before the Object has to be created (...


3

You should return a 404. You can do it by throwing a NotFoundException (https://jersey.java.net/apidocs/2.6/jersey/javax/ws/rs/NotFoundException.html). Also please look at this SO question if you need to control the returned content type http://stackoverflow.com/questions/23858488/how-i-return-http-404-json-xml-response-in-jax-rs-jersey-on-tomcat


6

It's not always necessary to create a new object when obtaining a value of an immutable type. A factory method may return an object that has already been created while a constructor call always creates a new object. There are some other advantages to factory methods, but they're not as closely related to immutability and the Date-Time API. For instance, ...


4

HTTP 204 means that something was found, but it's empty. For instance, imagine that you're serving log files through HTTP, with the requests such as http://example.com/logs/[date-goes-here]. On May 18th, 2015: http://example.com/logs/2015-05-19 would return HTTP 404, which means that there are no logs, because, well, it's difficult to log the future. http:/...


1

Assumed you need a generic solution, where the program is not tied to a specific column structure at run time, you can use an ArrayList of rows, where each row is a string array String[]. You will need an additional HashTable<String,int> to store the mapping of the column name to the column index (a HashMap will probably work, either). So if you have ...


0

If you need performance, you probably need Arrays to hold column values, else 1. you will have memory overhead and 2. accessing lower rows will be slow. Columns can be either a Hashmap (name -> Array) or directly Object fields (the latter one is preferable but requires fields and types to be statically known). This would be the basic, column-based answer ...


3

Use database connection pooling. I don't recommend writing your own. Here's an explanation on StackOverflow. You can use c3p0 or read up more on your own by searching for "connection pooling."


2

Something that I don't think has been mentioned here is that there are efficiencies that come from garbage collection. In the most commonly used Java collectors, the main place that objects are allocated is an area reserved for a copying collector. When things start, this space is empty. As objects are created, they are allocated next to each other in the ...


3

What is the role of “throws exeption” It's used for checked exceptions. The idea is, if you write code to call a function that throws FoobarException, then the compiler will force you to either handle the exception, or to add the same throws FoobarException declaration to the function that you are writing. It's a way to make sure that nobody will forget ...


2

The big difference that garbage collection makes isn't that you don't have to explicitly delete objects. The much bigger difference is that you don't have to copy objects. This has effects that become pervasive in designing programs and interfaces in general. Let me give just one tiny example to show how far-reaching this is. In Java, when you pop ...


1

It doesn't say much in the Javadocs about how this is implemented in the compiler, nor does it for the equivalent NotImplementedException in C#. However, it wouldn't surprise me if the compiler's static code analysis went something like this: an exception is thrown unconditionally before return is called, so there's no need to check the return type. When ...


4

This: new Runnable(){ public void run(){ ...statements } } (in Java) is called an anonymous class. You're creating a new class definition + instance deriving from the Runnable interface, and providing the run() method. It's anonymous, since it's not named, and you can't re-use that definition elsewhere.


0

The most common way to use a SOCKS proxy server in the Linux world is to do so via a shared library that intercepts calls to standard socket functions and redirects them to the proxy server. This does not allow multiple connections to different servers, however (except by configuring different servers for different addresses, but that doesn't seem to be ...


2

Here is a good explaination on differentiating association, aggregation, and composition. But here's a thing. If you try to show everything your system is capable of (or every description of your system) on the same diagram, you're going to run out of relationships, or end up reusing the relationship kinds with widely different meaning on the same diagram. ...



Top 50 recent answers are included