I am writing a graphics program however I am having trouble calling for the thread to start in the main and getting it to run in the separate class. My main class looks like the following..
package shooter;
import java.awt.Color;
import javax.swing.JFrame;
public class ShooterRunner extends JFrame {
public ShooterRunner()
{
super("Shooter Game");
setSize(600,600);
setBackground(Color.black);
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
getContentPane().add(new Shooter());
setFocusable(true);
setVisible(true);
}
public static void main(String[] args) {
ShooterRunner test = new ShooterRunner();
Thread thread = new Thread(new Shooter());
}
}
I am aware that I am creating a new instance of shooter when I create the thread however I get an error if I try create a Shooter object above and use it for both getContentPane.add() and as the parameters of creating the thread.
Related
here is a sample source code of vala for creating a simple GTK application from elementary os website
public class Examples.Application : Gtk.Application {
public Application () {
Object (
application_id: "org.valadoc.examples",
flags: ApplicationFlags.FLAGS_NONE
);
}
protected override void activate () {
var application_window = new Gtk.ApplicationWindow (this);
application_window.show_all ();
}
public static int main (string[] args) {
var app = new Application ();
return app.run (args);
}
}
i dont understand th object in this code? what is it? is it an object ? if its an object so why it has not new keword and not instanciated?
The Object() you see there in the constructor is a Vala-specific syntax called: GObject-style construction. It allows you to set your properties all at once.
This allows you to work with GObject's so-called "construct properties": properties which can be set during construction (sometimes they can even only exclusively be set during construction).
I'm working on a game and I'm trying to add a JPanel to the JFrame. I have a separate class which extends JPanel and I create a new object which again, extends JPanel.
However, I get this error: "The method add(Component) in the type Container is not applicable for the arguments (mainMenu)" (mainMenu is the class which extends JPanel).
It suggests adding an argument to match 'add(Component, Object)'
I am at a loss in trying to fix this especially because later in my code, I use the same add argument to add an object whose class extends a JButton. Any help is greatly appreciated.
I have tried creating a regular JPanel and adding that which worked.
(JFrame class)
public class gardenRunner extends JFrame {
public static void run(String[] args)
{
new gardenRunner()
}
public void gardenRunner()
{
mainMenu m = new mainMenu();
add(m); <-- gives error
}
(JPanel class)
public class mainMenu extends JPanel {
public mainMenu()
{
super();
setSize(60, 60);
}
I would expect this to add a JPanel to my JFrame but this results in an error.
Thanks for the help, turns out Eclipse was acting a little buggy and this worked when I deleted my JPanel class and made a new one. Thanks again.
I am curious about whether mapreduce job is using multiple threading in a single machine. For example, I have 10 servers in the hadoop cluster, by default, if the input file is large enough, there will be 10 mappers. Is the single mapper using multiple threading in a single machine?
Is the single mapper using multiple threading in a single machine?
YES. Mapreduce job can use multithreaded mapper(Multiple threads or thread pool running map method) .
I have used for better CPU utilization for Map only Hbase jobs...
MultiThreadedMapper is a good fit if your operation is highly CPU intensive, could increase the speed.
mapper class should extend org.apache.hadoop.mapreduce.lib.map.MultithreadedMapper instead of regular org.apache.hadoop.mapreduce.Mapper .
The Multithreadedmapper has a different implementation of run()
method. like below.
run(org.apache.hadoop.mapreduce.Mapper.Context context)
Run the application's maps using a thread pool.
You can set the number of threads within a mapper in MultiThreadedMapper by
MultithreadedMapper.setNumberOfThreads(n); or you can set the property in loading from a property file mapred.map.multithreadedrunner.threads = n
and use above setter method(per job basis) to control jobs which are less cpu intensive.
The affect of doing this, you can see in mapreduce counters specially CPU related counters.
Example Code snippet of MultithreadedMapper implementation:
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.map.MultithreadedMapper;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.lib.output.MultipleOutputs;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import java.io.IOException;
import java.util.regex.Pattern;
public class MultithreadedWordCount {
// class should be thread safe
public static class WordCountMapper extends Mapper<LongWritable, Text, Text, LongWritable> {
public static enum PREPOST { SETUP, CLEANUP }
#Override()
protected void setup(Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws java.io.IOException, java.lang.InterruptedException {
// will be called several times
context.getCounter(PREPOST.SETUP).increment(1);
}
#Override
protected void map(LongWritable key, Text value,
Context context) throws IOException, InterruptedException {
String[] words = value.toString().toLowerCase().split("[\\p{Blank}[\\p{Punct}]]+");
for (String word : words) {
context.write(new Text(word), new LongWritable(1));
}
}
#Override()
protected void cleanup(Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws java.io.IOException, InterruptedException {
// will be called several times
context.getCounter(PREPOST.CLEANUP).increment(1);
}
}
public static class WordCountReducer extends Reducer<Text, LongWritable, Text, LongWritable> {
#Override
protected void reduce(Text key, Iterable<LongWritable> values, Context context
) throws IOException, InterruptedException {
long sum = 0;
for (LongWritable value: values) {
sum += value.get();
}
context.write(key, new LongWritable(sum));
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
Job job = new Job();
job.setJarByClass(WordCount.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
MultithreadedMapper.setMapperClass(job, MultithreadedWordCount.WordCountMapper.class);
MultithreadedMapper.setNumberOfThreads(job, 10);
job.setMapperClass(MultithreadedMapper.class);
job.setCombinerClass(MultithreadedWordCount.WordCountReducer.class);
job.setReducerClass(MultithreadedWordCount.WordCountReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(LongWritable.class);
/* begin defaults */
job.setInputFormatClass(TextInputFormat.class);
job.setOutputFormatClass(TextOutputFormat.class);
/* end defaults */
job.waitForCompletion(true);
}
}
Please refer https://hadoop.apache.org/docs/r2.6.3/api/org/apache/hadoop/mapreduce/Mapper.html
Applications may override the run(Context) method to exert greater control on map processing e.g. multi-threaded Mappers etc.
Moreover there is also a MultithreadedMapper . I have never used this though.
I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?
It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.
I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}
It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.
I have a project that contains some forms, class and Method. Some methods have a lot of process and I do threading on method, which works OK.
So, how can I do Multi threading or Parallel Processing on GUI of my forms?
I do this because when method being running as a GUI (like forms and another control) it is slow.
I wrote this code in Program class but have problems:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Threading;
namespace WindowsFormsApplication1
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Parallel.Do(
delegate()
{
job();
}
);
}
public delegate void mydelegate();
private static void job()
{
try
{
Application.Run(new frmMain());
}
catch
{
}
}
}
}
How can I speed this up using multi threading or parallel processing?
I would recommend taking a look at the BackgroundWorker Class
Have a look at the Task Class.
// Declare Task Object.
Task t = new Task(Job);
//Start another Task to do the job.
t.Start()
(...)
// Task ended
t.ContinueWith(task =>
(.. process result if there is any ..)
);