-2

I am planning to program a java code editor using Swing and the main feature is highlighting code segments like keywords , strings and variables. I need some suggestions on how i should implement the program, one of my friend told to use 2 separate threads, one for editing and one for highlighting the code, but how to establish communication between those 2 threads ?

if i don't use separate threads, will it have any impact on my program ?

I'm really confused. Please help me, with some suggestions .

EDIT: ONe more Question Should i use a JEditorPane or a JTextPane for this purpose ?

cyberpirate92
  • 3,076
  • 4
  • 28
  • 46
  • 1
    If I remember correctly, not all of swing/a majority of it is thread safe.... is that still the case? – roguequery Jun 29 '13 at 04:39
  • 1
    i think so , that's why they use the SwingUtilities,invokeLater() fn – cyberpirate92 Jun 29 '13 at 04:42
  • 1
    I would advise aginst trying this in swing, no reason to. I think a better route would be as a web app, so you could iterate on it quickly and get a lot of followers, kind of like collabedit or cloud9, but java-specific. – roguequery Jun 29 '13 at 04:43
  • 1
    Also see [this](http://stackoverflow.com/questions/14229611/code-completion-and-syntax-highlighting-in-swing/14230233#14230233) answer for some help on the specific elements i.e syntax highlighting and auto suggestions – David Kroukamp Jun 29 '13 at 08:27

2 Answers2

2

Using separate threads will be an overhead. Best way in my view would be to use a single thread and as soon as text is edited you can parse it and highlight that based on your logic.

But if you are keen on having separate threads then you can create a separate highlighter thread [which will highlight keywords based on your logic] but the edited text wil have to be passed to it by your main thread so there wont be much gain unless your highlighting logic is very complex.

Lokesh
  • 7,810
  • 6
  • 48
  • 78
  • 1
    just wondering ... isn't there any way where i don't have to pass the text, like having a common class ?? – cyberpirate92 Jun 29 '13 at 04:49
  • 1
    There has to be a way for highlighter thread to know which text has been edited, so you should pass it [best way would be blocking queue] if you want to see text highlighting on the fly. Else you can have a crawling background thread can parse the text[based on some logic] in background and highlight the text. – Lokesh Jun 29 '13 at 05:01
  • as you said , looks like this would make things much worse. It seems i have to drop my idea of multithreading for this program. – cyberpirate92 Jun 29 '13 at 05:07
2

From the Docs

Swing object methods are not "thread safe": invoking them from multiple threads risks thread interference or memory consistency errors.

http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ravitheja
  • 142
  • 1
  • 8